Search code examples
powershellwhile-looptimer

Timed loop that restarts if criteria is met or time expires?


I am trying to run through a loop every 3 seconds for xx minutes. Inside the while loop is an IF statement. If the statement is true, then fire off my command and restart the loop for the predefined number of minutes again.

If the if statement is never true after the minutes defined, fire off my command and then restart the loop all over again with the time set above.

I could do this in a batch file with goto but cannot figure out how to do this in PowerShell.

Here is a representation of what I want to accomplish.

$minutes = 5
while(loop for 5 minutes)
{
    if(1 -eq 1)
    {
        do something
        restart the while loop for the minutes defined above
    }
    start-sleep -seconds 3
}
do something here
restart the while loop for the minutes defined above

Update:

Here is what I came up with. This is my first time trying to write a script in PowerShell so I am almost certain there is a more elegant way to write this.

# we need a constant loop going
while(1 -eq 1)
{
    # now we need our timed loop. set the timer -seconds 3 (3 seconds right now for testing)
    $timeout = new-timespan -seconds 3
    $sw = [diagnostics.stopwatch]::StartNew()
    while ($sw.elapsed -lt $timeout)
    {
        # check to see if things are still true
        if($something -eq "true")
        { 
            echo "Do nothing."
        }
        else
        {
            echo "Do something and restart."
            # break out of this timed loop since we want to restart it
            break
        }
        # check every 1 second
        start-sleep -seconds 1
    }
        echo "$something did not equal true in the IF above or the timer has run out. Do something and restart."

    # continue restarts the loop
    continue
}

Solution

  • Shouldn't you be able to just reset $sw?

    $sw = [diagnostics.stopwatch]::StartNew()
    while ($sw.elapsed -lt $timeout) {
        if ($Condition) {
            $sw.Reset()
        }
    }