【问题标题】:PowerShell replace value in an arrayPowerShell替换数组中的值
【发布时间】: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


【解决方案1】:

如果你真的需要一个数组数组(输入[array[]]),你的问题解决如下:

$nodes[0][0].slot[0] = "b" 

也就是说,您的每个$nodes 元素本身就是一个数组,而您填充$nodes 的方式,您的get-NcNode | select-object ... 管道输出的每个[pscustomobject] 实例都成为$nodes 的自己的元素,但每个作为单元素子数组 - 因此需要额外的[0] 索引访问。[1]


但是,在您的情况下,这听起来像一个常规数组([array],实际上与[object[]] 相同)就足够了,其中每个元素都包含一个(单个,标量)[pscustomobject]:

# Type constraint [array] creates a regular [object[]] array.
[array] $nodes = get-NcNode | select-object -property Node, @{Label = "slot"; expression = {@("a")*4}}

像这样定义$nodes,您的原始代码应该可以工作。


[1] 在 获取 一个值时 - 但不是在 设置 - 由于 PowerShell 的 member-access enumeration 功能,您可以在没有额外索引的情况下逃脱。

【讨论】:

    猜你喜欢
    • 2015-10-18
    • 2022-11-17
    • 2015-10-30
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    相关资源
    最近更新 更多