Adding a new property to an array of objects. Parallel

324 views Asked by At

I'd like to add a new property to an array of objects. Add-member doesn't work, please assist

$computers = Get-ADComputer -Filter {(name -like "SMZ-*-DB")} | select -First 30
workflow test-test
{
    param([Parameter(mandatory=$true)][string[]]$computers)
    $out = @()
    foreach -parallel -throttlelimit 20 ($computer in $computers)
    {
        sequence
        {
            [bool]$ping = (Test-Connection $computer.name -Quiet -Count 1)
            $computer = $computer | Add-Member -NotePropertyName "Ping" -NotePropertyValue $ping            
            $Workflow:out += $computer
            

        }
    }
    return $out  

}
test-test $computers
3

There are 3 answers

0
js2010 On BEST ANSWER

You can do something like this in powershell 7. It looks like the ADComputer objects from Get-ADComputer are read-only, so you can't add members to them.

Get-ADComputer -filter 'name -like "a*"' -resultsetsize 3 |
foreach-object -parallel {
  $computer = $_
  $ping = Test-Connection $computer.name -Quiet -Count 1
  [pscustomobject]@{
    ADComputer = $computer
    Ping = $ping
  }
}

ADComputer                      Ping
----------                      ----
CN=A001,DC=stackoverflow,DC=com True
CN=A002,DC=stackoverflow,DC=com True
CN=A003,DC=stackoverflow,DC=com True
2
A Seyam On

You are adding to Microsoft.ActiveDirectory.Management.ADComputer Typename not an array.

Try to create a PSCustomObject instead

0
Scepticalist On

If you need ALL the properties of the object or need to use the object later then probably simpler to add it once to the custom object:

    sequence
    {
        [bool]$ping = (Test-Connection $computer.name -Quiet -Count 1)
        $newObj = [pscustomobject]@{ADObject = $computer;Ping = $ping}
        $Workflow:out += $newObj
    }

...but usually you'd just grab the properties you need:

    sequence
    {
        [bool]$ping = (Test-Connection $computer.name -Quiet -Count 1)
        $newObj = [pscustomobject]@{ComputerName = $Computer.Name;Ping = $ping}
        $Workflow:out += $newObj
    }