PowerShell Loops

 

 

There are several different types of loops in PowerShell I am going to show the basic format of 5 of them:

The IF 

Switch

Do while

Do Until

ForEach

and The For Loop

The if loop has the following syntax (check out help about_if )

if (<test1>)
{<statement list 1>}
[elseif (<test2>)
{<statement list 2>}]
[else
{<statement list 3>}]

$q = read-host -Prompt “Enter Yes No or Maybe”

If ($q -eq “yes”){
    Write-host “You entered Yes”}
elseif ($q -eq “No”){
    Write-host “You Entered No”}
elseif ($q -eq “Maybe”){
    Write-host “You entered Maybe” }
else { Write-Host “Your not taking this question seriously”}

The Switch construct has the following Syntax:

From help about_switch

A basic Switch statement has the following format:

Switch (<test-value>)
{
<condition> {<action>}
<condition> {<action>}
}

$q = read-host -Prompt “Enter Yes No or Maybe”

switch ($q)
{
‘Yes’ {Write-Host “you entered Yes”}
‘No’ {Write-Host “you entered No”}
‘Maybe’ {Write-Host “you entered Maybe”}
Default {Write-Host “you didn’t take the question seriously”}
}

Do-While and Do-Until (from help about_do)

The following shows the syntax of the Do-While statement:
do {<statement list>} while (<condition>)
The following shows the syntax of the Do-Until statement:
do {<statement list>} until (<condition>)

$x = 10

do
{
Write-host $x
$x–
}
while ($x -gt 0)

The results of this script is:

do
{
Write-host $x
$x–
}
while ($x -gt 0)
10
9
8
7
6
5
4
3
2
1

The do-until command is slightly different

To achieve the same results you have to change the condition to 0

$x = 10
do
{
Write-host $x
$x–
}
until ($x -eq 0)

ForEach (from help about_foreach)

Syntax
The following shows the ForEach syntax:
foreach ($<item> in $<collection>){<statement list>}

$computers = @(“workstation1”, “WS2”, “windows7”, “Windows8”)

foreach ($computer in $computers){
Write-host “$computer”
}

For (from help about_for)

Syntax
The following shows the For statement syntax.
for (<init>; <condition>; <repeat>)
{<statement list>}

for ($i = 1; $i -lt 10; $i++)
{
write-host $i
}

another way of using this is to scroll through an array

$s = Get-Service

for ($i = 1; $i -lt 10; $i++)
{
$a = $s[$i]
write-host $a
}

Leave a Reply

Your email address will not be published. Required fields are marked *