我有一个 while($true)
循环,其末尾有一个 start-sleep -s 60
。目的是启动一个外部 PowerShell 脚本作为不同的用户,该脚本将运行服务器列表,检查事件日志以了解最后一分钟内的更改并做出相应的 react 。
由于我的 while 循环(如下)使用 -credential
标志以其他人的身份运行脚本,我担心出现错误(例如帐户被锁定、密码过期、文件丢失等).
我尝试了 if ($error)
语句,并更改了外部脚本的文件名,但我从未收到警告。我在想这是因为它永远不会停止重新检查自己吗?
while($true) {
# Start the scan
Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command & c:\batch\02-Scan.ps1'
# Sleep 60 seconds
start-sleep -s 60
}
我想我可以将计划任务更改为每分钟运行一次,但到目前为止,这个循环似乎运行良好。只想在循环处于事件状态时引入错误检查。
最佳答案
您尝试过 try/catch block 吗?错误的凭据是一个终止错误,因此 try block 中的其余代码将不会在凭据错误后运行。当你捕获它时,你可以做任何你想做的事.. 例如。
try {
Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command & c:\batch\02-Scan.ps1'
} catch {
#Catches terminating exceptions and display it's message
Write-Error $_.message
}
如果要捕获所有错误,请将 -ErrorAction Stop
添加到 Start-Process
行。如前所述,凭据应该是一个终止错误,这使得 erroraction
参数变得不必要
编辑 为什么首先要使用 Start-Process
来运行脚本?我将其切换为远程运行 powershell 脚本的 Invoke-Command
。当缺少脚本文件时,您将收到非终止错误。因为它是非终止错误,所以我们需要使用 -ErrorAction Stop
参数。要捕获丢失文件错误和所有其他错误(如凭据),请使用如下内容:
try { Invoke-Command -ScriptBlock { & c:\batch\02-Scan.ps1 } -ErrorAction Stop
} catch {
if ($_.Exception.GetType().Name -eq "CommandNotFoundException") {
Write-Error "File is missing"
} else {
Write-Error "Something went wrong. Errormessage: $_"
#or throw it directly:
#throw $_
}
}
关于PowerShell:在 while true 循环中进行错误检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14818443/