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.
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.
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.
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.
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:
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With