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!