By introducing loops into scripts it is possible to repeat a block of code multiple times without having to write the same code over and over again. This makes your code more concise, more readable, and more maintainable.
There are two main types of loops in PowerShell: for loops and while loops.
For Loops
Are used to iterate over a sequence of values, such as a list or a string.
While Loops
Are used to repeat a block of code as long as a certain condition is true.
By being able to repeat code blocks it is possible to automate repetitive tasks and perform operations on large amounts of data. For example, you might use a loop to process a large dataset, or to automate a series of calculations that would be tedious to do by hand.
3rd PowerShell Script
The third PowerShell script created is:
These loops have varying levels of complexity to achieve different outputs. While PowerShell does not require all loops to use indentation, it is best practice as it provides an easier way to read the script.
For Loop 1
Loop 1 creates a variable called x, and has it output each character that makes up the string “NorthGreen”. This loop is created with the following line
A breakdown of the command is as follows:
· For – starts the loop
· $i=0; – sets the initial value of the variable i to 0
· $i -lt “NorthGreen”.Length; - sets the upper limit of the loop. The .Length function calculates the length of the string (10 Characters). So this section is saying that “for as long as the value of i is less than 10”
· $i++ - increment the value of i by 1
The output command then instructs the appropriate value of i in the string to be printed to the command line
It is important to note that the first N has a value of 0 from an array perspective
For Loop 2
Loop 2 uses an array of the days of the week and outputs each day in turn. The foreach keyword is used here, this is because in Powershell when working with a collection of data or an array foreach handles the data better.
As the loop iterates through the days array, each element is assigned to the parameter x, which is then printed.
For Loop 3
Loop 3 demonstrates how a nested loop can be implemented in PowerShell. It is important to make sure that for every loop that opens with a brace ({) that there is a corresponding close (}). This example, as with our others, shows that the x in days loop then runs the nested loop of y in meals and outputs both variables.
While Loop
While loops are used to execute a command for as long as a condition is true. In the first while loop,
The value of “i” is printed to the terminal and increased by 1 for as long as the value is less than 5. This condition is created at the beginning of the loop by using the command