Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do-while loop with timeout

Tags:

powershell

I have the following loop:

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

Which works fine. I want to add a timeout to the loop, how do I do that? The expectation is that at some point the output won't match the string but I don't want it to run forever if the output matches the string forever.

like image 839
Iokanaan Iokan Avatar asked Nov 28 '16 10:11

Iokanaan Iokan


People also ask

How do you stop a loop after a certain time in python?

Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.

Do-While loop in PowerShell?

PowerShell Do-While loopA Do-While loop is a variant of the While loop, and the main difference is that the script block is executed before the condition is checked. This means that even if the start condition is false, the script block will be executed at least once. Write-Host End of Do-While loop.

Do until in PowerShell?

In PowerShell Do Until loop is used when we want to repeatedly execute statements as long as the condition is false. Like the Do-While loop, Do Until loop always runs at least once before the condition is evaluated in PowerShell.


2 Answers

Although using the Get-Date Cmdlet is valid, a cleaner approach would be to use the System.Diagnostics.Stopwatch class, which is available in .NET Core >= 1.0.

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

Sources:

  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
like image 174
dacabdi Avatar answered Oct 19 '22 20:10

dacabdi


Just use the Get-Date cmdlet and check for that in your while condition. Example:

$startDate = Get-Date

$output = (command)
do {
something
} while ($output -match "some string" -and $startDate.AddMinutes(2) -gt (Get-Date))
like image 25
Martin Brandl Avatar answered Oct 19 '22 19:10

Martin Brandl