windows - 如何在powershell中不断尝试某件事直到成功?

标签 windows powershell scripting powershell-3.0 powershell-4.0

使用基本结构:

try
{
    Do-Something
}
catch
{
    Write-Output "Something threw an exception"
}

是否可以继续尝试“Do-Something”直至成功?也许使用像这样的 while 循环:

$Timeout = 60
$timer = [Diagnostics.Stopwatch]::StartNew()
$t = 0
while (($timer.Elapsed.TotalSeconds -lt $Timeout) -and ($t -ne 1))) {
    Start-Sleep -Seconds 1
    try
    {
        Do-Something
        $t = 1
    }
    catch
    {
        Write-Output "Something threw an exception"
    }
}
$timer.Stop()

这里我使用计时器来确保 PowerShell 不会无限期地运行。 它应该继续尝试,直到 try 成功并且 $t = 1 被执行。然而,大约2秒后就失败了。请帮忙。

更具体地说,Do-Something 是:

(Get-Process -Name FineReader).MainWindowHandle

我希望代码继续尝试,直到 FineReader 存在并且它可以获取 MainWindowHandle

最佳答案

您可以使用break关键字。

# Set the erroracton preference to stop when an error occurs,
$ErrorActionPreferenceBak = $ErrorActionPreference
$ErrorActionPreference    = 'Stop'

While($True){
    try{
        Do-Something
        break
    }
    catch{
        Write-Output "Something failed"
        Start-Sleep -Seconds 1 # wait for a seconds before next attempt.
    }
    finally{
        #Reset the erroracton preference
        $ErrorActionPreference = $ErrorActionPreferenceBak
    }
}

关于windows - 如何在powershell中不断尝试某件事直到成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52403643/

相关文章:

linux - 将文本和文件内容发送到标准输入,而不使用临时文件

windows - 是否可以避免对话框函数中的静态或全局变量

windows - 通过命令行启动程序的批处理文件/命令

windows - Cygwin:创建 Windows 通知并在单击通知时聚焦程序

powershell - 从PowerShell发送的ToastNotifications从Action Center中消失

bash - 将变量从多个 ssh awk 输出复制到本地文本文件

windows - 如何仅使用CMD连接到WiFi?

powershell - 为 Windows 7 开发的 PowerShell 脚本能否在 Win Server 2008 R2 上运行?

powershell - 读主机具有多种颜色

linux - 最后一个特定字符后的表达式