Home ยป How to Convert Array to Comma Separated String

How to Convert Array to Comma Separated String

You can use multiple ways to convert an array to a comma-separated string in PowerShell.

The following methods show how you can do it with syntax.

Method 1: Using -join operator

$languages = @("PowerShell","Python","Java","C#")
$commaSeparatedString = $languages -join ","
Write-Output "Comma separated string is: $commaSeparatedString"

This example will convert the array into a comma-separated string using the -join operator.

Method 2: Using the Join() method

$languages = @("PowerShell","Python","Java","C#")
$commaSeparatedString = [string]::Join(",",$languages)
Write-Output "Comma separated string is: $commaSeparatedString"

This example will convert the array into a comma-separated string using the Join() method of the string class.

The following examples show how you can use these methods.

Convert Array to Comma Separated String Using -join Operator

You can the -join operator in PowerShell to convert the array to a comma-separated string.

# define an array
$languages = @("PowerShell","Python","Java","C#")

# use -join operator to convert array to comma separated string
$commaSeparatedString = $languages -join ","

# write the output
Write-Output "Comma separated string is: $commaSeparatedString"

Output:

PowerShell convert array to comma-separated string using -join operator
PowerShell convert array to comma-separated string using -join operator

In this PowerShell script, the $languages variable is an array that stores the programming languages. We then use the -join operator over the array variable $languages to convert them into a comma-separated string.

Finally, the comma-separated string is output to the console using the Write-Output cmdlet.

Convert Array to Comma Separated String Using Join() Method

Another way to convert an array to a comma-separated string is by using the Join() method of the string class.

# define an array
$languages = @("PowerShell","Python","Java","C#")

# convert array into comma-separated string
$commaSeparatedString = [string]::Join(",",$languages)

# write the output to console
Write-Output "Comma separated string is: $commaSeparatedString"

Output:

PowerShell convert array to comma-separated string using Join method
PowerShell convert array to comma-separated string using Join method

In this script, the $languages variable is an array that stores the programming languages. We then use the Join() method of the string class to convert an array into a comma-separated string.

Finally, the comma-separated string is output to the console using the Write-Output cmdlet.

Conclusion

I hope the above article on converting an array to a comma-separated string in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.