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).

1
  • 2
    It's not the comma - it's the [string] constraint Commented Dec 4, 2020 at 14:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.