PowerShell Loops – A Simple Guide with Video

Rate this post

PowerShell foreach Loop

Syntax:

The keyword ‘foreach‘ is used in Windows PowerShell to iterate through a series or list of items, usually with the intent of performing operations using each item. 

foreach ( unit in collection ) { code block }

Example:

In the following example, we use PowerShell to read the contents of a text file (C:\Temp\ServerList.txt) filled with server names, storing the values in a variable called $Servers:

$Servers = Get-Content -Path C:\Temp\ServerList.txt

Next, we loop through the server names using the keyword ‘foreach‘. The loop will repeat as many times as there are server names in the text file.

foreach ( $Server in $Servers ) {
    Get-Service -ComputerName $Server -DisplayName "Print Spooler" | Restart-Service
}

Within the loop, we find the ‘Print Spooler’ service object from each server and pipe it to the Restart-Service cmdlet. The service is restarted, and the loop continues on to the next server in the list. 

PowerShell foreach Loop Through an Array

Usually, the objects being iterated through with the ‘foreach‘ loop is an array, or a collection of objects. When we want to perform some action on each item in the array, we use the ‘foreach‘ keyword to step through the array, one unit at a time, and act on the object.

In the following example, we create an array of the numbers one through ten and store it in a variable called $numbers:

$numbers = (1..10)

If we call the variable, we get a list of the numbers, one per line.

Now suppose we want to square each number, multiplying each number by itself. We can’t simply square the $number variable itself. Instead, we use ‘foreach‘ to iterate through each unit in the array, then multiply the number by itself:

foreach ( $number in $numbers ) {
    Write-Output "The square of $number is $($number * $number)."
}

Running these commands, we get the square values of each number in the array.

PowerShell Loop Through Files

We can use the foreach loop to iterate through a list of files and perform any number of actions on each one.

In the following example, we change directories to the C:\Windows\System32 folder, then list all the files contained therein with the '.txt' extension:

Set-Location C:\Windows\System32

foreach ( $file in ( Get-ChildItem *.txt )) {
     Write-Output $file.name
}

PowerShell loop break

Occasionally, when looping through a list or array, we may want to stop performing the actions mid-way through, usually based on some special criteria. In such a case, we can use the ‘break‘ statement to exit the current script block. The rest of the loop will not be executed.

In the following example, we can re-use the $numbers variable which contains the integers one through ten.

$numbers = (1..10)

Then we’ll use the foreach keyword to loop through the array of numbers. However, when we reach the number ‘seven’, we’ll use the ‘break‘ statement to terminate the loop. 

foreach ( $number in $numbers ) {
    if ( $number -ne 7 ) {
        Write-Output "The number $number can pass."
    } else {
        Write-Output "The number $number was found. Exiting..."
        break
    }
}

As we can see, each number is printed as expected until the ‘7’ has reached its turn in the loop. The ‘break‘ statement terminates the loop, preventing the remaining integers in the array from being evaluated.

PowerShell Loop X Times

A similar concept to the ‘foreach‘ keyword is the ‘for‘ statement, which allows us to create a loop that will run our desired commands for a certain number of times, but without needing to create an array beforehand. In the ‘for‘ statement, we create a starting unit, a condition, and an increment to iterate through the loop. 

Syntax:

for ( $variable = value;  $variable conditional statement; $variable incremental statement ) {
    <commands go here>
}

Example:

for ( $i = 1; $i -lt 5; $i++ ) {
    Write-Output "The latest number is $i"
}

In this example we begin by setting the variable $i to be equal to one.

Next, we evaluate if the variable is ‘less than’ (or -lt) the number five. If it is, then the commands within the scriptblock are executed.

Finally we use ‘$i++‘ to increment the variable by one and repeat the process.

This will continue until $i is equal to five, at which point the variable $i will no longer be less than five, and the loop exits. To perform this logic in separate commands would be more work and prone to error. Using the ‘for‘ loop is a handy shortcut.

We are not restricted to the above values when using the ‘for‘ statement. We can use any valid variable name instead of $i (such as $counter or $turns). We can also make the initial variable equal to any number that makes sense, such as zero, two, or ten billion. Nor do we have to increment our counter by one. In the following example, we begin with the number six, increase the variable by 9 in each iteration, and stop when the variable is less than or equal to (‘-le‘) one hundred:

for ( $unit = 6; $unit -le 100; $unit += 9) {
    Write-Output "The latest unit number is $unit"
}

Likewise, we can decrease the increment if that makes more sense. In the following example, we’ll count down from ten to simulate a rocket liftoff:

for ( $count = 10; $count -gt -1; $count-- ) {
    Write-Output "T-minus $count seconds..."
    Start-Sleep -Seconds 1
}
Write-Output "LIFT OFF!"

PowerShell While Loop

Another looping concept common to both programming in general and PowerShell in particular is called ‘While‘. In this concept, the loop is continued indefinitely for as long as a particular condition is met. The loop could occur one time, many times, an infinite number of times, or even no times at all. The ‘While‘ loop has simpler syntax than the ‘for‘ statement, and it’s best used when the number of desired loops is unknown. Unlike the ‘for‘ statement that usually requires the number of iterations to perform, like the digits in an array or the rows in a text file, the ‘While‘ loop will perform actions until a certain condition is no longer true, no matter how long that might be.

Syntax:

While ( condition ) { code block }

Example

$CurrentSecond = $False

While ( $CurrentSecond -ne 59 ) {
    $CurrentSecond = (Get-Date).Second
    Start-Sleep -Seconds 1
    Write-Host " . " -NoNewline
}
$Time = Get-Date -Format "hh:mm:ss"
Write-Output "`nThe time is exactly $Time"

In this example, the code block runs the cmdlet ‘Get-Date‘ and extracts just the value of the current second, storing it in the variable $CurrentSecond. Then the ‘Start-Sleep‘ cmdlet pauses the script for one second, a star is written to the screen to serve as a visual counter, and the loop begins again.

If $CurrentSecond isn’t equal to 59, then the code block is run again. This will repeat until $CurrentSecond finally is equal to 59, whereupon the loop is exited, and PowerShell informs us that the computer’s time is at the top of the minute.

When we run this code, we don’t know how many times it will loop, whether it be one second’s worth or nearly a minute’s worth. If all we are concerned about is when it’s exactly the top of the minute, then we can let the ‘While‘ loop keep track of it. This sort of code block would be difficult to construct with a ‘for‘ statement or a ‘foreach‘ loop because it would be impossible to know how many times the code block needs to loop until the top of the minute. 

Loops are a powerful and common tool in both scripting languages like PowerShell, and in fact all programming languages like Python, Java, and C#. Use loops to perform repetitive tasks quickly and easily.