The for statement is used to run a block code for a specified number of times.
for (initialization; condition; repeat) {
# your code here
}
Count to 20:
for ($i=1; $i -le 20; $i++) {
Write-Host $i
}
We delimit each parameter with a semi-colon (;) even if we define and initialize our variable outside the condition you need to delimit each parameter. If you forget the first semi-colon you will create an infinite loop. Use Ctrl+C to stop it.
$i=1
for (; $i -le 20; $i++) {
Write-Host $i
}
Another way of delimiting is using Carriage return.
for ($i=1
$i -le 5
$i++)
{
write-host $i
}
Processing elements of an array:
# My array with values
$myArray = @( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
for ($i=0; $i -le $myArray.Length - 1; $i++) {
Write-Host $myArray[$i]
}