9

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.

2
  • sorry, I misunderstood your question Commented Nov 28, 2016 at 10:22
  • no problem, I should have been more clear. Commented Nov 28, 2016 at 10:23

2 Answers 2

18

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))
Sign up to request clarification or add additional context in comments.

6 Comments

thats pretty neat!
Definitely the way to go. Notice that $output stays the same in the original example, due to nothing ever being assigned to it inside the do{}while() loop
one quick question here. When you assign the output of a command to a variable like this, does powershell run the command everytime it checks the value of the variable?
No, the variable gets assigned with the result of the command you invoked. PowerShell wont invoke it again.
I see, then I should include $output=(command) line within the loop, right?
|
6

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://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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.