将新的 属性 添加到对象数组。平行线

Adding a new property to an array of objects. Parallel

我想向对象数组添加一个新的 属性。加会员不成功,请协助

$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

您要添加到 Microsoft.ActiveDirectory.Management.ADComputer Typename 而不是数组。

尝试改为创建 PSCustomObject

如果您需要对象的所有属性或需要稍后使用该对象,那么将它添加到自定义对象中可能更简单:

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

...但通常您只需要获取所需的属性即可:

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

您可以在 powershell 7 中执行类似的操作。看起来 Get-ADComputer 中的 ADComputer 对象是只读的,因此您不能向它们添加成员。

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=Whosebug,DC=com True
CN=A002,DC=Whosebug,DC=com True
CN=A003,DC=Whosebug,DC=com True