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

The Infinite Forbidden Set Stats

Yu-Gi-Oh! The Infinite Forbidden launched in the TCG on July 19, 2024. I’ve been excited for this set since its announcement because of the nostalgia-bait of Exodia. As a core set, it’s full of new cards, strategies, and archetypes. The highly anticipated Fiendsmith makes its TCG debut just in time for the Yu-Gi-Oh! NAWCQ. Exodia, White Forest, and Gimmick Puppet get support, and a new TCG-exclusive archetype called Mimighoul makes its debut.

Read More

Help! I’m Missing haptic feedback in Beat Saber

The haptic feedback in Beat Saber just stopped working. I knew it wasn’t the controller since vibrations were working outside of Steam or Beat Saber. I didn’t realize how much the haptic feedback contributed to VR immersion, but wow, did I miss it.

Read More