2

I have encountered a PowerShell behavior I don't understand. A comma between strings concatenates them and inserts a space in between, e.g.:

PS H:\> [string]$result = "a","b"

PS H:\> $result # a string with 3 characters
a b

If the result is interpeted as an array, then using a comma separates the elements of the array, e.g.:

PS H:\> [array]$result = "a","b"

PS H:\> $result # an array with 2 elements
a
b

I have tried searching for an explanation of this behavior, but I don't really understand what to search for. In the documentation about the comma operator, I see that it is used to initialize arrays, but I have not found an explanation for the "string concatenation" (which, I suspect, may not be the correct term to use here).

mklement0
  • 382,024
  • 64
  • 607
  • 775
Developer
  • 435
  • 4
  • 16

1 Answers1

2

Indeed: , is the array constructor operator.

Since your variable is a scalar - a single [string] instance - PowerShell implicitly stringifies your array (converts it to a string).

PowerShell stringifies arrays by joining the (stringified) elements of the array with a space character as the separator by default.
You may set a different separator via the $OFS preference variable, but that is rarely done in practice.[1]

You can observe this behavior in the context of string interpolation:

PS> "$( "a","b" )"
a b

[1] As zett42 points out, an easier way to specify a different separator is to use the -join operator; e.g.,
"a", "b" -join '@' yields 'a@b'.
By contrast, setting $OFS without resetting it afterwards can cause later commands that expect it to be at its default to malfunction; with -join you get explicit control.

mklement0
  • 382,024
  • 64
  • 607
  • 775