【发布时间】:2016-02-16 04:42:47
【问题描述】:
如果强制终止 PowerShell 脚本,是否可以强制执行某些代码?我试过 try..finally 和 Traps,但它们似乎都不起作用,至少当我从 PowerShell ISE 中按 Ctrl-C 时。
基本上,我有一个执行 PowerShell 脚本的 Jenkins 构建。如果出于任何原因我想从 Jenkins 中停止构建,我不希望任何子进程锁定文件,从而使我的构建项目处于损坏状态,直到管理员手动终止有问题的进程(在我的情况下为 nunit-agent.exe )。因此,如果发生这种情况,我希望能够强制执行终止 nunit-agent.exe 的代码。
更新:正如@Frode 下面建议的那样,我尝试使用try..finally:
$sleep = {
try {
Write-Output "In the try block of the job."
Start-Sleep -Seconds 10
}
finally {
Write-Output "In the finally block of the job."
}
}
try {
$sleepJob = Start-Job -ScriptBlock $sleep
Start-Sleep -Seconds 5
}
finally {
Write-Output "In the finaly block of the script."
Stop-Job $sleepJob
Write-Output "Receiving the output from the job:"
$content = Receive-Job $sleepJob
Write-Output $content
}
然后,当我执行此操作并使用 Ctrl-C 中断该过程时,我没有得到任何输出。我认为我应该得到的是:
In the finally block of the script.
Receiving the output from the job:
In the try block of the job.
In the finally block of the job.
【问题讨论】:
标签: powershell nunit powershell-ise