PowerShell outputting array items when interpolating within double quotes

I found some strange behavior in PowerShell surrounding arrays and double quotes. If I create and print the first element in an array, such as:

$test = @('testing')
echo $test[0]

Output:
testing

Everything works fine. But if I put double quotes around it:

echo "$test[0]"

Output:
testing[0]

Only the $test variable was evaluated and the array marker [0] was treated literally as a string. The easy fix is to just avoid interpolating array variables in double quotes, or assign them to another variable first. But is this behavior by design?


Solution 1:

So when you are using interpolation, by default it interpolates just the next variable in toto. So when you do this:

"$test[0]"

It sees the $test as the next variable, it realizes that this is an array and that it has no good way to display an array, so it decides it can't interpolate and just displays the string as a string. The solution is to explicitly tell PowerShell where the bit to interpolate starts and where it stops:

"$($test[0])"

Note that this behavior is one of my main reasons for using formatted strings instead of relying on interpolation:

"{0}" -f $test[0]

Solution 2:

In such cases you have to do:

echo "$($test[0])"

Another alternative is to use string formatting

echo "this is {0}" -f $test[0]

Note that this will be the case when you are accessing properties in strings as well. Like "$a.Foo" - should be written as "$($a.Foo)"