PowerShell: How to Join an Array with newline

Often you may want to join the elements in an array using a newline in PowerShell.

You can use the following syntax with the Out-String cmdlet to do so:

$teams_new = $teams | Out-String

This particular example joins all of the elements from the array named $teams into a new array named $teams_new that uses a newline as the separator between elements.

This method works because the Out-String places each element of an array on its own line by default.

The following example shows how to use this syntax in practice.

Example: How to Join an Array with Newline in PowerShell

Suppose we create the following array named $teams that contains the names of various basketball teams:

$teams = @('Mavs', 'Lakers', 'Spurs', 'Nets', 'Celtics')

Suppose that we would like to join together all elements from this array, using a newline.

We can use the following syntax to do so:

$teams_new = $teams | Out-String

The following screenshot shows how to use this syntax in practice:

PowerShell join array with newline

Notice that the new array named $teams_new contains all values from the original array joined together by newlines.

Note: You can find the complete documentation for the Out-String cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Compare Two Arrays
PowerShell: How to Check if Input Value Exists in Array
PowerShell: How to Remove Duplicate Values from Array

Leave a Reply