Datasheet
26 CHAPTER 1
•
USING POWERSHELL WITH ACTIVE DIRECTORY
Add Logic to a Script
Logic allows your scripts to do things to the variables you’re using and make deci-
sions about what to do. You need to know two basic logic concepts in order to write
PowerShell scripts: loops and conditionals.
Loops
Loops allow you to go through a collection of items and do something to each
item. For example, if you run the
Get-Process
cmdlet on one of your servers,
PowerShell displays a list of processes that are currently running on that server.
However, you can assign the output of
Get-Process
to a variable, using the
following command:
$RunningProcesses = Get-Process
In the
$RunningProcesses
variable, each process is represented by a di erent
object. You could loop through the objects in this variable and do something to
each object, such as display the process ID of each process. One way to accomplish
this is with the
ForEach-Object
cmdlet:
$RunningProcesses | ForEach-Object { Write-Host $_.Name : $_.Id }
By piping the
$RunningProcesses
variable into the
ForEach-Object
cmdlet, the
ForEach-Object
cmdlet can cycle through all the objects. e command inside
the curly brackets (
{...}
) is executed for each of the objects processed by the loop.
You may recognize the
$_
variable from Table 1.5. e
$_
variable references the
current object that the loop is processing. So when
$_.Id
is used, you’re working
with the
Id
property on each of the objects in the variable. In this case, we’re calling
the
Write-Host
cmdlet to output the
Name
and
Id
of each process to the screen.
Another type of loop you can use is
Do
. e
Do
loop allows you to loop until
a speci c condition is met. ere are two types of
Do
loops:
Do ... While
and
Do ... Until
.
In a
Do ... While
loop, a block of script code is executed over and over again as long
as something is happening. For example, consider the following script code snippet:
$counter = 0
Do
{
Write-Host “Current Number: $counter”
$counter++;
} While ($counter -lt 3)
c01.indd 26c01.indd 26 5/12/2011 1:07:50 PM5/12/2011 1:07:50 PM