Let’s do some loop’s, while, for, do until.
The ForEach-Object we already discussed.
The While loop is pretty simple one:
While(<whats in here is true>)
{
repeat this code here
}
Simple example
$i = 0 while($i -lt 5) { #print the value of $i $i #add 1 to $i equal to $i = $i + 1 $i++ }
Another more productive example:
#Read a file into $content variable $content = Get-Content "C:\Temp\myTextFile.txt" #Let's check what type or variable we are getting $content.GetType() $i = 0 #while $i is less then $content.Length which is the number of objects in our array while($i -lt $content.Length) { #Print string object $i from $content array which represents a line from C:\Temp\myTextFile.txt $content[$i] $i++ }
The for loop, in the for loop we have the initialization, condition and repeat inside the brackets like this:
for(initialization;condition;repeat)
{
Repeat the code here
}
This code will do the same as our first while example:
for($i=0;$i -lt 5;$i++) { $i }
The Do Until first does then checks:
Do
{
Repeat the code here
}
Until(<UNTIL THIS IS TRUE>)
For example:
$i = 0 Do { $i $i++ } Until($i -eq 5)
This is a nice one:
0..4 | %{ $_ }
We already discussed the:
foreach($item in $items) { do something with $item }
And the:
$items | ForEach-Object{ Do something with $_ (which is the current object) }
The same as:
$items | %{ Do something with $_ (which is the current object) }
Tagged: Do Until, For, ForEach, Get-Content, Loop, Loops, While
Leave a comment