Some tasks need to be repeated for a variety of variables or processes. In this tutorial, you will learn how to use for-loops in PowerShell.
If you have not already done so, click open Windows PowerShell ISE. Think of two programs that you use the most. For the purpose of writing this tutorial, notepad and internet explorer are selected.
Normally, the for-loop is used when you want to loop through some code a defined number of times. Granted, there is a way for one to make it run an infinite number of times, however for a defined number for repetition, the for-loop is suggested.
The for-loop is implemented as follows:
for ($i = 1; $i -1e 5; $i++)
The output will then contain the digits one through five inclusive in the output pane. Each digit will be on its own corresponding line, as they appear below.
To break the for-loop code down, essentially the first part where the variable $i was initialized to 1, is known as the initialization expression. The second part is $i -le 5, this establishes the condition that must return true for the loop to continue and is typically evaluated for each repetition of the loop. In the case that the expression returns false, the loop then is concluded. The code reads, until variable $i is less than or equal to 5, continue on.
The last part, $i++, is a counting section. It too, is executed once per repetition of the loop after each loop-block process is complete. The code merely implies to increase the value of variable $i by one. The code within the braces can do whatever function needed of course; it doesn't have to remain with an arithmetic function.
For-loops are used for a variety of functions and are a great way to begin the concept of repetition in coding. PowerShell is an automation scripting language, the use of repetition is actually strongly emphasized in future tutorials. Join us next time for additional Windows PowerShell tutorials! Till then!