Datasheet
28 CHAPTER 1
•
USING POWERSHELL WITH ACTIVE DIRECTORY
statement can either end or test to see if something else is true. For example, con-
sider the following
If
statement:
$RunningProcesses = Get-Process
$RunningProcesses | ForEach-Object {
$MemUsageMB = $_.PrivateMemorySize / 1024 / 1024
If ($MemUsageMB -lt 50)
{
Write-Host $_.Name “: Using less than 50MB of memory”
}
Else
{
Write-Host $_.Name “: Using “ $MemUsageMB “MB of memory”
}
}
If you execute this script, the output lists every running process and, if it’s using
more than 50 MB of memory, displays the amount of memory that the process is
using. e
ForEach-Object
command loops through all the processes. For each
process, the
If
statement is evaluated. e
If
statement checks to see whether the
amount of memory is less than 50. If so, it writes to the screen that the process is
using less than 50 MB of memory. If the process is using more than 50 MB, the
Else
statement is executed, and instead, the script outputs to the screen the name
of the process and the amount of memory that it’s using.
e
-lt
parameter indicates that the
If
statement is checking whether
$MemUsageMB
is less than 5
0
. In typical programming languages, this is usually
accomplished with the symbol
<
. Instead, PowerShell uses the comparison opera-
tors listed in Table 1.6.
In addition to the
If
statement, you can use the
Where-Object
command.
Where-Object
evaluates the objects that are piped into it and lters out everything
that doesn’t meet the expression you set. For example, you can use the following
Where-Object
command in a script to lter out all processes that are using less
than 50 MB of memory:
Get-Process | Where-Object { $_.PrivateMemorySize / 1024 / 1024 -gt 50 }
| ForEach-Object { Write-Host $_.Name }
In this command, the
Where-Object
cmdlet is passing through every process that
is using more than 50 MB of memory. e processes that are passed through the
lter are piped into the
ForEach-Object
cmdlet so they can be further processed,
and the information is displayed on the screen.
c01.indd 28c01.indd 28 5/12/2011 1:07:50 PM5/12/2011 1:07:50 PM










