Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

string interpolation - 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...