PowerShell: How to Run a Loop X Number of Times


You can use the following basic syntax to run a loop X times in PowerShell:

1..10 | ForEach-Object { Write-Host $_ }

This particular example uses a loop to print the values 1 through 10.

Here is how this syntax works:

  • First, we use 1..10 with the start..end notation to create a range of numbers from the start value of 1 to the end value of 10.
  • We then pipe this into a ForEach-Object cmdlet to perform some action for each value between 1 and 10.
  • Lastly, we use Write-Host to write the current loop number ( $_ ) to the output.

Note that you can include any code that you’d like within the curly brackets of the ForEach-Object cmdlet to perform more complex operations.

The following example shows how to use this syntax in practice.

Example: How to Run a Loop X Number of Times in PowerShell

We can use the following syntax to run a loop 10 times that simply outputs the values from 1 to 10:

1..10 | ForEach-Object { Write-Host $_ }

The following screenshot shows how to use this syntax in practice:

PowerShell loop X number of times

Notice that this prints the values ranging from 1 to 10.

Note that we could also include custom text in the output if we’d like:

1..10 | ForEach-Object { Write-Host "Loop Number $_" }

The following screenshot shows how to use this syntax in practice:

This loop prints the text “Loop Number” followed by a number between 1 and 10.

Note that we could also use the % symbol as an alias for the ForEach-Object cmdlet if we’d like to use shorter syntax:

1..10 | % { Write-Host "Loop Number $_" }

The following screenshot shows how to use this syntax in practice:

Notice that this returns the same results as the previous example.

Feel free to use whichever syntax you would like.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Use Where-Object in List
PowerShell: How to Use Where-Object is Not Null
PowerShell: How to Use Where-Object with Multiple Conditions

Leave a Reply