If


The If statement also executes a block of code if some condition is met. However, this construct can also execute a block of code if the condition is not met. For this reason, If is more of a decision making construct instead of a looping one:

 if (<condition>)    {<code_block1>} [else    {<code_block2>}] 

The Else section is optional. Here's a quick one line example:

 PS C:\> $i=1 PS C:\> if ($i -le 10) {write-host "less than 10"} less than 10 PS C:\> 

This example says that if the condition contained within the parentheses is TRUE, then execute the code in the braces. Since $i is less than 10, the code is executed.

If we want a block of code to run if the condition is not TRUE, then we introduce the Else operator.

IfTest.ps1

image from book
 #IfTest.ps1 $i=11 if ($i-le 10) { "Less than 10" } else { "Greater than 10" } 
image from book

In simple English, if $i is less than 10, then execute the first block of code, otherwise execute the second block of code. By the way, you are very likely to see code snippets where the If Else statement is all on a single line like this:

 PS C:\> $var=get-wmiobject -class win32_logicaldisk | ` >> where {$_.deviceid -eq "C:"} >> PS C:\> $5GB=(1024*1024*1024)*5 PS C:\> if ($var.freespace -le $5GB) {"Low space"} else {"OK"} Low space PS C:\> if ($var.freespace -le 10000) {"Low space"} else {"OK"} OK PS C:\> 

The If statement in this example is checking if the free space on drive C:, which we obtained through WMI, is less than some value. If so then a "Low Space" message is displayed. Otherwise an "OK" message is displayed.

Formatting the Expression

As long as you have the proper syntax with parentheses and braces, it is up to you on how you format the expression. You can either break it into different lines as we did in IfTest.ps1 or stick to a single line as we did in the example above. If you have several lines of code or commands that you want to execute, you'll find it easier to write and troubleshoot by breaking the statement into multiple lines.

But what about a situation where if a condition is not true you want it to check for other conditions before resorting to an Else statement? PowerShell supports an ElseIf component to the If statement:

 if (<condition>)    {<code_block1>} Elseif (<condition2>)    {<code_block2>) else    {<code_block3>} 

Here our previous example is expanded to demonstrate:

IfElseIfTest.ps1

image from book
 #IfElseIfTest.ps1 $i=45 if ($i -le 10) { write-host "Less than 25" } elseif ($i -le 50) { write-host "Less than 50" } else { write-host "Greater than 50" } 
image from book

The logic of this example is that if $i is less than 10, and then execute the first block of code. If it is not, then the ElseIf condition is evaluated. If this condition is TRUE, then the second block of code is executed. If even this condition is FALSE, then the last Else statement is reached and the last block of code is run.

You can have as many ElseIf statements as you want. However, from a practical perspective more than one or two will make your code a little harder to troubleshoot. If you want to evaluate multiple conditions, a better operator to use is Switch, which is discussed below.

Finally, even though it may not be technically required, if you include ElseIf, you should end your If statement with an Else clause. Let's look at a practical example that combines several logic constructs in a single script. The script checks the cpu time for each running process. If the cpu time is less than 300 seconds, the script displays the process name and cpu time in green. If the cpu time is greater than 301 and less than 1000, the process displays the information with no color coding. Otherwise the process information is displayed in red:

ProcessCPU.ps1

image from book
 #ProcessCPU.ps1 $process=get-process $low=0 #counter for low cpu processes $med=0 #counter for medium cpu processes $high=0 #counter for high cpu processes foreach ($p in $process) { [int]$cpuseconds="{0:F0}" -f $p.cpu  if ($cpuseconds -le 300) {   write-host $p.name $cpuseconds "seconds" -foregroundcolor "Green"   $low++  elseif (($cpuseconds -ge 301) -AND ($cpuseconds -le 1000)) {   write-host $p.name $cpuseconds "seconds"   $med++   }  else   {   write-host $p.name $cpuseconds "seconds" -foregroundcolor "Red"   $high++   } } #display a summary message write-host `n"Process Summary" write-host "-->" $low "low CPU processes" write-host "-->" $med "medium CPU processes" write-host "-->" $high "high CPU processes" 
image from book

This script uses a number of PowerShell elements that we've covered up to this point. The script begins by initializing some variables, including one that holds the output of the Get-Process cmdlet. We then use ForEach to enumerate each element of the $process object. Remember, it is a collection. Within this construct we use If and ElseIf statements to evaluate a condition as follows. Determine if the value of $cpuseconds is greater or less than some value. For example, if the value of $cpuseconds is less than or equal to 300, then we display a message in green and increase the $low variable by one. If that isn't true, then the ElseIf statement is evaluated. If this condition is true, then the number of cpu seconds is between 301 and 1000, which means the process information is displayed. Otherwise, the Else clause is reached and the number of cpu seconds is greater than 1000, so we display the message in red.

Formatting Details

We want to point out some special characters that were used in the ProcessCPU.ps1 script. First, we specifically cast $cpuseconds as an integer type by using [int]. We did this so that our comparisons with -le and -ge would work as expected. We also used -f to format the value of $p.cpu that contains the number of seconds, and then format it to a fixed type with no decimal places. This changes a value like 180.7899632 to 181. Finally, the `n instructs PowerShell to write a blank line to the console. It helps separate the summary section from the rest of the output.

Here's an excerpt of the script's output:

 svchost 73 seconds svchost 47 seconds svchost 1133 seconds svchost 27 seconds svchost 261 seconds svchost 24 seconds System 5645 seconds wcescomm 12747 seconds wdfmgr 9 seconds winlogon 55 seconds WINWORD 71 seconds WISPTIS 4 seconds WLTRAY 168 seconds WLTRYSVC 9 seconds wmiapsrv 654 seconds Process Summary --> 42 low CPU processes --> 4 medium CPU processes --> 15 high CPU processes PS C:\> 

You'll have to run the full script on your system to see the actual colorized output.

VBScript Alert

If you are experienced with VBScript, the PowerShell syntax for the If statement may confuse you at first. You do not need to use Then and there is no End If. Instead, they are implied in PowerShell.



Windows PowerShell. TFM
Internet Forensics
ISBN: 982131445
EAN: 2147483647
Year: 2004
Pages: 289

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net