Windows PowerShell automatically handles the
memory allocation for me.
CONDITIONAL STATEMENTS
One of the most important features needed in any scripting environment is the ability to
define conditional statements such as if x equal 2 then do this otherwise do something else.
After all, without conditional statements such as If/ElseIf/Else combinations, you
can??™t really implement any kind of logic in your script. The key to being able to create
branches in your code is to combine conditional statements with comparison operators
to make decisions based on values of variables within your script. Here??™s an example:
$a = 5
if ($a -eq 1) {
write-host "One"
}
elseif ($a -eq 2) {
write-host "Two"
}
else {
write-host "Anything but One or Two!"
}
Hopefully you can follow this slightly longer code snippet. First, you assign the value
of 5 to $a. Then check if the value of $a is equal to 1 and, if it is, you output One to the
screen. If $a is not equal to 1, check whether it is equal to 2 and output Two if it is. If
neither condition is met, the string Anything but One or Two! is displayed. Based
on the value of $a being 5, this script will output Anything but One or Two! Try
changing the value of $a to a different number to see the output.
447 Chapter 13: Windows PowerShell
In the preceding example, we have used the -eq comparison operator to check
whether the variable equaled a certain value.
Pages:
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475