我尝试了这段代码,但只创建了file1.txt。文件2.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
我终于找到了解决方案。启动作业脚本在默认主文件夹中启动,与脚本位置不同。 因此,如果我使用绝对路径,它可以工作。 我比自定义循环更喜欢这段代码:
Start-Job {
Out-File "C:file2.txt"
} | Wait-Job -Timeout 3
使用名为 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.'
}