Lessons In PowerShell - Loops

   Submit to Reddit      
  

The following useful information is primarily taken from the Windows PowerShell Language Quick Reference (QuadFold.rtf) documentation.

For

Format:

[:label] for ([initializer]; [condition]; [iterator]) {}

Example:

for ($i=0; $i -lt 5; $i++) { Write-Object $i }

For Each

Format:

[:label] 
foreach (identifier in collection) {}

Expression | foreach {}

Expression | foreach {BEGIN{} PROCESS{} END{}}

Examples:

$i = 1,2,3
foreach ($z in $i) { Write-Object $z } 

Get-Process | foreach {
    BEGIN{$x=1}
    PROCESS{$X++} 
    END{"$X Processes"}
}

Do Until

do
{ 
    ...
} until (condition)

While

[:label] while (condition)
{
    ...
}

Do While

do
{ 
    ...
} while (condition)


comments powered by Disqus