Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 791
Brain2000 Avatar asked Feb 08 '12 15:02

Brain2000


People also ask

How do you pass variables in double quotes in PowerShell?

To pass a double quote, escape with a backslash: \" -> " To pass a one or more backslashes followed by a double quote, escape each backslash with another backslash and escape the quote: \\\\\" -> \\" If not followed by a double quote, no escaping is necessary for backslashes: \\ -> \\

How do you handle double quotes in PowerShell?

Finally, if your PowerShell strings are quoted with double quotes, then any double quote characters in the string must be escaped with the backtick "`". Alternatively, the embedded double quote characters can be doubled (replace any embedded " characters with "").

Can an array be interpolated?

Arrays can be interpolated by means of a one-to-one mapping given by (7) f : A S → A ¯ S , where is a sector.

What is the difference between single quotes and double quotes in PowerShell?

There is no such difference between the single quote (') and double quote(“) in PowerShell. It is similar to a programming language like Python. We generally use both quotes to print the statements.


1 Answers

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]
like image 83
EBGreen Avatar answered Oct 19 '22 15:10

EBGreen