如何在 powershell 命令上设置超时?

How can I put a timeout on a powershell command?

我试过这段代码,但只创建了 file1.txt。 File2.txt 没有。我正在寻找使用超时的内置方式。所以不是通过创建自定义循环。

Out-File "file1.txt"                  #this file is created

$Job = Start-Job -ScriptBlock {            
        Out-File "file2.txt"          #this file is not created
}
$Job | Wait-Job -Timeout 5
$Job | Stop-Job

使用一个名为 Wait-Action 的函数将所有这些功能合并到一个 PowerShell 函数中,从 PowerShell 库下载它:

安装脚本-名称等待操作

要向 PowerShell 脚本添加超时功能需要完成几个不同的任务:

开始计时 调用一段代码 经常检查代码的状态 如果超过超时,让 PowerShell 做一些事情 如果没有超时,继续执行脚本 停止计时器

我们需要做的第一件事是定义超时。大多数情况下,以秒为单位的超时会起作用。我想确保我的代码不会持续超过 10 秒,所以我会为此设置一个变量。

$Timeout = 10 ## seconds

接下来,我需要获取我想要等待的任何代码并将其添加到脚本块中。对于这个例子,假设我已经在脚本的上方创建了一些后台作业。我想等到所有这些工作都完成后再继续。

$jobs = Get-Job
 $Condition = {param($jobs) 'Running' -not in $jobs.State }
 $ConditionArgs = $jobs

接下来,我需要定义我的脚本执行任务的检查间隔时间。

$RetryInterval = 5 ## seconds

现在我开始计时。

## Start the timer
 $timer = [Diagnostics.Stopwatch]::StartNew()

现在计时器已启动,我现在可以调用我需要完成的那段代码。

## Start checking the condition scriptblock. Do this as long as the action hasn't exceeded
 ## the timeout or the condition scriptblock returns something other than $false or $null.
 while (($timer.Elapsed.TotalSeconds -lt $Timeout) -and (& $Condition $ConditionArgs)) {

     ## Wait a specific interval
     Start-Sleep -Seconds $RetryInterval

     ## Check the time
     $totalSecs = [math]::Round($timer.Elapsed.TotalSeconds,0)
     Write-Verbose -Message "Still waiting for action to complete after [$totalSecs] seconds..."
 }

一旦超时或任务完成,我就需要停止计时器。

## The action either completed or timed out. Stop the timer.
 $timer.Stop()

现在我可以检查是否超时或任务是否自行完成。在这里,我抛出一个异常,表明如果超时停止操作则操作没有完成。否则,我只是写了一个冗长的声明,之后任何代码都可以遵循。

## Return status of what happened
 if ($timer.Elapsed.TotalSeconds -gt $Timeout) {
     throw 'Action did not complete before timeout period.'
 } else {
     Write-Verbose -Message 'Action completed before the timeout period.'
 }

我终于找到了解决办法。 Start-Job 脚本在默认主文件夹中启动,与脚本位置不同。 所以如果我使用绝对路径它会起作用。 与自定义循环相比,我更喜欢这段代码:

Start-Job {                
    Out-File "C:\file2.txt"
} | Wait-Job -Timeout 3