PowerShell:在 while true 循环中进行错误检查?

标签 powershell

我有一个 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/

相关文章:

powershell - Powershell错误验证

azure - 无法使用变量中的 az network vnet 子网列表进行循环

powershell - 在 TFS 构建期间访问 Powershell 脚本中的构建修订号

Powershell:如何从非常大的文件中流式传输、分页文本?

excel - Powershell等待Excel中执行宏

collections - 通过System.Collections.Queue传递对象时丢失类型信息

powershell - 使用 Get-AzureStorageBlobContent 从 Azure 下载 - 内容出现乱码

powershell - 我可以确定 PowerShell 函数是否作为管道的一部分运行吗?

c# - 无法从 Powershell 3.0 调用 C# 类

regex - 获取模式的最后一个实例