How to join String array into one String in PowerShell

While customizing results in PowerShell, there is a common need to convert a list of strings or an array of string items into a comma-separated string, or delimit by some other string such as semi-colon, space, underscore, etc.

In PowerShell, we can use the join operator (-join) to convert multiple strings into a single string. The join operator concatenates a set of strings into a single string. The strings are separated with a delimiter and appended into the result string.

The following command joins the array of strings into a single string as comma (,) separated values.

$ArrayOfStrings = @("a","b","c","d")
$JoinedString = $ArrayOfStrings -join ","

#Output
a,b,c,d

Join with a semi-colon delimiter

$ArrayOfStrings = @("a","b","c","d")
$ArrayOfStrings -join ";"

Join strings with space

$ArrayOfStrings = @("a","b","c","d")
$ArrayOfStrings -join " "

Enclose the string with quotes and join it with a comma

$ArrayOfStrings = @("a","b","c","d")
$JoinedString = '"' + ($ArrayOfStrings -join '","' ) + '"'

Likewise, you can use any delimiter character and combine the strings.

Concatenates a set of strings without using the join operator

The join operator can be used only with an array object. If you want to combine text from multiple string variables, then you can simply use the plus (+) operator to add values from multiple variables.

$StringVar1 = ”a”
$StringVar2 = ”b”
$Output1 = $StringVar1 + $StringVar2
#With separator 
$Output2 = $StringVar1 +”,”+ $StringVar2
Advertisement