July 31

Powershell: Creating an endless loop in your script

Sometimes when scripting you need to create a never ending loop while your script either waits for some other task to complete or repeats a task over and over again. There are two ways people tend to go about creating loops in Powershell, but one of them will eventually leave your script in a heap.

What not to do – a self referencing function:

When people are first starting out in Powershell, they tend to make loops with self-referencing functions. It’s the logical thing to do – run a function and, if it doesn’t turn out the way you wanted it to, run the function again. Take the example below:

Function Count-Up
{
    if($i -lt 9999)
    {
        $i++
        Count-Up
    }
    else
    {
        Write-Host “Count complete - We have counted up to $i”
    }
}

The problem with this is that you aren’t really creating a loop – it’s actually a spiral. Each time the Count-Up function is executed by the If statement it is actually running within the previous Count-Up function. Eventually, and in this case quite quickly, you end up with a spiral so deep PowerShell decides to bail out. At that point you get a “call depth overflow” and Powershell merrily ploughs on with the rest of your script.

The Right Way – using the While statement:

The correct way to build a loop is to use the inbuilt statement While. With a While loop, While replaces the If statement and the loop will continue to run while the statement evaluates to true, removing the need to re-reference the function (and accidentally create a spiral). This is the previous example re-written for a While statement:

Function Count-Up
{
    while($i -lt 9999)
    {
        $i++
    }

    Write-Host “Count complete - We have counted up to $i”
}

Notice we have also got rid of the Else statement. A While loop will continue to run until the statement is no longer true, so it doesn’t require Else statements (or support them) – we can be sure that the line after the loop will only run once the loop has completed.

Creating a truly endless function:

Sometimes you will want a truly endless function, that will run and run until the PowerShell session is closed. This is acheived simply by providing the While statement a condition that is always true. In PowerShell this looks like this:

while($true)
{
    $i++
    Write-Host “We have counted up to $i”
}

By: A. Craik


Copyright 2021. All rights reserved.

Posted July 31, 2014 by Timothy Conrad in category "Programming

About the Author

If I were to describe myself with one word it would be, creative. I am interested in almost everything which keeps me rather busy. Here you will find some of my technical musings. Securely email me using - PGP: 4CB8 91EB 0C0A A530 3BE9 6D76 B076 96F1 6135 0A1B