本文介绍了如何捕获在Start-JOB的脚本块中引发的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下脚本
$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
或Get-Job
返回的作业对象,并检查State
属性。然后,您可以从作业对象本身访问异常消息。
根据您的请求,我更新了该示例以包括并发性。
$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
}
}
这篇关于如何捕获在Start-JOB的脚本块中引发的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!