PowerShell for Loop 1 to 10

PowerShell for loop from 1 to 10

Using Traditional for Loop

Use the traditional for loop to print from 1 to 10 on the PowerShell console.

In the above example, we used the traditional for loop to iterate from 1 to 10. The header of the for loop consists of three parts separated by a semicolon (;). The first part is the Initializationplaceholder, the second is called Condition or Test Expression, and the third is Repeat. All three parts are enclosed in parentheses (()) followed by the for keyword. Let’s understand them below:

The Initialization placeholder consists of one or multiple commands that run before the for loop starts. It is used to define and initialize a variable with an initial value. For example, in the above code, the $i=1expression is the initialization part where the i variable is initially set to 1. This variable is accountable for holding values from 1 to 10 (one at a time). Note that the variables are prefixed with $ in PowerShell.

The Condition or Test Expression placeholder returns a Boolean value (True/False) in each loop iteration. We can also have multiple conditions here. As per the above code snippet, the $i -le 10 is the Condition, which determines if the value of $i is less than or equal to 10 using the -le operator. Note that the condition is evaluated in each iteration of the loop until it becomes False. If this test expression returns True, the body of the for loop (enclosed within {}) gets executed; otherwise, it does not.

The Repeatpalceholder represents one or multiple commands separated by a comma (,); it is used to update the variable’s value, which is checked inside the Test Expression part (a.k.a. Condition part) of the loop. Considering the above code example, $i++ is the repeat section which increments the value of $i by 1 using the increment operator represented by ++. Remember, we can also write $i = $i+1 instead of $i++ but $i++ seems easier, reader-friendly and professional.

We used the Write-Host cmdlet to print the value of $i with a customized message. So, the above for loop starts printing from 1 to 10 and exits from the loop as soon as i=11. So, what is the execution flow of the for loop?

  1. Initialization part will be executed.
  2. The condition will be evaluated.
  3. The script block (body of the for loop) will be executed if the condition is true.
  4. The repeat part will be executed.
  5. The updated value will be checked via the specified condition.
  6. Now, steps 3, 4, and 5 will be repeated until the condition becomes false.

There is an alternate syntax for using the traditional for loop, which is given below:

We replaced the ; with a new line in the above code snippet.

Use Multiple Commands in for Loop Header

Use multiple commands in the header of the traditional for loop, iterate 10 times and print a customized message on the PowerShell console.

This example is similar to the previous one, but we involved two variables, i and j, to use multiple commands in each section of the for loop. We can also do Initialization outside of the for loop as follows:

Similarly, we can do the Repeat section within the script block; see the following example.

We can also display a constant value or string (which does not change) for every iteration of the loop for an unlimited time until the user stops it. See the following example.

Unlimited Iterations using for Loop

Omit all commands from the traditional for loop header to iterate unlimitedly.

This time, we do not have any command enclosed within the () except two semicolons which results in unlimited execution of the script block wrapped around with {}. It will continue printing Welcome to Java2Blog! until the user presses Ctrl + C.

Let’s see another example where the value changes with each iteration but still runs for unlimited times until the user hits the Ctrl + C.

Using ForEach Loop

Use the ForEach loop to print values from 1 to 10 on the PowerShell console.

First, we created an array using the array operator (@()) containing 10 integer values (one to ten), which we assigned to the $array variable. Next, we used the ForEach to loop over the $array. Finally, we used the Write-Host cmdlet in each iteration to print the current value from the $array.

Remember, the ForEach loop (a.k.a. ForEach statement) is also used for traditional looping constructs for stepping through items in a collection, such as arrays. The ForEach loop has two parts enclosed within (). In the first part, a variable is automatically created when PowerShell runs the ForEach statement; in the above code, it was $i. The second part is the collection ($array) on which the loop will be iterated.

Unlike the for loop, we can not directly have multiple commands in each part of the ForEach header to work on various arrays or collections, but there is the other way around. So let’s see how we can do it.

Work with Multiple Arrays using ForEach Loop

Use the Zip() method to work with multiple arrays in the ForEach loop and iterate 10 times.

First, we created two arrays, $names having names and $ages containing the ages of the students. Then, we must zip both arrays to work on $names and $ages within the ForEach. Why are we zipping them? Because we can’t use multiple commands within the ForEach header to iterate over $names and $ages. So, we used the Zip() method of System.Linkq.Enumerable class to combine $names and $ages into tuples. Note that zipping both arrays will not modify the original arrays.

The Zip() method took three arguments whose brief description is given below sequentially:

  1. The $names array that we want to zip with the second array.
  2. The $ages array that we want to zip with the first array.
  3. This argument is a delegate specifying how to combine $names and $ages. In the above code, it is defined using the [System.Func[object, object, object]] type representing that it will take two object arguments and will return an object. It creates a Tuple object with two arguments ($args[0] and $args[1]) corresponding to the items of the two arrays being zipped.

We stored the tuple, returned by the Zip() method, in the $zipped variable, which was further passed to the ForEach. Then, inside the ForEach, we used the Write-Host cmdlet to print customized messages.

Pipe Input to ForEach Loop

Pipe input to the ForEach loop to iterate from 1 to 10 in PowerShell.

Alternatively, we can do the above example as follows if creating an array is not mandatory.

The .. was used to create a range of numbers in PowerShell.

Unlimited Iterations using ForEach Loop

There is no direct way to use ForEach for unlimited iterations, but we can use while with ForEach to do infinite iterations; otherwise, a traditional for loop can be used for this particular scenario (we have learned traditional for in the first section).

Here, we did not specify the test condition for the while loop to end but mentioned $true within the (), which means the while loop would always be True and cause ForEach loop’s execution for an unlimited time until the user hits Ctrl+C.

The for and ForEach loops are both traditional looping constructs, but ForEach is the simplest and easiest way to loop over a collection and can be used with the pipeline. On the other hand, using traditional for is more straightforward than ForEach while working with multiple arrays or commands.

Using ForEach-Object Cmdlet

Use the ForEach-Object cmdlet to loop from 1 to 10 in PowerShell.

First, we specified a lower number before the .. operator and an upper number after it. Then, we stored this range of numbers in the $range variable, piped with the ForEach-Object cmdlet to iterate over it and display one element on each iteration using the Write-Host cmdlet. The ForEach-Object cmdlet performs the given operation on each element of the collection of input objects.

Alternatively, we can do as follows:

Here, % means for each object in the given range, which was 1..10.

Remember, the ForEach-Object is only used when input data is piped to it.

Work with Multiple Arrays using ForEach-Object Cmdlet

Use the ForEach-Object cmdlet with -Begin and -Process parameters to work with multiple arrays and iterate 10 times.

After creating $names and $ages arrays, we piped the $names to the ForEach-Object cmdlet and used -Begin and -Process parameters to iterate over both arrays ($names & $ages) simultaneously.

Inside the -Begin block, we set the $i to 0. Then, in the -Process block, the current element from the $names array was accessed in the pipeline using $_ and the corresponding age from $ages using the $i variable. Finally, we used Write-Host to print those on the PowerShell console.

Unlimited Iterations using ForEach-Object Cmdlet

Unlike the ForEach loop, there is no direct way to use ForEach-Object for unlimited iterations, but we can use while with ForEach-Object to do unlimited iterations; otherwise, traditional for loop can be used for this use case.

This loop will only end if the user presses Ctrl+C from the keyboard.

That’s all about PowerShell for loop 1 to 10.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *