PowerShell里的数组

创建数组

最简单的写法:

$Output = @("Power","Shell")

当然,你连括号也可以不写

$Output = "Power","Shell"

那么,使用变量也是可以的

$Power ="Power"
$Shell="Shell"
$Output = @($Power,$Shell)

来思考

于是,这天我写出了这样的一段代码

$Power ="Power"
$Shell="Shell"
$Output = @($Power+$Shell, $Power+$Shell)

很好理解,我的数组的length应该是2,[0]=[1]="PowerShell"
结果,数组Length是1,输出结果(字符串)是"PowerShell PowerShell"
What?
对着代码看了良久,我悟了

$Output = @($Power+$Shell, $Power+$Shell) 
||
$Output = @($Power+  $Shell, $Power   +$Shell) 
||
$Output = @($Power+  @($Shell, $Power)   +$Shell) 

解决方案

  1. 既然是String Array,那就显式指定就好了
$Power ="Power"
$Shell="Shell"
$Output = @("$Power$Shell", "$Power$Shell")
  1. 如果不用方法1呢?当然是万能的括号了。毕竟这个问题本质原因就是运算符的优先级问题导致的。
$Power ="Power"
$Shell="Shell"
$Output = @($($Power+$Shell), $($Power+$Shell))

参考

ref:https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-arrays?view=powershell-7.1

posted @ 2021-09-13 12:38  talentzemin  阅读(193)  评论(0编辑  收藏  举报