Home > Net >  Powershell update value in Array
Powershell update value in Array

Time:03-25

I'm suspect I am going about this the wrong way and need to switch to a hash table but is it possible to update a specific value in an Array? The script retrieves the cluster nodes and stores the data in a array, then proceeds to reboot each one, once rebooted I want to update the reboot 'column' value in the array to 1.

$Array=@()
$Cluster = Get-ClusterNode
foreach ($Node in $Cluster)
    {                 
        $item = New-Object PSObject
        $item | Add-Member -type NoteProperty -Name 'Node' -Value $Node.Name
        $item | Add-Member -type NoteProperty -Name 'State' -Value $Node.State
        $item | Add-Member -type NoteProperty -Name 'Rebooted' -Value "0"
        $Array  = $item
    }
foreach ($row in $Array | Where { $Array.Rebooted -eq "0" })
    {
    Reboot-Function -Node $row.Node
    $Array.Rebooted  = 1 | Where-Object {$Array.Node -eq $row.Node}
    }
$Array

CodePudding user response:

You need to rewrite the Where-Object statement in the second loop slightly (use $_ to refer to the current pipeline object), and then simply update the current object via the $row variable inside the loop body:

foreach ($row in $Array | Where { $_.Rebooted -eq "0" })
{
    Reboot-Function -Node $row.Node
    $row.Rebooted = '1'
}
  • Related