powershell数组赋值遇到的bug, 开头的逗号不是一直都
2022-08-31 本文已影响0人
别有路
今天写Powershell的时候遇到个bug, 搜了半天没搜到(不过最后解决后感觉以前似乎看到过, 可能我搜的内容不对)
简单地说, powershell弄个数组一般就直接逗号分隔即可, 例如
$arr1 = "a", "b", "c"
不过如果要定义单元素的数组的话, 我之前比较喜欢的方法是:
$arr2 = , "d"
结果今天我在一个脚本里写的时候, 想着有个数组的长度不定, 我就都给加个逗号, 比如:
$list1 = , "asd", "qwe", "zxc", "rty"
Write-Host $list1
>>> asd qwe zxc rty
然后echo出来也没问题, 但是在后续逻辑监测item的时候, 第一个item始终无法检测
$list1.Contains("qwe")
>>> True
$list1.Contains("asd")
>>> False
妈呀, 想了半天, 最后发现GetType出来的俩玩意儿不一样, was...
$list1[0].GetType()
>>> IsPublic IsSerial Name BaseType
>>> -------- -------- ---- --------
>>> True True Object[] System.Array
$list1[1].GetType()
>>> IsPublic IsSerial Name BaseType
>>> -------- -------- ---- --------
>>> True True String System.Object
所以, powershell把逗号一起算进第一个item的头上了...就是下面这个
, "asd"
这么想的话, 就是有点类似于python的这种
list1 = [[0], 1, 2, 3]
大概就是这种感觉吧...
以后不犯这种错误嘞... 甚至都想换种方式定义, 其他的方法他不香吗!
[array] $arr1 = "a"
$arr2 = @("b")
总之powershell还是挺灵活的在这方面