powershell - 如何捕获 start-job 的脚本 block 中引发的异常?

标签 powershell powershell-2.0

我有以下脚本,

$createZip = {
    Param ([String]$source, [String]$zipfile)
    Process { 
        echo "zip: $source`n     --> $zipfile"
        throw "test"
    }
}

try {
    Start-Job -ScriptBlock $createZip -ArgumentList "abd", "acd"  
    echo "**Don't reach here if error**"
    LogThezippedFile
}
catch {
    echo "Captured: "
    $_ | fl * -force
}
Get-Job | Wait-Job 
Get-Job | receive-job 
Get-Job | Remove-Job 

但是,无法捕获在另一个 powershell 实例中引发的异常。捕获异常的最佳方法是什么?
Id              Name            State      HasMoreData     Location             Command                  
--              ----            -----      -----------     --------             -------                  
343             Job343          Running    True            localhost            ...                      
**Don't reach here if error**
343             Job343          Failed     True            localhost            ...                      
zip: abd
     --> acd
Receive-Job : test
At line:18 char:22
+ Get-Job | receive-job <<<<  
    + CategoryInfo          : OperationStopped: (test:String) [Receive-Job], RuntimeException
    + FullyQualifiedErrorId : test

最佳答案

使用 throw将更改作业对象的 State属性为“失败”。关键是使用Start-Job返回的job对象或 Get-Job并检查 State属性(property)。然后,您可以从作业对象本身访问异常消息。

根据您的要求,我更新了示例以还包括并发性。

$createZip = {
    Param ( [String] $source, [String] $zipfile )

    if ($source -eq "b") {
        throw "Failed to create $zipfile"
    } else {
        return "Successfully created $zipfile"
    }
}

$jobs = @()
$sources = "a", "b", "c"

foreach ($source in $sources) {
    $jobs += Start-Job -ScriptBlock $createZip -ArgumentList $source, "${source}.zip"
}

Wait-Job -Job $jobs | Out-Null

foreach ($job in $jobs) {
    if ($job.State -eq 'Failed') {
        Write-Host ($job.ChildJobs[0].JobStateInfo.Reason.Message) -ForegroundColor Red
    } else {
        Write-Host (Receive-Job $job) -ForegroundColor Green 
    }
}

关于powershell - 如何捕获 start-job 的脚本 block 中引发的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8751187/

相关文章:

user-interface - 在脚本运行时刷新表单上的数据的后台作业?

powershell - 如何安装 PSCX Powershell 模块?

c# - 无法加载 GAC 中找到的程序集

powershell - 如何在交互式 PowerShell 窗口中编写多行 "for"循环?

powershell - 如何搜索 PowerShell Get-Help 条目?

powershell - 需要逗号将 SamAccountName 与组分开

json - Powershell 2.0格式列表输出到JSON吗?

powershell - 使用PowerShell解析XML:使用属性获取元素的值

powershell - 使用 ConvertTo-HTML 将 URL 列表转换为可点击的 HTML 链接

php - 从 powershell 传递到批处理时丢失部分 url