具有超时的do-while循环

Iok*_*kan 5 powershell

我有以下循环:

$output = (command)
do {
something
} while ($output -match "some string")
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ndl 11

只需使用Get-Datecmdlet并在您的while情况下检查它.例:

$startDate = Get-Date

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

  • 绝对是要走的路.请注意,`$ output`在原始示例中保持不变,因为在`do {} while()`循环中没有任何内容被分配给它 (2认同)

小智 6

尽管使用Get-DateCmdlet 是有效的,但更简洁的方法是使用该类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)
Run Code Online (Sandbox Code Playgroud)

资料来源:

  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://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch?view=netframework-4.8
  4. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/new-timespan?view=powershell-6