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
    – 4c74356b41
    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))
6
  • 1
    thats pretty neat!
    – 4c74356b41
    Commented Nov 28, 2016 at 10:25
  • 2
    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 Commented Nov 28, 2016 at 10:25
  • 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? Commented Nov 28, 2016 at 10:42
  • No, the variable gets assigned with the result of the command you invoked. PowerShell wont invoke it again. Commented Nov 28, 2016 at 10:49
  • 1
    I see, then I should include $output=(command) line within the loop, right? Commented Nov 28, 2016 at 10:51
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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.