Search

For Loops in PowerShell

One of the core building blocks for any computer language. For loops iterate in a loop (repeat) until a condition is met, or continues forever, who am I to judge! The basics of a for loop is:

for ($x = 0; $x -lt $array.Count; $x++) {
    # Repeat code in this block
}


# Another way to look at it:
for (<# $this #>; <# while $this is less/equal/greater than $that #>; <# increase/decrease $this by 1 #>){
	# Repeat code in this block
}

Try it at home!

This for loop runs 10 times since $array is set to 10. $i starts at 1 , while $i is less than or equal to $array, increase $i by 1 for each loop of the script block. I put a conditional if statement inside the script block just for fun. If $i equals the value of $array (aka the last time this block will run), then print an encouraging message followed by a pleasant roflcopter. If it isn’t the last loop, then print how many times it has run. Once it is finished, print “Finished” in the console.

$array = 10

for ($i = 1; $i -le $array; $i++) {
    if ($i -eq $array) {
        Write-Host "Congratulations! Final lap!"
        Write-Host @"
        _^___
        L    __/   [] \    
       LOL===__        \ 
        L      \________]
                I   I
               --------/
"@ -ForegroundColor White -BackgroundColor Black 
    }
    else {
        Write-Host "This ran $i time(s)!"
    }
}
Write-Host "Finished"

which will output:

This ran 1 time(s)!
This ran 2 time(s)!
This ran 3 time(s)!
This ran 4 time(s)!
This ran 5 time(s)!
This ran 6 time(s)!
This ran 7 time(s)!
This ran 8 time(s)!
This ran 9 time(s)!
Congratulations! Final lap!
        _^___
        L    __/   [] \
       LOL===__        \
        L      \________]
                I   I
               --------/
Finished

for loops are great and have so many great uses when writing PowerShell scripts. Pretty neat!

Share the Post:

Related Posts

PNG Press – Convert all those annoying .webp files quickly

PNG Press is a lightweight desktop application built using .NET Core 8. It features a simple drag-and-drop interface designed to convert one or multiple images to PNG format with ease. This project was born out of my own necessity for a straightforward image conversion tool, and I’m excited to finally share it with you.

Read More

Yu-Gi-Oh! Rarity Collection 2 Set Overview

The Yu-Gi-Oh! TCG set Rarity Collection 2 is getting mixed reviews to say the least. I’ve consulted with the Millennium items and searched the labyrinth of Atem’s mind to find this Yu-Gi-Oh! set’s stats, metrics, and other neat insights, let’s go!

Read More