Export (0) Print
Expand All
6 out of 8 rated this helpful - Rate this topic

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


Const CONVERSION_FACTOR = 1048576
Const WARNING_THRESHOLD = 100
Computer = "atl-dc-01"
Set objWMIService = GetObject("winmgmts://" & Computer)
Set colLogicalDisk = objWMIService.InstancesOf("Win32_LogicalDisk")
For Each objLogicalDisk In colLogicalDisk
 FreeMegaBytes = objLogicalDisk.FreeSpace / CONVERSION_FACTOR
 If FreeMegaBytes < WARNING_THRESHOLD Then
 Wscript.Echo objLogicalDisk.DeviceID & " is low on disk space."
 Else
 Wscript.Echo objLogicalDisk.DeviceID & " has adequate disk space."
 End If
Next

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.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.