Taking Multiple Actions by Using If Then Else
Microsoft® Windows® 2000 Scripting Guide
The script shown in Listing 2.10 displays a warning message if a disk drive is low on disk space. If a disk drive has adequate free space, however, no message of any kind is displayed. For a simple monitoring script this is probably acceptable. On the other hand, a user running this script would have no way of knowing whether the lack of output was because all the drives had adequate disk space, or whether the lack of output was because the script failed to run for some reason.
In other words, sometimes you want your script to evaluate a condition and then take a different course of action based on that evaluation. For example, you might want to echo a warning message if a drive is low on disk space and echo a "No problem" message if a drive has adequate disk space. This kind of approach can be implemented by using an If Then Else statement.
If-Then-Else statements work exactly as the name implies: If a condition is True (or False), Then take this course of action, Else take this course of action. If disk space is low, echo a warning message; otherwise, echo a "No problem" message.
An example of this is shown in Listing 2.11. In line 8, the amount of free disk space on a drive is compared against a warning threshold. If the conditional statement is True (that is, if the amount of free disk space is less than the warning threshold), then line 9 runs.
But what if the conditional statement is False? To handle this possibility, an Else statement is included on line 10. If the conditional statement is False, and the drive has adequate space, then line 11, the line immediately following the Else statement, runs instead.
Listing 2.11 Using an If-Then-Else Statement
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
It is possible to construct more elaborate scenarios, scenarios that can take more than just two possible courses of action. Two different ways to construct these scenarios are discussed later in this chapter.