PowerShell 在双引号内插值时输出数组项 [英] PowerShell outputting array items when interpolating within double quotes

查看:75
本文介绍了PowerShell 在双引号内插值时输出数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PowerShell 中发现了一些围绕数组和双引号的奇怪行为.如果我创建并打印数组中的第一个元素,例如:

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]

仅计算 $test 变量,数组标记 [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?

推荐答案

因此,当您使用插值时,默认情况下它只对 toto 中的下一个变量进行插值.所以当你这样做时:

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

"$test[0]"

它将 $test 视为下一个变量,它意识到这是一个数组并且它没有好的显示数组的方法,因此它决定它不能插入并只将字符串显示为字符串.解决方案是明确告诉 PowerShell 要插入的位从哪里开始以及在哪里停止:

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]

这篇关于PowerShell 在双引号内插值时输出数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆