PowerShell For loop

For loop - do you actually need it, since there’s foreach loop? Turns out, yes - there are situations where for loop comes very handy. In this video I’ll show you the basic syntax of the for loop, going through nested for loops to end up with real case scenario from Azure Application Insights. # Link to the video: https://youtu.be/YQnBVn-9SN0 # Documentation: # https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_for?view=powershell-7.1 # Basic syntax: # for (Initial Value/statement; Condition; Repeat) { Run my code } # Initial value: Set this is up before starting the loop # Condition: For loops ends, when condition evaluates to false; or it keep running as lon as condition is true # Repeat: Do this after every loop for ($MyVariable = 0; $MyVariable -lt 10; $MyVariable = $MyVariable + 1) { '$MyVariable is {0}' -f $MyVariable Start-Sleep -Seconds 2 } for ($MyVariable = 0; $MyVariable -lt 99; $MyVariable++) { '$MyVariable is {0}' -f $MyVariable } # We can also decrease it for ($MyVariable = 10; $MyVariable -gt 5; $MyVariable = $MyVariable - 1) { '$MyVariable is {0}' -f $MyVariable } # or specify variable outside if $outside = 7 for (; $outside -lt 15; $outside++) { '$Outside is {0}' -f $outside } #Looping through array $pets = @("Cat", "Dog", "Fish", "Turtle") $pets....

14 July 2021 · 3 min · 544 words · Kamil