Making a timed loop in Powershell

A question on one of the forums came up recently about how to write a Powershell loop that would exit after a specified amount of time.

There are a few different ways to do this, but the simplest I’ve found is to create a timer using [system.diagnostics.stopwatch]::startnew().

This creates and starts a timer that can be easily interrogated to see how long the loop has been running.

This example will run the loop for 1 minute, checking every 5 seconds for the existence of a particular file, writing to the console and then exiting the loop if it finds it. If it hasn’t found the file by the time the timer hits the timeout value, it exits the loop ane writes “Timed out” to the console.

If you want it to check more often, just reduce the start-sleep time, but don’t take it out altogether or you’ll create a “busy” loop that will become a cpu hog.

$timeout = new-timespan -Minutes 1
$sw = [diagnostics.stopwatch]::StartNew()
while ($sw.elapsed -lt $timeout){
    if (test-path c:\testfiles\somefile.txt){
        write-host "Found a file!"
        return
        }

    start-sleep -seconds 5
}

write-host "Timed out"
Advertisements

3 responses to “Making a timed loop in Powershell

  1. Just what I was looking for, a non-blocking polling-style key-press function!

  2. PERFECT..! šŸ˜€ šŸ˜€ šŸ˜€

  3. Nice. Thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s