PowerShell: How to Print Array Elements on One Line


Often you may want to print all of the elements in an array on one line in PowerShell.

The easiest way to do so is by using the -join operator to join together each of the elements in the array using a specific separator:

$my_array -join " "

This particular example will print all of the elements in the array named $my_array on one line, using a single space as the separator between the elements.

Note that you can use any separator between the elements, including no separator if you’d like.

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

Example: How to Print Array Elements on One Line in PowerShell

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

$my_array = @("Mavs", "Nets", "Hawks", "Kings")

If we simply type the name of this array into PowerShell, each element of the array will be shown on a new line:

To display each element of the array on the same line, we must use the -join operator as follows:

$my_array -join " "

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

PowerShell print array elements on one line

Notice that each of the elements in the array are now shown on the same line, separated by a single space between them.

Note that you could also use the following syntax to display each of the elements from the array on the same line with no separator between them:

$my_array -join ""

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

PowerShell display array elements on one line with no separator

Notice that each of the elements in the array are now shown on the same line with no separator between them.

Feel free to specify any separator that you’d like when using the -join operator.

Related Tutorials

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

PowerShell: How to Concatenate Strings
PowerShell: How to Append String to Each Item in Array
PowerShell: How to Get First Line of String in a Variable

Leave a Reply