Datasheet

UNDERSTAND THE BASICS OF POWERSHELL 27
Administering
Service Delivery
PART I
If you were to run this code in a PowerShell script, the output would read
Current Number: 0
Current Number: 1
Current Number: 2
e
Do
statement loops through the code inside the curly brackets for as long as
the condition speci ed in the
While
statement is valid. In this example, the
Do
loop will keep going as long as the
$counter
variable is less than 3 (
-lt 3
). A er
$counter
reaches 3, the loop stops, and therefore only the numbers 0, 1, and 2
are displayed. With a
Do ... While
loop, the code inside the curly brackets is
executed  rst, and then the condition determining whether it should keep going is
evaluated.
On the other hand, a
Do ... Until
loop processes the condition  rst. To under-
stand this, we’ll turn the previous code into a
Do ... Until
loop:
$counter = 0
Do
{
Write-Host “Current Number: $counter”
$counter++;
} Until ($counter -gt 3)
is time, the
Do
loop will continue to process until
$counter
is greater than 3.
Before the code in the
Do
loop is processed even once, the condition is evaluated to
make sure
$counter
is still 3 or less.  e following is the output if this code is run
in a script:
Current Number: 0
Current Number: 1
Current Number: 2
Current Number: 3
A er the script displays that the current number is 3,
$counter
is incremented
to 4.  is causes the condition
($counter -gt 3)
to be met because 4 is greater
than 3, and the
Do
loop is no longer processed.
Conditionals
In addition to loops, you can use conditionals to make decisions inside your scripts.
One conditional that you’ll probably use o en is
If ... Else
.  e
If
statement
tests whether something is true. If it is, it executes some code. If not, the
If
c01.indd 27c01.indd 27 5/12/2011 1:07:50 PM5/12/2011 1:07:50 PM