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
If a join is used on an empty array, the array.count is 1, is there a simple way to make the join conditional of content being in the array?
To elaborate:
$array = @() -join ‘|’
$array.count would result to: 1
If we were to view the output of this array, it would appear to be empty… but not it’s null, nor is it the pipe.
Actually your final result from join is string text, not array, so you have to use Length instead of count.
$arrayAsString = @() -join ‘|’
$arrayAsString.Length