PowerShell: How to Convert Array to Comma Separated String


Often you may want to convert an array to a comma separated string in PowerShell.

Here are two common ways to do so:

Method 1: Convert Array to Comma Separated String

$my_string = $my_array -join ","

This particular example converts the array named $my_array to a comma separated string named $my_string.

Method 2: Convert Array to Comma Separated String with Quotes

$my_string = "'$($my_array -join "','")'" 

This particular example converts the array named $my_array to a comma separated string named $my_string with quotes around each word in the string.

The following examples show how to use each method in practice.

Example 1: Convert Array to Comma Separated String in PowerShell

Suppose we have an array named $my_array that contains 4 items.

We can use the following syntax to create this array, then convert it into a comma separated string:

$my_array = 'one', 'two', 'three', 'four'
$my_string = $my_array -join ","

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

PowerShell convert array to comma separated string

We can see that the array has been converted to a comma-separated string.

We can verify that $my_array is an array and that $my_string is a string by using GetType() for each variable:

$my_array.GetType()
$my_string.GetType()

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

We can see that $my_array has a BaseType of an array while $my_string has a BaseType of object with a data type of String.

Example 2: Convert Array to Comma Separated String with Quotes in PowerShell

Once again suppose we have an array named $my_array that contains 4 items.

We can use the following syntax to create this array, then convert it into a comma separated string with quote around each individual word in the string:

$my_array = 'one', 'two', 'three', 'four'
$my_string = "'$($my_array -join "','")'"

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

PowerShell convert array to comma separated string with quotes

We can see that the array has been converted to a comma-separated string with quotes around each individual word in the string.

Related Tutorials

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

PowerShell: How to Convert String to Double
PowerShell: How to Convert String to Datetime
PowerShell: How to Split String into Separate Variables

Leave a Reply