如何对powershell命令设置超时?
我尝试了这段代码,但只创建了file1.txt。File2.txt不支持。我正在寻找使用超时的内置方式。因此,不是通过创建自定义循环如何对powershell命令设置超时?,powershell,timeout,start-job,Powershell,Timeout,Start Job,我尝试了这段代码,但只创建了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-
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 Gallery下载: 安装脚本-名称等待操作 要向PowerShell脚本添加超时功能,需要执行几个不同的任务: 启动计时器 调用某段代码 经常检查代码的状态 如果超过超时,请让PowerShell执行某些操作 如果未超过超时,请继续执行脚本 停止计时 我们需要做的第一件事是定义一个超时。通常情况下,以秒为单位的超时将起作用。我想确保我的代码不会持续超过10秒,所以我将为此设置一个变量
$Timeout = 10 ## seconds
接下来,我需要获取任何我想要等待的代码,并将其添加到scriptblock中。对于本例,假设我在脚本的后面创建了一些后台作业。我想等到所有这些工作都完成后再继续
$jobs = Get-Job
$Condition = {param($jobs) 'Running' -not in $jobs.State }
$ConditionArgs = $jobs
接下来,我需要定义脚本执行任务的检查间隔时间
$RetryInterval = 5 ## seconds
现在我来启动计时器
## Start the timer
$timer = [Diagnostics.Stopwatch]::StartNew()
## The action either completed or timed out. Stop the timer.
$timer.Stop()
现在计时器启动了,我现在可以调用需要完成的代码了
## 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..."
}
一旦超过超时时间,或者任务完成,我就需要停止计时器
## Start the timer
$timer = [Diagnostics.Stopwatch]::StartNew()
## 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 {
Out-File "C:\file2.txt"
} | Wait-Job -Timeout 3
您将使用作业收集信息,然后
接收作业
以获得结果