11.3. Conditional Expressions
Any script code beyond the most basic requires the ability to do one thing if a certain condition is specified and to do something else if the condition is not satisfied. An expression that allows such decisions to be made is called a conditional expression.
Windows PowerShell supports two conditional expressions:
The if statement with its variants that include an else clause
The switch statement
11.3.1. The if Statement
The simplest form of the if statement allows you to evaluate an expression, and depending on the result of the evaluation, to optionally execute a block of Windows PowerShell code.
The following script, contained in the file ifExample.ps1, demonstrates simple usage of a single if statement. The script is available for downloading from this book's web site.
write-host "This example shows a simple if statement in use." $a = read-host -prompt "Enter a number between 1 and 10" if ($a -lt 3) {write-host '$a'" is less than 3"}
The read-host cmdlet accepts a number from the user. If the user enters a value less than 3, the test part of the if statement:
if ($a -lt 3)
returns true. Therefore, the statement block (in this case a single statement) contained between the paired curly brackets, that is:
{write-host '$a'" is less than 3"}
is executed and writes the message " $a is less than 3" to the console. Should the test part of the if statement evaluate to $false, then the statement block is not executed. In this simple example, no code is ...
Get Professional Windows® PowerShell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.