PowerShell工作流中的Add-Member

时间:2014-08-28 03:56:51

标签: powershell

我在PowerShell中有以下工作流程:

workflow Audit-Computer
{
    param([string[]]$Computers)

    foreach -parallel ($computer in $Computers)
    {
        #Create a return object to hold the information we gather
        $returnObject = [PSCustomObject]@{ComputerName=$computer}

        #Test if the machine is reachable 
        $hostAlive = $true
        try {
                #Attempt a connection to the computer.
                $os = Get-WmiObject –class Win32_OperatingSystem -PSComputerName $computer –erroraction Stop

                #If we get here the connection was successful 
                $returnObject | Add-Member -MemberType NoteProperty -Name "HostAvailability" `
                    -Value "Online" -PassThru | `
                        Add-Member -MemberType NoteProperty -Name "OperatingSystem" -Value $os.Caption
        } catch {
                $hostAlive = $false
        }

        if($hostAlive){
            #The host is alive lets run our audit
        }
        else
        {
            $returnObject | Add-Member -MemberType NoteProperty -Name "HostAvailability" -Value "Offline"
        }

        #Return the gathered information to the pipeline
        Write-Output $returnObject       
    }
}

不幸的是Add-Member似乎不起作用。返回的对象不包含add-member的NoteProperties。如何在工作流程中向自定义对象添加属性?

1 个答案:

答案 0 :(得分:0)

PowerShell工作流中的cmdlet有几个限制。根据{{​​3}},Add-Member仅限于“仅本地执行”。

我无法准确测试你的脚本,但这似乎重现了同样的效果:

workflow Test-Workflow {
    $obj = [PSCustomObject]@{ComputerName = 'test'}
    $obj | Add-Member -MemberType NoteProperty -Name HostAvailable -Value "Online"
    Write-Output $obj
}

但添加InlineScript块使其有效:

workflow Test-Workflow {
    InlineScript {
        $obj = [PSCustomObject]@{ComputerName = 'test'}
        $obj | Add-Member -MemberType NoteProperty -Name HostAvailable -Value "Online"
        Write-Output $obj
    }
}