【发布时间】:2020-07-13 10:19:45
【问题描述】:
我是 PowerShell 的新手,我需要一些关于如何替换数组中的值的支持。请看我的例子:
[array[]]$nodes = @()
[array[]]$nodes = get-NcNode | select-object -property Node, @{Label = "slot"; expression = {@("a")*4}}
$nodes
Node slot
---- ----
nn01 {a,a,a,a}
nn02 {a,a,a,a}
nn03 {a,a,a,a}
nn04 {a,a,a,a}
$nodes[0].slot[0]
a
$nodes[0].slot[0] = "b" #I try to replace a with b
$nodes[0].slot[0]
a #It didn’t work
$nodes[0].slot.SetValue("b",0) #I try to replace a with b
$nodes[0].slot[0]
a #It didn’t work
$nodes[0] | Add-Member -MemberType NoteProperty -Name slot[0] -Value "b" -Force
$nodes[0]
Node slot slot[0]
---- ---- -------
nn01 {a,a,a,a} b #That’s not what I wanted
【问题讨论】:
-
$nodes[0].slot[0] = "b"适合我。请注意,$nodes数组不与您的Select-Object表达式内联。如果插槽是一个数组,则显示输出中的字符串之间应该有空格:{a, a, a, a}。我建议你使用这个$Nodes = 1..4 | Select-Object @{n = 'Node'; e = { "nn0$_" }}, @{n = 'Slot'; e = { @('a') * 4 }}作为minimal reproducible example 输入。 -
顺便说一句:初始化语句
[array[]]$nodes = @()毫无意义:它的效果被下一个[array[]]$nodes = ...语句替换。 -
@iRon,代码仅在将
[array[]]更改为[array]时有效。
标签: arrays powershell arrayofarrays