具有超时的do-while循环

时间:2016-11-28 10:17:07

标签: powershell

我有以下循环:

$output = (command)
do {
something
} while ($output -match "some string")

哪个工作正常。我想在循环中添加超时,我该怎么做?期望在某些时候输出与字符串不匹配,但如果输出永远与字符串匹配,我不希望它永远运行。

2 个答案:

答案 0 :(得分:9)

只需使用Get-Date cmdlet并检查while条件下的内容。例如:

$startDate = Get-Date

$output = (command)
do {
something
} while ($output -match "some string" -and $startDate.AddMinutes(2) -gt (Get-Date))

答案 1 :(得分:1)

尽管使用Get-Date Cmdlet是有效的,但更干净的方法是使用System.Diagnostics.Stopwatch类,该类在.NET Core> = 1.0中可用。

$timeout = New-TimeSpan -Seconds 5
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
do {
    # do stuff here
} while ($stopwatch.elapsed -lt $timeout)

来源:

  1. https://mjolinor.wordpress.com/2012/01/14/making-a-timed-loop-in-powershell/
  2. https://mcpmag.com/articles/2017/10/19/using-a-stopwatch-in-powershell.aspx
  3. https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch?view=netframework-4.8
  4. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/new-timespan?view=powershell-6