捕获工作流程中的错误

Jus*_*ane 3 powershell workflow-foundation powershell-3.0

我一直在 PS 3.0 RC 中使用 PowerShell 工作流程,到目前为止,我已经爱上了它。然而,在工作流程中可以使用和不能使用的事物有很多限制。我目前所关心的是 $Error 变量。调用我的工作流程时,我收到以下错误:

The variable 'Error' cannot be used in a script workflow.
Run Code Online (Sandbox Code Playgroud)

有谁知道如何捕获工作流程中的错误文本,或者如果您不熟悉工作流程,有关于错误捕获的替代方法的建议吗?我一直在四处寻找,几乎找不到有关工作流程细节的信息。谢谢!

我正在尝试做这样的事情:

workflow Get-LoggedOnUser{
    param([array]$computers,[System.Management.Automation.PSCredential]$credential)

    foreach -parallel($computer in $computers) {
        $response = $null
        $errorMessage = $null
        If (Test-Connection -ComputerName $computer -count 1 -quiet) {
            Try {
                $ErrorActionPreference = "Stop"
                $response = Get-WMIObject -PSCredential $credential -PSComputername $computer -query "Select UserName from Win32_ComputerSystem"
                $Error
            }
            Catch {
                $errorMessage = $Error[0].exception
            }
            Finally {
                $errorActionPreference = "Continue"
            }
        }
        Else {
            $errorMessage = "No response"
        }   
        $output = [PSCustomObject]@{
            Name = $computer
            User = $response.UserName
            Error = $errorMessage
        }
        $output
    }
}
Run Code Online (Sandbox Code Playgroud)

Jus*_*ane 5

我最终通过将工作流程的大部分逻辑封装在 InlineScript 块中来解决这个问题。这样,工作流的每个循环仍然并行运行(这是我想要的),但我可以在工作流中自由使用普通的 PowerShell cmdlet、参数和变量(包括 $Error):

workflow Get-LoggedOn {
param(
    [array]$computers,
    [System.Management.Automation.PSCredential]$Credential
    )
    ForEach -parallel ($computer in $computers) {
    InlineScript {
        Try {
            $ErrorActionPreference = "Stop"
            $response = Get-WMIObject -computername $using:computer -credential $using:Credential -query "select UserName from Win32_ComputerSystem"
        }
        Catch {
            $errorMessage = $Error[0].Exception
        }
        Finally {
            $ErrorActionPreference = "Continue"
        }
        $output = [PSCustomObject]@{
            Name = $using:computer
            User = $response.UserName
            Error = $errorMessage
        }
        $output
    }
}
Run Code Online (Sandbox Code Playgroud)

}