Windows PowerShell's If StatementIntroduction to Windows PowerShell's If StatementPowerShell's 'If' statement comes under the umbrella of flow control. Once you master the basic construction then you can increase its usefulness by appending, 'Else' and 'ElseIf' statements. Another alternative would be to use 'Switch'. Topics for PowerShell PowerShell's If Statement
♣ Construction of the 'If' StatementAs with so many PowerShell constructions, the type of bracket signifies how to break the script into sections. It is worth emphasising that (parenthesis are for the first part, the condition), while {braces are for the block command}. If (condition) {Do stuff} Example 1 Plain 'If'$Number = 10 Learning PointsNote 1: Trace the construction and separate into: if (test) and {what to do}. Note 2: Avoid over-think; there is no 'Then' in PowerShell's 'If' statement. My advice is that instead of worrying about 'Then', pay close attention to the two types of bracket. Note 3: To double check your understanding, try amending, "Bigger than Zero" to a different text string, such as: "Less than nought". Once you have done that, set $Number to -1. Example 1a File Content Example of Plain 'If'PowerShell has a batch of help files. One of these files contains help about the 'if' statement. In the example below, $File references that file. $Content is set to the content of the file. The third line attempts to match a string to the contents of the file. # Help on PowerShell's if statements Learning PointsThis example is concerned with matching a string "The if Statement" to the contents of a file. Example 2 'If' with 'Else'# Help on PowerShell's if statements Learning PointsThe best way to see how 'else' operates is to amend line 3 thus:
˚
Example 3 ElseIfThis example has a real task, and that is to check that we have the name of an actual file. # Help on PowerShell's if statements Learning PointsNote 1: The advantage of ElseIf over plain Else, is that we can introduce a new test. In the above example we use ElseIf to check if the length of the file is less than 1. To activate the 'ElseIf' block, set
$File to a non-existent file for example Note 2: To trigger the final 'Else', try changing: If you have time, you could add more 'ElseIf' statements to cater for other eventualities. Alternatively, if the ElseIf construction is getting unwieldy, then try the superior switch command.
Guy Recommends: SolarWinds LANSurveyor
|
||||||
Download my ebook:
|
*
|
|
|
|
Home Copyright © 1999-2009 Computer Performance LTD All rights reserved Please report a broken link, or an error. | |