Can you use FOR loop to change wheels in your car?

Hi, Damian Garbus here and this is Poshland blog about Powershell. 
Several posts ago I wrote the post about “FOREACH” loop, which is very popular so it’s time to show FOR loop. Let’s do this. 

For vs. Foreach

As I wrote in the introduction several posts ago I wrote about another type of loop. So First what you can do is read about this post and return here.

The difference between “For” and “Foreach loop is that Foreach uses all things declared in the variable (objects in the array) and “For loop uses numbers for this (int variable type). Maybe the example will be more clear. I will use the same example from the post about foreach loop.

$MyWheels = "Front Left Wheel", "Front Right Wheel", "Rear Left Wheel","Rear Right Wheel"
foreach ($wheel in $MyWheels) { 
    Write-Host "Unscreew $wheel"
    Write-Host "Change tire"
    Write-Host "Fix $wheel"
$NumberOfWheels = 4
for ($currentWheel=1; $currentWheel -le $NumberOfWheels; $currentWheel++) {
    Write-Host "Unscreew $currentWheel wheel"
    Write-Host "Change $currentWheel tire"
    Write-Host "Fix $currentWheel wheel"

To understand the difference you have to analyze these two examples. In the first, I use wheels like an object but in a second I only use the number of wheels in my car. I don’t have named them.

Try to do the same like Foreach

OK, so I will try to do the same example using “For” loop in order to take the same result as “Foreach” loop. When you have wheels you can check how many are in your car.

$MyWheels = "Front Left Wheel", "Front Right Wheel", "Rear Left Wheel","Rear Right Wheel"
#Check how many wheels you have
#Declare new variable - it's not nessesary because you can use $MyWheels.count
$NumberOfWheels = $MyWheels.count

for ($currentWheel=0; $currentWheel -lt $NumberOfWheels; $currentWheel++) {
    Write-Host "Unscreew $($MyWheels[$currentWheel])"
    Write-Host "Change $($MyWheels[$currentWheel])"
    Write-Host "Fix $($MyWheels[$currentWheel])"

Maybe For loop is unnecessary

Wrong idea. It’s necessary for many examples. Sometimes, when you don’t have objects but only you know how many times do the same, then you can use FOR loop. I know that it’s used rarely but it’s important to know about this type of loop in Powershell and other programming languages.

Get Access to Poshland Resources for FREE!!!

Signup now and receive an email once I publish new content.

I agree to have my personal information transfered to MailerLite ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.