Loops
Looping
Looping is similar than in any programming language. You have a collection of items that you iterate through one by one.
You can use looping constructs, such as ForEach
, For
, and While
loops, to iterate the elements in an array.
Foreach
An example, to use a ForEach
-loop to display the elements in the $a array:
$names = 'Jack', 'Jill', 'Jake'
foreach ($name in $names) {
$hello = 'Hello ' + $name
$hello
}
Or if we want to make shorter, it can be written to one line like this:
$names = 'Jack', 'Jill', 'Jake'
foreach ($name in $names) {"Hello my friend $name"}
Foreach
can be used also like a method for an array and for an object collection.
So, let's do the same as above with a method Foreach
.
$names = 'Jack', 'Jill', 'Jake'
$names.ForEach({'Hello again my friend ' + $_})
In the following sample, we will go through the array of numbers.
#raise to second power
$a = @(1 .. 5)
$a.ForEach({ $_ * $_})
ForEach
-method can be used to execute a method on every item in the collection.
#change to Uppercase
$names = 'anna', 'bella', 'cecilia'
$names.ForEach("ToUpper")
For
A for
loop iterates while a specified condition is true.
In the following example we will simulate how to create an account for four users in array.
$users = 'Al', 'Ben', 'Calle', 'Dave'
for ($i = 0; $i -lt $users.Count; $i++) {
Write-Output("I will do an account for " + $users[$i])
}
In the following example, the loop will iterate four times by starting off with the number one and continue as long as the counter variable $i is less than 5. Totally it will sleep for a total of 10 seconds.
for ($i = 1; $i -lt 5; $i++) {
Write-Output "Sleeping for $i seconds"
Start-Sleep -Seconds $i
}
Do
There are two different Do loops in PowerShell. Do Until
runs while the specified condition is false. Do While
runs as long as the specified condition is evaluated to true.
Example of do-loop
#let's set a number randomly between 2-21
$number = Get-Random -Minimum 2 -Maximum 21
#user will guess as long as she get right value
do {
$guess = [int](Read-Host "What's your guess?")
if ($guess -lt $number) {
Write-Output 'Too low!'
}
elseif ($guess -gt $number) {
Write-Output 'Too high!'
}
}
until ($guess -eq $number)
#the end
Write-Output("You got it: " + $number)
Do While is just the opposite. It runs as long as the specified condition evaluates to true.
$number = Get-Random -Minimum 2 -Maximum 21
do {
$guess = [int](Read-Host "What's your guess?")
if ($guess -lt $number) {
Write-Output 'Too low!'
} elseif ($guess -gt $number) {
Write-Output 'Too high!'
}
}
while ($guess -ne $number)
#the end
Write-Output("You got it: " + $number)
While
While
is similar to the Do While loop, a While loop runs as long as the specified condition is true. The
difference is that a While loop evaluates the condition at the top of the loop before any code is run so it doesn’t run at all if the condition evaluates to false.
$max = [int](Read-Host("Give number to go"))
while($val -ne $max)
{
$val++
Write-Host $val
}
Break, Continue and Return
Break
Break
is used to break out of a loop. It's also used with the switch statement.
#in the case that database will return null we will use break
$users = 'Al', 'Ben','null' ,'Calle', 'Dave'
for ($i = 0; $i -lt $users.Count; $i++) {
if($users[$i] -eq 'null')
{
Write-Output("Illegal input, execution will be ended")
break
}
Write-Output("I will do an account for " + $users[$i])
}
Continue
Continue
is designed to skip to the next iteration of a loop.
#in the case that database will return null we will skip
$users = 'Al', 'Ben','null' ,'Calle', 'Dave'
for ($i = 0; $i -lt $users.Count; $i++) {
if($users[$i] -eq 'null')
{
Write-Output("Illegal input, account is not created")
continue
}
Write-Output("I will do an account for " + $users[$i])
}
Return
The return
keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached.
In PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C# return only the value or values that are specified by the return keyword.
ForEach-Object
ForEach-Object
is a cmdlet with parameters that can be employed in a lot of different ways. Like the foreach statement, the ForEach-Object cmdlet can iterate over a set of objects.
The ForEach-Object cmdlet performs an operation on each item in a collection of input objects. You point each item with a built-in variable $_
The input objects can be piped to the cmdlet.
In the following example FileInfo-objects are piped to the cmdlet ForEach-Object.
Get-ChildItem | ForEach-Object {Write-Host "you got a file named $_"}
In the following example we will use the cmdlet ForEach-Object for calculating all objects of a collections.
$nums = 10, 100, 4200, 55500
$nums | ForEach-Object -Process {Write-Host $_ "and 24% of it is" ($_ * 0.24)}
In the following example we will use the cmdlet ForEach-Object for calculating all objects of a collections. Please, note that we use parameters Begin
and Process
to tell what to do before and during process.
Please, do not try this example in your home folder!!!
Get-ChildItem | ForEach-Object
-Begin { $count, $newname = 1, 'jacko' }
-Process { Rename-Item $_ -NewName $newname$count; $count++ }