我有一个脚本可以启动监视进程的作业Start-Job
。每当此进程终止时,脚本将自动重新启动该进程,然后重新启动该脚本。
如果脚本无法重新启动进程,它将发送电子邮件并完全退出PowerShell,以避免重新启动脚本。我只是退出工作,但这似乎不起作用。
如果无法重新启动进程,如何告诉我的脚本不重启?
这是我的代码:
$sb = {
while ((Get-Process LogikWebserver).Responding) { sleep -m 50 }
if (!(Get-Process LogikWebserver).Responding) {
#restart process
try {
Start-Process "$processpath\LogikWebserver.exe" -EA Stop
sleep -s 2
if (Get-Process LogikWebserver -EA Stop) {
Send-MailMessage
}
} catch {
Send-MailMessage
<# With this exit I want to tell the script to exit completely #>
exit
}
}
}
# start and get job
Start-Job -Name LogikWebserverWatch -ScriptBlock $sb
Wait-Job -Name LogikWebserverWatch
Get-Job -Name LogikWebserverWatch | Remove-Job -Force
# restart script
$skript = "{0}\{1}" -f $PSScriptRoot, "Watch-LogikWebserver.ps1"
& $skript
答案 0 :(得分:1)
不要在scriptblock中捕获异常。接收作业输出并捕获异常。此外,使用无限循环重新运行作业,而不是重新运行脚本。
$sb = {
while ((Get-Process LogikWebserver).Responding) {
Start-Sleep -Milliseconds 50
}
# restart process (at this point .Responding was already false, thus no
# point in checking again)
Start-Process "$processpath\LogikWebserver.exe" -ErrorAction Stop
Start-Sleep -Seconds 2
if (Get-Process LogikWebserver -ErrorAction Stop) {
Send-MailMessage
}
}
while ($true) {
# start and get job
try {
Start-Job -Name LogikWebserverWatch -ScriptBlock $sb |
Wait-Job |
Receive-Job -ErrorAction Stop
} catch {
Send-MailMessage
exit
} finally {
Get-Job -Name LogikWebserverWatch | Remove-Job -Force
}
}