2013-02-11 161 views
2

我有一个while($true)循环,最后有一个start-sleep -s 60。其目的是作为不同用户启动外部PowerShell脚本,该用户将运行一系列服务器,在最后一分钟内检查事件日志中的变化并作出相应的反应。PowerShell:在while循环中检查错误?

由于我的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 

} 

我想我可以改变我的计划任务运行每一分钟,但到目前为止,这个循环似乎一直很好。只是想在循环激活时引入错误检查。

+0

尝试我喜欢的PS奥秘的位:(!$?)如果 – EBGreen 2013-02-11 18:31:17

回答

3

你试过try/catch块吗?错误的凭证是一个终止错误,所以try块中的其他代码在凭证错误后不会运行。当你抓住它时,你可以做任何你想做的事情。

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 StopStart-Process线。至于说,凭据应当终止错误,这使erroraction参数不必要

编辑你为什么要使用Start-Process在首位运行的脚本?我将它切换到Invoke-Command远程运行powershell脚本。当脚本文件丢失时,您将收到一个非终止错误。由于这是一个非终止错误,我们需要使用-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 $_ 
    } 
} 
+0

我会如何处理丢失文件或其他常见错误?我假设一个丢失的文件也是一个终止错误,所以应该在没有'-ErrorAction'的情况下被捕获。我将try/catch块添加到我的脚本并更改了文件名。然后我把它设置为通过电子邮件通知我。它从未发送过。我添加了“Write-Error $ _。message”,并且屏幕上没有任何内容。我只是试图调试,如果这是工作。 – Pat 2013-02-11 18:51:17

+0

更新:如果帐户的密码无效,此功能无效。我们如何也能够找到丢失的文件?当它能够'毫无问题地启动 - 处理powershell'时,它不会感觉到错误。该错误发生在次级PowerShell窗口中。 – Pat 2013-02-11 19:27:02

+0

查看更新的答案 – 2013-02-11 19:41:35

0

也许吧?

while($true) { 

# Start the scan 
try{ 
Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command & c:\batch\02-Scan.ps1' -ErrorAction Stop 
} 
    catch { 
      send-alert 
      break 
      } 

# Sleep 60 seconds 
start-sleep -s 60 
} 
+0

此捕捉凭证无效的伟大工程。下一个问题:是否也可能捕获缺少的文件名?当它能够'毫无问题地启动 - 处理powershell'时,它不会感觉到错误。 – Pat 2013-02-11 19:31:36

+0

如果使用-file参数而不是命令,它会更好吗? – mjolinor 2013-02-11 20:18:11