Loops

Simple while loop:

Clear-Host
$i = 1
while ($i -le 5)
{
    "`$i - $i"
    $i = $i + 1
}

Simple do-while loop:

Clear-Host
$i = 1
do
{
    "`$i = $i"
    $i++
} while ($i -le 5)

Simple do-until loop:

Clear-Host
$i = 1
do
{
    "`$i - $i"
    $i++
} until ($i -ge 6)

Simple for loop:

Clear-Host
for ($f = 0; $f -le 5; $f++)
{
    "`$f - $f"
}

Can set the initializer outside the loop:

# Outputs 2, 4, 6, 8, 10
Clear-Host
$f = 2;
for (; $f -le 10; $f += 2)
{
    "`$f - $f"
}

One way to loop through a collection:

Clear-Host
$array = 11,12,13,14,15
for ($i = 0; $i -lt $array.Length; $i++)
{
    "`$array[$i] = " + $array[$i]
}

An easier way is to use foreach:

Clear-Host
$array = 11,12,13,14,15
foreach ($item in $array)
{
    "`$item = $item"
}

Using foreach on a range of values:

Clear-Host
foreach ($num in 1..5)
{
    $num
}

Using foreach on the output of a cmdlet:

Clear-Host
Set-Location "C:\Temp"
foreach ($file in Get-ChildItem)
{
    $file.Name
}

More complex example:

# Output the names of all text files in the C:\Temp folder
Clear-Host
Set-Location "C:\Temp"
foreach ($file in Get-ChildItem)
{
    if ($file.Name -like "*.txt")
    {
        $file.Name
    }
}

Can break/continue to a specific loop using loop labels:

# Only outputs 1 in the outside loop and 4 in the inside loop
Clear-Host
:outsideloop foreach ($outside in 1..3)
{
    "`$outside = $outside"
    foreach ($inside in 4..6)
    {
        "    `$inside = $inside"
        break outsideloop
    }
}

results matching ""

    No results matching ""