1

I'm quite new in PowerShell and I would need a little bit of support how to replace values in an array. Please have a look at my example:

[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
3
  • $nodes[0].slot[0] = "b" works fine for me. Note that the $nodes array is not inline with your Select-Object expression. If the slot is an array, there should be spaces between the strings in the display output: {a, a, a, a}. I recommend you to use this $Nodes = 1..4 | Select-Object @{n = 'Node'; e = { "nn0$_" }}, @{n = 'Slot'; e = { @('a') * 4 }} for the minimal reproducible example input. Commented Jul 13, 2020 at 11:44
  • As an aside: The initialization statement, [array[]]$nodes = @(), is pointless: its effects are replaced by the next [array[]]$nodes = ... statement. Commented Jul 13, 2020 at 12:25
  • 1
    @iRon, the code only works if [array[]] is changed to [array]. Commented Jul 13, 2020 at 12:33

1 Answer 1

3

If you really need an array of arrays (type [array[]]), your problem is solved as follows:

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

That is, each of your $nodes elements is itself an array, and the way you filled $nodes, each [pscustomobject] instance output by your get-NcNode | select-object ... pipeline became its own element of $nodes, but each as a single-element sub-array - hence the need for the extra [0] index access.[1]


However, it sounds like a regular array ([array], effectively the same as [object[]]) is sufficient in your case, where each element holds a (single, scalar) [pscustomobject]:

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

With $nodes defined like this, your original code should work.


[1] On getting a value - but not on setting - you can get away without the extra index, thanks to PowerShell's member-access enumeration feature.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.