2.3 Computer system hardware classes


2.3 Computer system hardware classes

2.3.1 Input device classes

The input device classes represent keyboards and pointing devices (see Table 2.2). The Win32_Keyboard and Win32_PointingDevice classes usually have one instance available, since a computer usually has one keyboard and one pointing device.

Table 2.2: The Input Devices Classes

Name

Description

Win32 Keyboard

Represents a keyboard installed on a Windows system.

Win32_PointingDevice

Represents an input device used to point to and select regions on the display of a Windows computer system.

However, the Key property of these classes is quite difficult to use (line 11 in the display output below). This is why it is easier to request all instances of the Win32_Keyboard and Win32_PointingDevice classes. The output obtained for the Win32_Keyboard class with Sample 1.5 ("Listing all instances of a class with their properties formatted") is as follows:

  1:    C:\>GetCollectionOfInstances.wsf Win32_Keyboard  2:    Microsoft (R) Windows Script Host Version 5.6  3:    Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  4:  5:  6:    Caption: ................................. Enhanced (101- or 102-key)  7:    ConfigManagerErrorCode: .................. 0  8:    ConfigManagerUserConfig: ................. FALSE  9:    CreationClassName: ....................... Win32_Keyboard 10:    Description: ............................. PC/AT Enhanced PS/2 Keyboard (101/102-Key) 11:    *DeviceID: ............................... ROOT\*PNP030B\1_0_22_0_32_0 12:    Layout: .................................. 00000813 13:    Name: .................................... Enhanced (101- or 102-key) 14:    NumberOfFunctionKeys: .................... 12 15:    PNPDeviceID: ............................. ROOT\*PNP030B\1_0_22_0_32_0 16:    PowerManagementSupported: ................ FALSE 17:    Status: .................................. OK 18:    SystemCreationClassName: ................. Win32_ComputerSystem 19:    SystemName: .............................. XP-DPEN6400 

The output obtained for the Win32_PointingDevice class with Sample 1.5 ("Listing all instances of a class with their properties formatted") is as follows:

  1:    C:\>GetCollectionOfInstances.wsf Win32_PointingDevice  2:    Microsoft (R) Windows Script Host Version 5.6  3:    Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  4:  5:  6:    Caption: ................................. Microsoft PS/2 Mouse  7:    ConfigManagerErrorCode: .................. 0  8:    ConfigManagerUserConfig: ................. FALSE  9:    CreationClassName: ....................... Win32_PointingDevice 10:    Description: ............................. Microsoft PS/2 Mouse 11:    *DeviceID: ............................... ROOT\*PNP0F03\1_0_21_0_31_0 12:    DeviceInterface: ......................... 4 13:    DoubleSpeedThreshold: .................... 6 14:    Handedness: .............................. 2 15:    HardwareType: ............................ Microsoft PS/2 Mouse 16:    InfFileName: ............................. msmouse.inf 17:    InfSection: .............................. PS2_Inst 18:    Manufacturer: ............................ Microsoft 19:    Name: .................................... Microsoft PS/2 Mouse 20:    NumberOfButtons: ......................... 5 21:    PNPDeviceID: ............................. ROOT\*PNP0F03\1_0_21_0_31_0 22:    PointingType: ............................ 2 23:    PowerManagementSupported: ................ FALSE 24:    QuadSpeedThreshold: ...................... 10 25:    Status: .................................. OK 26:    SystemCreationClassName: ................. Win32_ComputerSystem 27:    SystemName: .............................. XP-DPEN6400 

To show a practical application of the Win32_PointingDevice class, Sample 2.1 determines if a mouse is configured for a right hand or a left hand.

Sample 2.1: Determine if a mouse is right or left hand configured

start example

  1:<?xml version="1.0"?>  .:  8:<package>  9:  <job> ..: 13:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\TinyErrorHandler.vbs" /> 14: 15:    <script language="VBscript"> 16:    <![CDATA[ ..: 20:    Const cComputerName = "LocalHost" 21:    Const cWMINameSpace = "root/cimv2" 22:    Const cWMIClass = "Win32_PointingDevice" ..: 29:    Set objWMIServices = GetObject("WinMgmts:{impersonationLevel=impersonate}!//" & _ 30:                                   cComputerName & "/" & cWMINameSpace) ..: 33:    Set objWMIInstances = objWMIServices.InstancesOf (cWMIClass) 34:    If Err.Number Then ErrorHandler (Err) 35: 36:    For Each objWMIInstance In objWMIInstances 37:        Select Case objWMIInstance.Handedness 38:               Case 0 39:                    WScript.Echo "The handedness for the " & _ 40:                                 objWMIInstance.Description & " is unknown." 41:               Case 1 42:                    WScript.Echo "The handedness for the " & _ 43:                                 objWMIInstance.Description & " is not applicable." 44:                Case 2 45:                    WScript.Echo "The handedness for the " & _ 46:                                 objWMIInstance.Description & " is set for the right hand." 47:                Case 3 48:                    WScript.Echo "The handedness for the " & _ 49:                                 objWMIInstance.Description & " is set for the left hand." 50:         End Select 51:    Next ..: 56:    ]]> 57:    </script> 58:  </job> 59:</package> 

end example

The output is as follows:

 C:\>IsMouseRightOrLeftHanded.wsf Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2000. All rights reserved. The Microsoft PS/2 mouse is set for the right hand. 

2.3.2 Mass storage classes

The mass storage classes represent storage devices such as hard disk drives, CD-ROM drives, and tape drives. These classes are shown in Table 2.3.

Table 2.3: The Mass Storage Classes

Name

Description

Win32 AutochkSetting

Represents the settings for the autocheck operation of a disk.

Win32 CDROMDrive

Represents a CD-ROM drive on a Windows computer system.

Win32_DiskDrive

Represents a physical disk drive as seen by a computer running the Windows operating system.

Win32 FloppyDrive

Manages the capabilities of a floppy disk drive.

Win32_LogicalDisk

Represents a data source that resolves to an actual local storage device on a Windows system.

Win32_MappedLogicalDisk

Represents network storage devices that are mapped as logical disks on the computer system.

Win32 TapeDrive

Represents a tape drive on a Windows computer.

One very interesting class in this category is the Win32_LogicalDisk class. Besides the properties and the methods exposed by this class, it is important to note that this class is also associated with an interesting set of classes (see Figure 2.1). With the associations, we can see that some classes, such as Win32_QuotaSettings, are associated with Win32_LogicalDisk, which means that it is possible to retrieve the quota information when working with one instance of the Win32_LogicalDisk class. We discuss this feature later, when working with the Disk Quota provider in the next chapter.

click to expand
Figure 2.1: The Win32_LogicalDisk class associations.

Of course, besides the ability to retrieve information about the media, which we made for the keyboard and the mouse, an interesting application of the Win32_LogicalDisk class is to monitor the free space on hard disks. Here we can reuse some of the scripts developed in the first book, Understanding WMI Scripting, Chapter 6, when we learned the WMI Event scripting technique. Instead of reusing one of the generic scripts to monitor WMI events (see Sample 6.14, "A generic script for synchronous event notification" and Sample 6.17, "A generic script for asynchronous event notification" in the appendix), which displays all properties of the event with its associated instance, let's make a script that uses a customized logic and that displays a message only when the free disk space falls below 50 percent for a specific disk. This logic is shown in Sample 2.2.

Sample 2.2: Alerting script when the free disk space decreases below 50 percent on a specific disk

start example

  1:<?xml version="1.0"?>  .:  8:<package>  9:  <job> ..: 13:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\TinyErrorHandler.vbs" /> 14:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\PauseScript.vbs" /> ..: 18:    <script language="VBscript"> 19:    <![CDATA[ ..: 23:    ' ---------------------------------------------------------------------------------------- 24:    Const cComputerName = "LocalHost" 25:    Const cWMINameSpace = "root/cimv2" 26:    Const cWMIClass = "Win32_LogicalDisk" 27:    Const cWMIInstance = "'C:'" 28:    Const cPercentage = 50 ..: 36:    Set objWMISink = WScript.CreateObject ("WbemScripting.SWbemSink", "SINK_") 37: 38:    Set objWMIServices = GetObject("WinMgmts:{impersonationLevel=impersonate}!//" & _ 39:                                   cComputerName & "/" & cWMINameSpace) ..: 42:    strWQLQuery = "Select * From __InstanceModificationEvent Within 10 " & _ 43:                  "Where TargetInstance ISA 'Win32_LogicalDisk' And " & _ 44:                  "TargetInstance.DriveType=3 And " & _ 45                   "TargetInstance.Device And " & _ 46                   "TargetInstance.FreeSpace < PreviousInstance.FreeSpace" 47: 48:    objWMIServices.ExecNotificationQueryAsync objWMISink, _ 49:                                              strWQLQuery, _ 50:                                              ' _ 51:                                              wbemFlagSendStatus ..: 54:    WScript.Echo "Waiting for events..." 55: 56:    PauseScript "Click on 'Ok' to terminate the script ..." 57: 58:    WScript.Echo vbCRLF & "Cancelling event subscription ..." 59:    objWMISink.Cancel ..: 64:    WScript.Echo "Finished." 65: 66:    '-------------------------------------------------------------------------------------------- 67:    Sub SINK_OnObjectReady (objWbemObject, objWbemAsyncContext) ..: 74:        WScript.Echo FormatDateTime(Date, vbLongDate) & " at " & _ 75:                     FormatDateTime(Time, vbLongTime) & "." 76: 77:        intPercentageFree = _ 78:             objWbemObject.TargetInstance.FreeSpace / objWbemObject.TargetInstance.Size * 100 79: 80:        If cPercentage >= Clng(intPercentageFree) Then 81:           WScript.Echo "Warning, disk " & objWbemObject.TargetInstance.Name & " has " & _ 82:                        objWbemObject.TargetInstance.FreeSpace & _ 83:                        " bytes free on a total capacity of " & _ 84:                        objWbemObject.TargetInstance.Size & _ 85:                        " bytes (" & intPercentageFree & "% free)." 86:        End If 87: 88:    End Sub 89: 90:    ]]> 91:   </script> 92:  </job> 93:</package> 

end example

The trick to monitoring the disk space with the necessary conditions requires two things: the WQL query (lines 42 through 46) and the logic of the event sink routine (lines 77 and 80). For a logical disk C: defined on a hard disk, the WQL query is as follows:

 1:  Select * From _InstanceModificationEvent Within 10 2:        Where TargetInstance ISA 'Win32_LogicalDisk' And 3:        TargetInstance.DriveType=3 And 4:        TargetInstance.DeviceID='C:' And 5:        TargetInstance.FreeSpace < PreviousInstance.FreeSpace" 

The WQL query contains four conditions, based on:

  • The TargetInstance class type (line 2): This condition makes sense, because the monitoring must be executed on an instance of the Win32_LogicalDisk class.

  • The DriveType (line 3): Since the monitoring must be performed on a local hard disk, the drive type must be equal to 3 (0=Unknown, 1=No Root Directory, 2=Removable Disk, 3=Local Disk, 4=Network Drive, 5=Compact Disk, and 6=RAM Disk).

  • The DeviceID (line 4): The device ID is the letter assigned to the logical drive. In this case, we evaluate the disk space on the C: drive.

  • The decreasing FreeSpace (line 5): Since the requirement is to send an alert only when the free space decreases, the test evaluates the free space of the current instance with the value of the previous instance. If the current instance free space value is smaller, it means that the free disk space decreases.

The Win32_LogicalDisk class doesn't expose a property giving the percentage of free space, which means that the provider does not provide this value. The script must compute this value from the total disk size and current free space values (line 78). This percentage evaluation is done during the event sink execution (line 80).

 ..: ..: ..: 77:        intPercentageFree = _ 78:             objWbemObjact.TargetInstance.FreeSpace / objWbemObject.TargetInstance.Size * 100 79: 80:        If cPercentage >= Clng(intPercentageFree) Then 81:           WScript.Echo "Warning, disk " & objWbemObject.TargetInstance.Name & " has " & _ 82:                        objWbemObject.TargetInstance.FreeSpace & _ ..: ..: ..: 

If the condition matches, the script will display messages as follows:

 C:\>AlertWhenFreeSpaceLessThan50%.wsf Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2001. All rights reserved. Waiting for events... Wednesday, 15 August, 2001 at 10:42:15. Warning, disk C: has 415331128 bytes free on a total capacity of 843816448 bytes (49.2205% free). Wednesday, 15 August, 2001 at 10:42:42. Warning, disk C: has 353877210 bytes free on a total capacity of 843816448 bytes (41.9376% free). 

Another interesting feature of the Win32_LogicalDisk class is the Chkdsk method. This method launches the CHKDSK utility. Because it executes in a WMI context, it is also possible to run CHKDSK on a remote computer. Sample 2.3 shows how to proceed.

Sample 2.3: Executing CHKDSK via WMI

start example

   1:<?xml version="1.0"?>   8:<package>   9:  <job>  ..:  13:    <runtime>  14:      <unnamed name="LogicalDisk" helpstring="the logical disk letter."                          required="true" type="string" />  15:      <named name="FixErrors" helpstring="Indicates what should be done to errors found                          on the disk. If true, then errors are fixed. The default is FALSE."                          required="false" type="boolean" />  16:      <named name="VigorousIndexCheck" helpstring="If TRUE, a vigorous check of index entries                          should be performed. The default is TRUE."                          required="false" type="boolean" />  17:      <named name="SkipFolderCycle" helpstring="If TRUE, the folder cycle checking should be                          skipped or not. The default is TRUE."                          required="false" type="boolean" />  18:      <named name="ForceDismount" helpstring="If TRUE, the drive should be forced to dismount                          before checking. The default is FALSE."                          required="false" type="boolean" />  19:      <named name="RecoverBadSectors" helpstring="If TRUE, the bad sectors should be located                          and the readable information should be recovered from these sectors.                          The default is FALSE." required="false" type="boolean" />  20:      <named name="OKToRunAtBootUp" helpstring="If TRUE, the chkdsk operation should be                          performed at next boot up time, in case the operation could not be                          performed because the disk was locked at time the method was called.                          The default is FALSE." required="false" type="boolean" />  21:      <named name="Machine" helpstring="determine the WMI system to connect to.                          (default=LocalHost)" required="false" type="string"/>  22:      <named name="User" helpstring="determine the UserID to perform the remote connection.                          (default=none)" required="false" type="string"/>  23:      <named name="Password" helpstring="determine the password to perform the remote                          connection. (default=none)" required="false" type="string"/>  24:      <example>Example:  25:  26:      WMIChkdsk.wsf C: /FixErrors+ /VigorousIndexCheck+ /SkipFolderCycle+  27:      WMIChkdsk.wsf C: /ForceDismount+ /RecoverBadSectors+ /OKToRunAtBootUp+  28:      WMIChkdsk.wsf C:  29:      </example>  30:    </runtime>  31:  32:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\TinyErrorHandler.vbs" />  33:  34:    <object prog  reference="true"/>  35:  36:    <script language="VBscript">  37:    <![CDATA[  ..:  41:    Const cComputerName = "LocalHost"  42:    Const cWMINameSpace = "root/cimv2"  43:    Const cWMIClass = "Win32_LogicalDisk"  63:    ' ----------------------------------------------------------------------------------------  64:    ' Parse the command line parameters  65:    If WScript.Arguments.Unnamed.Count = 0 Then  66:       WScript.Arguments. ShowUsage()  67:       WScript.Quit  68:    Else  69:       strWMIInstance = WScript.Arguments.Unnamed.Item(0)  70:    End If  71:  72:    boolFixErrors = WScript.Arguments.Named("FixErrors")  73:    If Len(boolFixErrors) = 0 Then boolFixErrors = False  74:  75:    boolVigorousIndexCheck = WScript.Arguments.Named("VigorousIndexCheck")  76:    If Len(boolVigorousIndexCheck) = 0 Then boolVigorousIndexCheck = True  77:  78:    boolSkipFolderCycle = WScript.Arguments.Named("SkipFolderCycle")  79:    If Len(boolSkipFolderCycle) = 0 Then boolSkipFolderCycle = True  80:  81:    boolForceDismount = WScript.Arguments.Named("ForceDismount")  82:    If Len(boolForceDismount) = 0 Then boolForceDismount = False  83:  84:    boolRecoverBadSectors = WScript.Arguments.Named("RecoverBadSectors")  85:    If Len(boolRecoverBadSectors) = 0 Then boolRecoverBadSectors = False  86:  87:    boolOKToRunAtBootUp = WScript.Arguments.Named("OKToRunAtBootUp")  88:    If Len(boolOKToRunAtBootUp) = 0 Then boolOKToRunAtBootUp = False  89:  90:    strUserID = WScript.Arguments.Named("User")  91:    If Len(strUserID) = 0 Then strUserID = ""  92:  93:    strPassword = WScript.Arguments.Named("Password")  94:    If Len(strPassword) = 0 Then strPassword = ""  95:  96:    strComputerName = WScript.Arguments.Named("Machine")  97:    If Len(strComputerName) = 0 Then strComputerName = cComputerName  98:  99:    objWMILocator.Security_.AuthenticationLevel = wbemAuthenticationLevelDefault 100:    objWMILocator.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate 101: 102:    Set objWMIServices = objWMILocator.ConnectServer(strComputerName, cWMINameSpace, _ 103:                                                     strUserID, strPassword) 106:    Set objWMIInstance = objWMIServices.Get (cWMIClass & "='" & strWMIInstance & "'") 109:    If boolFixErrors Then 110:       WScript.Echo "Errors will be fixed." 111:    End If 112: 113:    If boolVigorousIndexCheck Then 114:       WScript.Echo "Vigorous check of index entries will be performed." 115:    End If 116: 117:    If boolSkipFolderCycle Then 118:       WScript.Echo "The folder cycle checking will be skipped." 119:    End If 120: 121:    If boolForceDismount Then 122:       WScript.Echo "The drive will be forced to dismount before checking." 123:    End If 124: 125:    If boolRecoverBadSectors Then 126:       WScript.Echo "The bad sectors will be located ... will be recovered from these sectors." 127:    End If 128: 129:    If boolOKToRunAtBootUp Then 130:       WScript.Echo "The chkdsk operation should be performed at next boot up time." 131:    End If 132: 133:    WScript.Echo 134:    WScript.Echo "Volume " & Ucase (objWMIInstance.DeviceID) & _ 135:                 " has " & objWMIInstance.FreeSpace & _ 136:                 " bytes free on a total of " & _ 137:                   objWMIInstance.Size & " bytes." 138:    WScript.Echo "The type of the file system is " & _ 139:                  objWMIInstance.FileSystem & "." 140:    WScript.Echo "Volume is " & objWMIInstance.VolumeName & "." 141:    WScript.Echo "Volume Serial Number is " & _ 142:                 objWMIinstance.VolumeSerialNumber & "." 143: 144:    WScript.Echo "WMI chkdsk started ..." 145:    intRC = objWMIInstance.Chkdsk (boolFixErrors, _ 146:                                   boolVigorousIndexCheck, _ 147:                                   boolSkipFolderCycle, _ 148:                                   boolForceDismount, _ 149:                                   boolRecoverBadSectors, _ 150:                                   boolOKToRunAtBootUp) 151:    If Err.Number Then ErrorHandler (Err) 152: 153:    Select Case intRC 154:           Case 0 155:                WScript.Echo "WMI chkdsk completed successfully." 156:           Case 1 157:                WScript.Echo "Locked and chkdsk scheduled on reboot." 158:           Case 2 159:                WScript.Echo "WMI chkdsk failure - Unknown file system." 160:           Case 3 161:                WScript.Echo "WMI chkdsk failure - Unknown error." 162:    End Select ...: 167:    ]]> 168:    </script> 169:  </job> 170:</package> 

end example

The script parses the Win32_LogicalDisk Chkdsk method parameters (lines 13 through 30 and lines 72 through 88) from the command line. After executing the WMI connection (lines 102 and 103), Sample 2.3 instantiates the desired logical disk (line 106). Before executing the CHKDSK utility, the script shows the actions to be executed (lines 109 through 131) with some information about the logical disk itself (lines 133 through 142). Next, the Chkdsk method is invoked (lines 145 through 150) with the given parameters. Once executed, the return code of the operation is interpreted (lines 151 through 162). The output produced by Sample 2.3 is as follows:

 C:\>WMIChkdsk.wsf E: /Machine:Remote.LissWare.Net /User:Administrator /Password:password Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2001. All rights reserved. Vigorous check of index entries will be performed. The folder cycle checking will be skipped. Volume E: has 6418804736 bytes free on a total of 7229595648 bytes. The type of the file system is NTFS. Volume is Win2003. Volume Serial Number is 84FC2438. WMI chkdsk started ... WMI chkdsk completed successfully. 

2.3.3 Motherboard, controller, and port classes

The motherboard, controller, and port classes represent devices such as memory, hardware controllers (i.e., IDE, PCMCIA, floppy), BIOS, parallel and serial ports, and so on. The classes related to these hardware devices and supported by the Win32 providers are shown in Table 2.4.

Table 2.4: Motherboard, Controller, and Port Classes

Name

Description

Win32 1394Controller

Represents the capabilities and management of a 1394 controller.

Win32_1394ControllerDevice

Relates the high-speed serial bus (IEEE 1394 Firewire) Controller and the CIM_LogicalDevice instance connected to it.

Win32_AllocatedResource

Relates a logical device to a system resource.

Win32_AssociatedProcessorMemory

Relates a processor and its cache memory.

Win32_BaseBoard

Represents a baseboard (also known as a motherboard or

systemboard).

Win32_BIOS

Represents the attributes of the computer system's basic input/output services (BIOS) that are installed on the computer.

Win32 Bus

Represents a physical bus as seen by a Windows operating system.

Win32_CacheMemory

Represents cache memory (internal and external) on a computer system.

Win32_ControllerHasHub

Represents the hubs downstream from the Universal Serial Bus (USB) controller.

Win32_DeviceBus

Relates a system bus and a logical device using the bus.

Win32_DeviceMemoryAddress

Represents a device memory address on a Windows system.

Win32_DeviceSettings

Relates a logical device and a setting that can be applied to it.

Win32_DMAChannel

Represents a direct memory access (DMA) channel on a Windows computer system.

Win32_FloppyController

Represents the capabilities and management capacity of a floppy disk drive controller.

Win32_IDEController

Represents the capabilities of an Integrated Drive Electronics (IDE) controller device.

Win32_IDEControllerDevice

Association class that relates an IDE controller and the logical device.

Win32_InfraredDevice

Represents the capabilities and management of an infrared device.

Win32_IRQResource

Represents an interrupt request line (IRQ) number on a Windows computer system.

Win32_MemoryArray

Represents the properties of the computer system memory array and mapped addresses.

Win32_MemoryArrayLocation

Relates a logical memory array and the physical memory array upon which it exists.

Win32_MemoryDevice

Represents the properties of a computer system's memory device along with its associated mapped addresses.

Win32_MemoryDeviceArray

Relates a memory device and the memory array in which it resides.

Win32_MemoryDeviceLocation

Association dass that relates a memory device and the physical memory on which it exists.

Win32_MotherboardDevice

Represents a device that contains the central components of the

Windows computer system.

Win32_OnBoardDevice

Represents common adapter devices built into the motherboard (system board).

Win32_ParallelPort

Represents the properties of a parallel port on a Windows computer system.

Win32_PCMCIAController

Manages the capabilities of a Personal Computer Memory Card Interface Adapter (PCMCIA) controller device.

Win32_PhysicalMemory

Represents a physical memory device located on a computer as available to the operating system.

Win32_PhysicalMemoryArray

Represents details about the computer system's physical memory.

Win32_PhysicalMemoryLocation

Relates an array of physical memory and its physical memory.

Win32_PNPAllocatedResource

Represents an association between logical devices and system resources.

Win32_PNPDevice

Relates a device (known to Configuration Manager as a PNPEntity), and the function it performs.

Win32_PNPEntity

Represents the properties of a Plug and Play device.

Win32_PortConnector

Represents physical connection ports, such as DB-25 pin male, Centronics, and PS/2.

Win32_PortResource

Represents an I/O port on a Windows computer system.

Win32_Processor

Represents a device capable of interpreting a sequence of machine instructions on a Windows computer system.

Win32_SCSIController

Represents a SCSI controller on a Windows system.

Win32_SCSIControllerDevice

Relates a Small Computer System Interface (SCSI) controller and the logical device (disk drive) connected to it

Win32_SerialPort

Represents a serial port on a Windows system.

Win32_SerialPortConfiguration

Represents the settings for data transmission on a Windows serial port.

Win32_SerialPortSetting

Relates a serial port and its configuration settings.

Win32_SMBIOSMemory

Represents the capabilities and management of memory-related logical devices.

Win32_SoundDevice

Represents the properties of a sound device on a Windows computer system.

Win32_SystemBIOS

Relates a computer system (including data such as startup properties, time zones, boot configurations, or administrative passwords) and a system BIOS (services, languages, system management properties).

Win32_SystemDriverPNPEntity

Relates a Plug and Play device on the Windows computer system and the driver that supports the Plug and Play device.

Win32_SystemEnclosure

Represents the properties associated with a physical system enclosure.

Win32_SystemMemoryResource

Represents a system memory resource on a Windows system.

Win32_SystemSlot

Represents physical connection points including ports, motherboard slots and peripherals, and proprietary connections points.

Win32_USBController

Manages the capabilities of a Universal Serial Bus (USB) controller.

Win32_USBControllerDevice

Relates a USB controller and the CIM_LogicalDevice instances connected to it.

Win32_USBHub

Represents the management characteristics of a USB hub.

By using some of these classes, it is possible to create a script to collect information about the hardware devices and the resources they use (IRQ, DMA). For the script sample, we use some classes that represent devices that are available in all computers. This makes the script usable with all computer types. For instance, some hardware components that are common to any computer are:

  • The processor represented by the Win32_Processor class

  • The memory represented by the Win32_PhysicalMemory class

  • The hardware resources, such as the IRQ and the DMA, respectively, represented by Win32_IRQResource and Win32_DMAChannel classes.

Many other classes from this category can be used to gather information about the hardware. All of them use the same logic. Samples 2.4 through 2.7 contain the script code to display the processor, the memory, and the hardware resources of a computer. This script can be easily extended to suit any other needs (i.e., displaying information about the PCMCIA controller with the Win32_PCMCIAController class).

Sample 2.4: Retrieving hardware resource information (Part I)

start example

  1:<?xml version="1.0"?>  .:  8:<package>  9:  <job> ..: 13:    <runtime> ..: 17:    </runtime> 18: 19:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeDeviceAvailabilityFunction.vbs" /> 20:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodePwrManCapabilitiesFunction.vbs" /> 21:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\TinyErrorHandler.vbs" /> 22: 23:    <object prog  reference="true"/> 24: 25:    <script language="VBscript"> 26:    <![CDATA[ ..: 44:    ' ---------------------------------------------------------------------------------- 45     ' Parse the command line parameters ..: 46:    strUserID = WScript.Arguments.Named("User") ..: 58:    Set objWMIServices = objWMILocator.ConnectServer(strComputerName, cWMINameSpace, _ 59:                                                     strUserID, strPassword) ..: 62:    ' ------------------------------------------------------------------------------------- 63:    WScript.Echo "--- Processors information " & String (60, "-") 64:    Set objWMIInstances = objWMIServices.InstancesOf ("Win32_Processor") 65:    If Err.Number Then ErrorHandler (Err) 66: 67:    If objWMIInstances.Count Then 68:       For Each objWMIInstance In objWMIInstances 69:           WScript.Echo objWMIInstance.DeviceID & " is an " & _ 70:                        objWMIInstance.Name & " (" & _ 71:                        objWMIInstance.Caption & ")." 72:           WScript.Echo "It is an " & objWMIInstance.AddressWidth & " bits CPU running at " & _ 73:                        "an internal clock speed of " & _ 74:                        objWMIInstance.CurrentClockSpeed & " Mhz." 75:           WScript.Echo "The external clock speed is " & objWMIInstance.ExtClock & " Mhz." 76:           WScript.Echo objWMIInstance.DeviceID & " is " & _ 77:                        DeviceAvallability (objWMIInstance.Availability) & " and state is " & _ 78:                        objWMIInstance.Status & "." 79:           WScript.Echo "The Second Level (L2) cache size is " & _ 80:                        objWMIInstance.L2CacheSize & " KB and is running at a speed of " & _ 81:                        objWMIInstance.L2CacheSpeed & " Mhz." 82:           WScript.Echo "This processor is manufactured by " & objWMIInstance.Manufacturer & _ 83:                        " and uses a " & objWMIInstance.SocketDesignation & " socket." 84:           WScript.Echo "The current revision level is " & objWMIInstance.Revision & _ 85:                        " stepping " & objWMIInstance.Stepping & ".' 86:           WScript.Echo "The processor ID is " & objWMIInstance.ProcessorId & "." 87:           If objWMIInstance.PowerManagementSupported Then 88:              WScript.Echo "Power management capabilities are " & _ 89:                PwrManCapabilities(objWMIInstance.PowerManagementCapabilities) & ".' 90:           Else 91:              WScript.Echo "Power management capabilities are not supported." 92:           End If 93:       Next 94:    Else 95:       WScript.Echo "No information available." 96:    End If 97:    WScript.Echo 98: ..: ..: ..: 

end example

The script does not require any specific parameter. This is the reason why it only contains the traditional parameters to connect to a remote machine with some optional credentials (skipped lines 13 through 17). Next, the script includes two helper functions (lines 19 and 20):

  • DecodeDeviceAvailabilityFunction.vbs

  • DecodePwrManCapabilitiesFunction.vbs

These two functions convert values contained in the PowerManagementCapabilities and the Availability properties into a readable text instead of showing their values. These two properties are not related to one specific class. Actually, many classes dealing with the hardware devices expose these properties. By using these functions, we simplify the hardware data reading and interpretation.

Once the command-line parameters are parsed and the WMI connection is established (lines 46 through 60), the script retrieves information about the processor (lines 63 through 97). The script requests the collection of processors available (line 64) and displays the most relevant properties (lines 69 through 92). The script outputs these properties in a readable text, as follows:

  1:    C:\>GetHardwareResourceInfo.wsf  2:    Microsoft (R) Windows Script Host Version 5.6  3:    Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  4:  5:    --- Processors information ------------------------------------------------------------  6:    CPU0 is an Intel(R) Pentium(R) 4 CPU 1.50GHz (x86 Family 15 Model 1 Stepping 2).  7:    It is an 32 bits CPU running at an internal clock speed of 1495 Mhz.  8:    The external clock speed is 400 Mhz.  9:    CPU0 is Running/Full Power and its state is OK. 10:    The Second Level (L2) cache size is 256 KB and is running at a speed of 1495 Mhz. 11:    This processor is manufactured by GenuineIntel and uses a XU1 socket. 12:    The current revision level is 258 stepping 2. 13:    The processor ID is 3FEBFBFF00000F12. 14:    Power management capabilities are not supported. 15: ..: ..: ..: 

Once the processor information is displayed, the script gathers information about the memory (see Sample 2.5). It follows the same logic. Only the way the information is displayed is different. The script retrieves the memory chips available and takes their size into account to display the values in KB or in MB (line 106).

Sample 2.5: Retrieving hardware resource information (Part II)

start example

  ..:  ..:  ..:  99:    ' ---------------------------------------------------------------------------------------- 100:    WScript.Echo "--- Memory information " & String (60, "-") 101:    Set objWMIInstances = objWMIServices.InstancesOf ("Win32_PhysicalMemory") 102:    If Err.Number Then ErrorHandler (Err) 103: 104:    If objWMIInstances.Count Then 105:       For Each objWMIInstance In objWMIInstances 106:           If (objWMIInstance.Capacity - 1024^2) < 0 Then 107:              WScript.Echo objWMIInstance.BankLabel & " is " & _ 108:                           objWMIInstance.Capacity / (1024) & " KB chip size (" & _ 109:                           objWMIInstance.DeviceLocator & ")." 110:           Else 111:              WScript.Echo objWMIInstance.BankLabel & " is " & _ 112:                           objWMIInstance.Capacity / (1024^2) & " MB chip size (" & _ 113:                           objWMIInstance.DeviceLocator & ")." 114:           End If 115:       Next 116:    Else 117:       WScript.Echo "No information available." 118:    End If 119:    WScript.Echo 120: ...: ...: ...: 

The output obtained is as follows:

 ..: ..: 15: 16:    --- Memory information ------------------------------------------------- 17:    Bank  0: J10 is 512 MB chip size (XMM1). 18:    Bank  1: J11 is 512 MB chip size (XMM2). 19:    ROM: XU15 is 512 KB chip size (XU15). 20: ..: ..: ..: 

end example

Next, the script retrieves information about the hardware resources used. Sample 2.6 retrieves information about the DMA resource usage, while Sample 2.7 retrieves information about the IRQ resource usage.

Sample 2.6: Retrieving hardware resource information (Part III)

start example

 ...: ...: ...: 120: 121:    ' ------------------------------------------------------------------------------------- 122:    WScript.Echo "--- DMA resource usage " & String (60, "-") 123:    Set objWMIInstances = objWMIServices.InstancesOf ("Win32_DMAChannel") 124:    If Err.Number Then ErrorHandler (Err) 125: 126:    If objWMIInstances.Count Then 127:       For Each objWMIInstance In objWMIInstances 128:           Set objAssoc1Instances = objWMlServices.ExecQuery _ 129:                                      ("Associators of (Win32_DMAChannel='" & _ 130:                                      objWMIInstance.DMAChannel & _ 131:                                      "'} Where AssocClass=Win32_PNPAllocatedResource") 132: 133:           If objAssoc1Instances.Count Then 134:              WScript.Echo objWMIInstance.Caption 135:              For Each objAssoc1Instance In objAssoclInstances 136:                  If Len (objAssoc1Instance.Service) Then 137:                     WScript.Echo "  " & Trim (objAssoc1Instance.Name) & "." 138:                     WScript.Echo "  Service name is '" & UCase (objAssoc1Instance.Service) & _ 139:                                  "' and status is " & objAssoc1Instance.Status & "." 140: 141:                     Set objAssoc2Instances = objWMlServices.ExecQuery _ 142:                                      ("Associators of {Win32_PnPEntity='" & _ 143:                                      objAssoc1Instance.DeviceID & _ 144:                                      "'} Where ResultClass=Win32_PortResource " & _ 145:                                      "AssocClass=Win32_PNPAllocatedResource") 146: 147:                     For Each objAssoc2Instance In objAssoc2Instances 148:                         WScript.Echo "     Address range is " & objAssoc2Instance.Name 149:                     Next 150: 151:                  Else 152:                     WScript.Echo "  " & objAssoc1Instance.Name & "." 153:                  End If 154:              Next 155:           End If 156:       Next 157:    Else 158:       WScript.Echo "No information available." 159:    End If 160:    WScript.Echo 161: ...: ...: ...: 

end example

Sample 2.7: Retrieving hardware resource information (Part IV)

start example

 ...: ...: ...: 161: 162:    '----------------------------------------------------------------------------------- 163:    WScript.Echo "--- IRQ resource usage " & String (60, "-") 164:    Set objWMIInstances = objWMIServices.InstancesOf ("Win32_IRQResource") 165:    If Err.Number Then ErrorHandler (Err) 166: 167:    If objWMIInstances.Count Then 168:       For Each objWMIInstance In objWMIInstances 169:           Set objAssoc1Instances = objWMIServices.ExecQuery _ 170:                                      ("Associators of (Win32_IRQResource='" & _ 171:                                      objWMIInstance.IRQNumber & _ 172:                                      "'} Where AssocClass=Win32_PNPAllocatedResource") 173:           If objAssoc1Instances.Count Then 174:              WScript.Echo objWMIInstance.Caption 175:              For Each objAssoc1Instance In objAssoc1Instances 176:                  If Len (objAssoclInstance.Service) Then 177:                     WScript.Echo "  " & Trim (objAssoc1Instance.Name) & "." 178:                     WScript.Echo "  Service name is '" & UCase (objAssoc1Instance.Service) & _ 179:                                  "' and status is " & objAssoc1Instance.Status & "." 180: 181:                     Set objAssoc2Instances = objWMIServices.ExecQuery _ 182:                                      ("Associators of {Win32_PnPEntity='" & _ 183:                                      objAssocIInstance.DeviceID & _ 184:                                      "') Where ResultClass=Win32_PortResource " & _ 185:                                      "AssocClass=Win32_PNPAllocatedResource") 186: 187:                     For Each objAssoc2Instance In objAssoc2Instances 188:                         WScript.Echo "     Address range is " & objAssoc2Instance.Name 189:                     Next 190: 191:                  Else 192:                     WScript.Echo objAssoc1Instance.Name & "." 193:                  End If 194:              Next 195:           End If 196:       Next 197:    Else 198:       WScript.Echo "No information available." 199:    End If ...: 204:    ]]> 205:    </script> 206:  </job> 207:</package> 

end example

The script retrieves the number of DMA channels available by requesting the instances of the Win32_DMAChannel class (line 123). Next, it enumerates the DMA channels (lines 127 through 156) and, for each channel, the script requests the collection of instances associated with the examined DMA channel (lines 128 through 131). This collection of instances is nothing more than the devices using the DMA channel number. If the collection of associated instances contains at least one item (line 133), which is one device that uses the examined DMA channel, the script displays the DMA channel instance name (line 134) and enumerates each associated instance in the collection (lines 135 through 154). For each associated instance, the script displays its name and status (lines 138 and 139).

As a result, the device name and its state are displayed. Because the device could use some I/O port addresses, the script also retrieves the I/O port addresses used by requesting the list of I/O ports associated with the instance (lines 141 through 145). In such a case, the script retrieves a list of associated instances (the list of I/O ports used) from each associated instance (the device examined). Lines 147 through 149 display the I/O port collection.

To summarize, the script retrieves a collection of DMA channels used, and for each DMA channel examined the script retrieves the list of devices using that DMA channel. Next, for each device using the considered DMA channel the script retrieves the list of I/O ports used by that device. In WMI words, we have a collection of instances where each instance is associated with a collection of instances, which in turn are associated with a second collection of instances. As a result, the script generates the following output:

 ..: ..: ..: 20: 21:    --- DMA resource usage -------------------------------------------------------------- 22:    Channel 4 23:      Direct memory access controller. 24:    Channel 2 25:      Standard floppy disk controller. 26:         Service name is 'FDC' and status is OK. 27:         Address range is 0x000003F0-0x000003F5 28:         Address range is 0x000003F7-0x000003F7 ..: ..: ..: 

Sample 2.7 uses the exact same logic as Sample 2.6. The only variation concerns the instance type retrieved. Sample 2.6 retrieves Win32_DMAChannel instances, while Sample 2.7 retrieves Win32_IRQResource instances (line 164).

As a result, the script displays the following information:

 ..: ..: ..: 29: 30:    --- IRQ resource usage --------------------------------------------------------------- 31:    IRQ 9 32:      Microsoft ACPI-Compliant System. 33:         Service name is 'ACPI' and status is OK. 34:    IRQ 18 35:      NVIDIA GeForce2 MX/MX 400. 36:         Service name is 'NV' and status is OR. 37:         Address range is 0x000003B0-0x000003BB 38:         Address range is 0x000003C0-0x000003DF 39:    IRQ 20 40:      Intel(R) PRO/100 VM Network Connection. 41:         Service name is 'E100B' and status is OR. 42:         Address range is 0x00001400-0x0000143F 43:    IRQ 21 44:      Adaptec AHA-2940AU PCI SCSI Controller. 45:         Service name is 'AIC78XX' and status is OR. 46:         Address range is 0x00001000-0x000010FF 47:    IRQ 22 48:      Creative SB Live! Basic (WDM). 49:         Service name is 'EMU10R' and status is OK. 50:         Address range is 0x00001440-0x0000145F 51:    IRQ 13 52:      Numeric data processor. 53:    IRQ 0 54:      System timer. 55:    IRQ 8 56:      System CMOS/real time clock. 57:    IRQ 12 58:      PS/2 Compatible Mouse. 59:         Service name is 'I8042PRT' and status is OK. 60:    IRQ 1 61:      Standard 101/102-Key or Microsoft Natural PS/2 Reyboard. 62:         Service name is 'I8042PRT' and status is OK. 63:         Address range is 0x00000060-0x00000060 64:         Address range is 0x00000064-0x00000064 65:    IRQ 4 66:      Communications Port (COM1). 67:         Service name is 'SERIAL' and status is OK. 68:         Address range is Ox000003F8-Ox000003FF 69:    IRQ 3 70:      Communications Port (COM2). 71:         Service name is 'SERIAL' and status is OR. 72:         Address range is 0x000002F8-0x000002FF 73:    IRQ 6 74:      Standard floppy disk controller. 75:         Service name is 'FDC' and status is OR. 76:         Address range is 0x000003F0-0x000003F5 77:         Address range is 0x000003F7-0x000003F7 78:    IRQ 14 79:      Primary IDE Channel. 80:         Service name is 'ATAPI' and status is OK. 81:         Address range is 0x000001F0-0x000001F7 82:         Address range is 0x000003F6-0x000003F6 83:    IRQ 15 84:      Secondary IDE Channel. 85:         Service name is 'ATAPI' and status is OK. 86:         Address range is 0x00000170-0x00000177 87:         Address range is 0x00000376-0x00000376 88:    IRQ 19 89:      Intel (r) 82801BA/BAM USB Universal Host Controller - 2442. 90:         Service name is 'USBUHCI' and status is OK. 91:         Address range is 0x00002440-0x0000245F 

2.3.4 Networking device classes

Even though a network device is listed in the previous sample output ("Intel[R] PRO/100 VM Network," lines 39 through 42) with the motherboard, controller, and the port classes, the sample does not show the network configuration of a network adapter. The classes used in Samples 2.4 through 2.7 do not allow the retrieval of such information. For this, WMI implements some other interesting classes to retrieve and set the network adapter configuration. These classes are listed in Table 2.5.

Table 2.5: The Networking Device Classes

Name

Description

Win32_NetworkAdapter

Represents a network adapter on a Windows system.

Win32_NetworkAdapterConfiguration

Represents the attributes and behaviors of a network adapter. The class is not guaranteed to be supported after the ratification of the Distributed Management Task Force (DMTF) CIM network specification.

Win32_NetworkAdapterSetting

Relates a network adapter and its configuration settings.

Besides the hardware information related to an adapter, with the help of these classes it is possible to gather information about the adapter protocol configuration (see Samples 2.8 through 2.11). Although the Win32_NetworkAdapterConfiguration class can retrieve IP and IPX network configurations, the script focuses on the IP configuration only (to retrieve the IPX configuration, the code sample can easily be extended by displaying some additional class properties).

As usual, Sample 2.8 starts with the command-line parameter definition (lines 13 through 19), continues with the command-line parsing (lines 56 through 75), and performs the WMI connection (lines 77 through 80).

Sample 2.8: Retrieving network device information (Part I)

start example

  1:<?xml version="1.0"?>  .:  8:<package>  9:  <job> ..: 13:    <runtime> 14:      <unnamed name="AdapterName" helpstring="The name of the network adapter." required="true"                 type="string" /> 15:      <named name="List" helpstring="Only list the adapter names." required="false"                 type="boolean" /> 16:      <named name="Machine" helpstring="determine the WMI system to connect to.                 (default=LocalHost)" required="false" type="string"/> 17:      <named name="User" helpstring="determine the UserID to perform the remote connection.                 (default=none)" required="false" type="string"/> 18:      <named name="Password" helpstring="determine the password to perform the remote                 connection. (default=none)" required="false" type="string"/> 19:    </runtime> 20: 21:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeDeviceAvailabilityFunction.vbs" /> 22:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeNetworkConnectionStatusFunction.vbs" /> 23: 24:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DisplayFormattedPropertyFunction.vbs" /> 25:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\TinyErrorHandler.vbs" /> 26: 27:    <object prog  reference="true"/> 28:    <object prog  /> 29: 30:    <script language="VBscript"> 31:    <![CDATA[ ..: 35:    Const cComputerName = "LocalHost" 36:    Const cWMINameSpace = "root/cimv2" 54:    '--------------------------------------------------------------------------------------- 55:    ' Parse the command line parameters 56:    boolAdapterList = WScript.Arguments.Named("List") 57:    If Len(boolAdapterList) = 0 Then boolAdapterList = False 58: 59:    If WScript.Arguments.Unnamed.Count = 0 And boolAdapterList = False Then 60:       WScript.Arguments.ShowUsage() 61:       WScript.Quit 62:    Else 63:       If WScript.Arguments.Unnamed.Count Then 64:         strAdapterName = WScript.Arguments.Unnamed.Item(0) 65:       End If 66:    End If 67: 68:    strUserID = WScript.Arguments.Named("User") 69:    If Len(strUserID) = 0 Then strUserID = "" 70: 71:    strPassword = WScript.Arguments.Named("Password") 72:    If Len(strPassword) = 0 Then strPassword = "" 73: 74:    strComputerName = WScript.Arguments.Named("Machine") 75:    If Len(strComputerName) = 0 Then strComputerName = cComputerName 76: 77:    objWMILocator.Security_.AuthenticationLevel = wbemAuthenticationLevelDefault 78:    objWMILocator.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate 79:    Set objWMIServices = objWMILocator.ConnectServer(strComputerName, cWMINameSpace, _ 80:                                                     strUserID, strPassword) ..: 82: ..: ..: ..: 

end example

Notice that the script has a Boolean parameter called /List (lines 15, 56, and 57). This parameter requests the list of adapters available in the system. To extract the network information from one specific network adapter, it is necessary to determine which Win32_NetworkAdapter Key property to use. Because the Key is an index representing the adapter number (called the DeviceID), it is easier to use the name of the network adapter. To do so, the script lists the network adapter names, as follows:

  1:    C:\>GetNetworkConfiguration.wsf /list+  2:    Microsoft (R) Windows Script Host Version 5.6  3:    Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  4:  5:    Compaq NC3121 Fast Ethernet NIC  6:    RAS Async Adapter  7:    WAN Miniport (L2TP)  8:    WAN Miniport (PPTP)  9:    WAN Miniport (PPPOE) 10:    Direct Parallel 11:    WAN Miniport (IP) 12:    WAN Miniport (Network Monitor) 13:    Microsoft Loopback Adapter 

Because the Win32_NetworkAdapter class does not define the adapter name property as a Key property for the class, the script does not instantiate the adapter directly. Instead, the script creates a collection that lists all available adapters. The collection of adapters is retrieved in Sample 2.9 at line 83, while the existing adapter enumeration starts at line 85. If the /List+ switch is specified, the script uses the same collection to list all adapter names available (lines 83 and 87). If the /List+ switch is not specified, the script searches for a match between the name given on the command line and the existing adapter names (line 89). It was possible to use a WQL query to find the adapter name (with the ExecQuery method of the SWBemServices object), but because we usually have a few number of adapters in a computer system, the enumeration technique is acceptable. Moreover, the same loop (lines 85 through 314) is used to list adapters (line 87) or to select the adapter to work with (line 89).

Sample 2.9: Retrieving network device information (Part II)

start example

  ..:  ..:  ..:  82:  83:    Set objWMIAdapterInstances = objWMIServices.InstancesOf ("Win32_NetworkAdapter")  84:  85:    For Each objWMIAdapterInstance in objWMIAdapterInstances  86:        If boolAdapterList Then  87:           WScript.Echo Mid (objWMIAdapterInstance.Caption, 12)  88:        Else  89:           If Ucase(Mid (objWMIAdapterInstance.Caption, 12)) = Ucase(strAdapterName) Then  90:        DisplayFormattedProperty objWMIAdapterInstance, _  91:                                 "Adapter name", _  92:                                 "Name", _  93:                                 Null  94:        DisplayFormattedProperty objWMIAdapterInstance, _  95:               "Device availability", _  96:               DeviceAvailability (objWMIAdapterInstance.Availability), _  97:                                 Null  98:  99:        If objWMIAdapterInstance.NetConnectionStatus = 0 Then 100:           DisplayFormattedProperty objWMIAdapterInstance, _ 101:                                    "Adapter state", _ 102:                                    "DISABLED", _ 103:                                    Null 104:        Else 105:           DisplayFormattedProperty objWMIAdapterInstance, _ 106:                                    "Adapter type", _ 107:                                    "AdapterType", _ 108:                                    Null 109:           DisplayFormattedProperty objWMIAdapterInstance, _ 110:                  "Adapter state", _ 111:                  NetworkConnectionStatus (objWMIAdapterInstance.NetConnectionStatus), _ 112:                                    Null 113:           DisplayFormattedProperty objWMIAdapterInstance, _ 114:                                    "MAC address is ", _ 115:                                    "MACAddress", _ 116:                                    Null 117:        End If 118: 119:        DisplayFormattedProperty objWMIAdapterInstance, _ 120:                                 "Adapter service name", _ 121:                                 "ServiceName", _ 122:                                 Null 123:        DisplayFormattedProperty objWMIAdapterInstance, _ 124                                  "Last reset", _ 125:                                 "TimeOfLastReset", _ 126:                                 Null 127: ...: ...: ...: 

end example

Once a match is found, the script displays all adapter properties (lines 89 through 313). For instance, properties such as the adapter name (lines 90 through 93), state (lines 99 through 103), type (lines 105 through 108), and MACAddress are listed (lines 113 through 116).

You will notice at line 99 the test on the adapter NetConnectionStatus property. If the adapter is enabled, the adapter type, the network connection status, and the MAC address properties are displayed (lines 105 through 116). If the NetConnectionStatus property has a value of 0 (line 99), this means that the adapter is disabled (lines 100 through 103). Table 2.6 summarizes the connection status values resolved by the NetworkConnectionStatus() function included at line 22 and invoked at line 111.

Table 2.6: The Connection Status Values

Name

Values

Disconnected

0

Connecting

1

Connected

2

Disconnecting

3

Hardware Not Present

4

Hardware Disabled

5

Hardware Malfunction

6

Media Disconnected

7

Authenticating

8

Authentication Succeeded

9

Authentication Failed

10

Next, the script retrieves the hardware resource information used by the adapter: IRQ, DMA, I/O Port, and memory address (see Sample 2.10). The script bases its research on the associations defined in the CIM repository. For instance, Figure 2.2 shows the associated instances available for one network adapter. This should ease the understanding of the relationships that exist between the adapter and the hardware resources.

Sample 2.10: Retrieving network device information (Part III)

start example

 ...: ...: ...: 128:         Set objWMIAdapterResourceInstances = objWMIServices.ExecQuery _ 129:                                  ("Associators of {Win32_NetworkAdapter='" & _ 130:                                  objWMIAdapterInstance.Index & _ 131:                                  "'} Where AssocClass=Win32_AllocatedResource") 132: 133:         If objWMIAdapterResourceInstances.Count Then 134:            WScript.Echo 135:            For Each objWMIAdapterResourceInstance In objWMIAdapterResourceInstances 136:                Select Case objWMIAdapterResourceInstance.Path_.Class 137:                       Case "Win32_IRQResource" 138:                            DisplayFormattedProperty objWMIAdapterResourceInstance, _ 139:                                                     "IRQ resource", _ 140:                                                     "IRQNumber", _ 141:                                                     Null 142:                       Case "Win32_DMAChannel" 143:                            DisplayFormattedProperty objWMIAdapterResourceInstance, _ 144:                                                     "DMA channel", _ 145:                                                     "DMAChannel", _ 146:                                                     Null 147:                       Case "Win32_PortResource" 148:                            DisplayFormattedProperty objWMIAdapterResourceInstance, _ 149:                                                     "I/O Port", _ 150:                                                     "Caption", _ 151:                                                     Null 152:                       Case "Win32_DeviceMemoryAddress" 153:                            DisplayFormattedProperty objWMIAdapterResourceInstance, _ 154:                                                     "Memory address", _ 155:                                                     "Caption", _ 156:                                                     Null 157:                End Select 158:            Next 159:         End If 

end example

click to expand
Figure 2.2: Associated instances of one network adapter.

The script uses an association class called Win32_AllocatedResource to retrieve the instances representing the hardware resources. As we have seen before, the hardware resources are represented by instances of the Win32_ IRQResource, Win32_DMAChannel, Win32_PortResource, and Win32_ DeviceMemoryAddress classes (lines 136 through 157). Each of these classes is classified in the motherboard, controller, and port classes discussed in the previous section.

To retrieve instances of the Win32_AllocatedResource class that correspond to the adapter (lines 128 through 131), the script uses the Key property (called Index) of the Win32_NetworkAdapter class with the index number of the adapter instance (line 130) previously retrieved in the script with the enumeration at line 85 (see Sample 2.9).

Once hardware resources are examined, the script starts to look at the IP protocol settings (see Sample 2.11). For this, it uses the Win32_NetworkAdapterConfiguration class. This class exposes a large number of properties related to the DHCP settings (lines 188 through 204), IP address settings (lines 208 through 223), DNS settings (lines 226 through 249), WINS settings (lines 252 through 285), and IP Security/Filtering settings (lines 288 through 309).

Sample 2.11: Retrieving network device information (Part IV)

start example

 ...: ...: ...: 180:         Set objWMIAdapterInstance = objWMIServices.Get _ 181:                                         ("Win32_NetworkAdapterConfiguration=" & _ 182:                                         objWMIAdapterInstance.Index) 183: 184:         If objWMIAdapterInstance.IPEnabled Then 185:            WScript.Echo 186: 187:            ' DHCP ---------------------------------------------------------------------------------- 188:            DisplayFormattedProperty objWMIAdapterInstance, _ 189:                                     "DHCP enabled", 190:                                     "DHCPEnabled", _ 191:                                     Null 192:            If objWMIAdapterInstance.DHCPEnabled Then 193:               DisplayFormattedProperty objWMIAdapterInstance, _ 194:                                        "DHCP expires", _ 195:                                        "DHCPLeaseExpires", _ 196:                                        Null ...: 205:            End If 206: 207:            ' IP Addresses -------------------------------------------------------------- 208:            DisplayFormattedProperty objWMIAdapterInstance, _ 209:                                     "IP address(es)", _ 210:                                     "IPAddress", _ 211:                                     "IPSubnet" ...: 216:            DisplayFormattedProperty objWMIAdapterInstance, _ 217:                                     "Default Gateway(s) and metric", _ 218:                                     "DefaultIPGateway", _ 219:                                     "GatewayCostMetric" ...: 224: 225:            ' DNS --------------------------------------------------------------------------------- 226:            DisplayFormattedProperty objWMIAdapterInstance, _ 227:                                     "DNS registration enabled", _ 228:                                     "DomainDNSRegistrationEnabled", _ 229:                                     Null 246:            DisplayFormattedProperty objWMIAdapterInstance, _ 247:                                     "DNS enabled for WINS resolution", _ 248:                                     "DNSEnabledForWINSResolution", 249:                                     Null 250: 251:            ' WINS --------------------------------------- 252:            DisplayFormattedProperty objWMIAdapterInstance, _ 253:                                     "Primary WINS Server", _ 254:                                     "WINSPrimaryServer", _ 255:                                     Null ...: 264:            DisplayFormattedProperty objWMIAdapterInstance, _ 265:                                     "Enable LMHOSTS lookup", _ 266:                                     "WINSEnableLMHostsLookup", _ 267:                                     Null 268: 269:            Select Case objWMIAdapterInstance.TcpipNetbiosOptions 270:                   Case 0 271:                        DisplayFormattedProperty objWMIAdapterInstance, _ 272:                                                 "NETBIOS over TCP/IP", _ 273:                                                 "by DHCP", _ 274:                                                 Null 275:                   Case 1 276:                        DisplayFormattedProperty objWMIAdapterInstance, _ 277:                                                 "NETBIOS over TCP/IP", _ 278:                                                 "ENABLED", 279:                                                 Null 280:                   Case 2 281:                        DisplayFormattedProperty objWMIAdapterInstance, _ 282:                                                 "NETBIOS over TCP/IP", 283:                                                 "DISABLED", 284:                                                 Null 285:            End Select 286: 287:            ' IP Security ------------------------------------------------------------------------ 288:            If objWMIAdapterInstance.IPFilterSecurityEnabled Then 289:               DisplayFormattedProperty objWMIAdapterInstance, _ 290:                                        "IP filtering security enabled", _ 291:                                        "ENABLED", 292:                                        Null ...: 305:               DisplayFormattedProperty objWMIAdapterInstance, _ 306:                                        "UDP ports allowed", _ 307:                                        "IPSecPermitUDPPorts", _ 308:                                        Null 309:                 End If 310:              End If 311:              Set objWMIAdapterInstance = Nothing 312:           End If 313:        End If 314:    Next 315:    WScript.Echo ...: 320:    ]]> 321:    </script> 322:  </job> 323:</package> 

end example

To retrieve the instance of the Win32_NetworkAdapterConfiguration that corresponds to the adapter (lines 180 through 182 in Sample 2.11), the script uses the Key property (called Index) of the Win32_NetworkAdapterConfiguration class with the index number of the adapter instance (line 182) previously retrieved from the script with the enumeration at line 85 (see Sample 2.9).

You will note that Sample 2.10 jumps from line 159 to Sample 2.11 at line 180. Lines 160 through 179 are not discussed in this section, because they use the Win32_NetworkProtocol class. This class is explained in section 2.4.7 ("Networking classes") in this chapter (see also Sample 2.42).

When the script is executed, the output is as follows (the section between lines 17 and 63 is skipped, since it is provided by the Win32_NetworkProtocol class examined in section 2.4.7).

  1:    C:\>"GetNetworkConfiguration (With NetProtocols).wsf" "Compaq NC3121 Fast Ethernet NIC"  2:    Microsoft (R) Windows Script Host Version 5.6  3:    Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  4:  5:    Adapter name: ............................ Compaq NC3121 Fast Ethernet NIC  6:    Device availability: ..................... Running/Full Power  7:    Adapter type: ............................ Ethernet 802.3  8:    Adapter state: ........................... Connected  9:    MAC address is : ......................... 00:08:C7:A9:27:56 10:    Adapter service name: .................... N100 11:    Last reset: .............................. 21-10-2001 12:02:00 12: 13:    *IRQ resource: ........................... 10 14:    Memory address: .......................... 0x40300000-0x40300FFF 15:    Memory address: .......................... 0x40100000-0x401FFFFF 16:    I/O Port: ................................ 0x00002420-0x0000243F 17: ..: ..: ..: 63: 64:    DHCP enabled: ............................ FALSE 65:    IP address(es): .......................... 10.10.10.3 255.0.0.0 66:    IP connection metric: .................... 30 67:    Default Gateway(s) and metric: ........... 10.10.10.254 1 68:    Dead gateway detection enabled: .......... TRUE 69:    DNS registration enabled: ................ FALSE 70:    DNS FULL registration enabled: ........... TRUE 71:    DNS search order: ........................ 10.10.10.3 72:    DNS domain: .............................. LissWare.Net 73:    DNS enabled for WINS resolution: ......... FALSE 74:    WINS scope ID: ........................... 75:    Enable LMHOSTS lookup: ................... FALSE 76:    NETBIOS over TCP/IP: ..................... ENABLED 77:    IP filtering security enabled: ........... ENABLED 78:    IP permitted protocols: .................. 0 79:    TCP ports allowed: ....................... 0 80:    UDP ports allowed: ....................... 0 

Note that for the "IP address" (line 65) and the "Default Gateway and metric" (line 67) properties are displayed on the same line. This piece of code (see Sample 2.11, lines 208 through 211 and lines 216 through 219) takes advantage of the DisplayFormattedProperty() function capabilities (see Sample 1.6, "The DisplayFormattedPropertyFunction.vbs function") to display two properties that are usually shown together:

  • The IP address and its mask

  • The Gateway address and its metric

This allows an output similar to the one obtained with the IPConfig.Exe utility.

The previous scripts are able to retrieve information from the real-world manageable entities (such as a network adapter), but at no time do the samples show how to modify the information retrieved. However, the Win32_NetworkAdapterConfiguration class exposes an important set of methods that allows the modification of the network adapter configuration. Table 2.7 lists the miscellaneous methods.

Table 2.7: The Win32_NetworkAdapterConfiguration Methods

Method name

Description

DisableIPSec

The DisableIPSec method is used to disable IP security on this TCP/IP-enabled network adapter.

EnableDHCP

The EnableDHCP method enables the Dynamic Host Configuration Protocol (DHCP) for service with this network adapter. DHCP allows IP addresses to be dynamic allocated.

EnableDNS

The EnableDNS method enables the Domain Name System (DNS) for service on this TCP/IP-bound network adapter.

EnableIPFilterSec

The EnableIPFilterSec method is used to enable IP security globally across all IP-bound network adapters. With security enabled, the operational security characteristics for any single network adapter can be controlled using the network adapter specific EnableIPSec method.

EnableIPSec

The EnableIPSec method is used to enable IP security on this specific TCP/IP-enabled network adapter. Ports are secured only when the IPFilterSecurityEnabled property is TRUE.

EnableStatic

The EnableStatic method enables static TCP/IP addressing for the target network adapter. As a result, DHCP for this network adapter is disabled.

EnableWINS

The EnableWINS method enables Windows Internet Naming Service (WINS) settings specific to TCP/IP, but independent of the network adapter.

ReleaseDHCPLease

The ReleaseDHCPLease method releases the IP address bound to a specific DHCP enabled network adapter. WARNING: If DHCP is enabled on this local computer system, the option disables TCP/IP on this specific network adapter. Unless you have an alternate path to the target system, that is, anotherTCP/IP bound network adapter, all TCP/IP communications will be lost.

ReleaseDHCPLeaseAll

The ReleaseDHCPLeaseAll method releases the IP addresses bound to all DHCP enabled network adapters. WARNING: If DHCP is enabled on this local computer system, the option will terminate all DHCP TCP/IP connections. The method returns an integer value that can be interpretted as follows:

0 - Successful completion, no reboot required.

RenewDHCPlease

The RenewDHCPLease method renews the IP address on specific DHCP-enabled network adapters. The lease for the IP address assigned via a DHCP server has an expiration date that the client must renew if it intends to continue use of the assigned IP address.

RenewDHCPLeaseAll

The RenewDHCPLeaseAll method renews the IP addresses on all DHCP-enabled network adapters. The lease for the IP address assigned via a DHCP server has an expiration date that the client must renew if it intends to continue use of the assigned IP address.

SetArpAlwaysSourceRoute

The SetArpAlwaysSourceRoute method is used to set the transmission of ARP queries by the TCP/IP.

SetArpUseEtherSNAP

The SetArpUseEtherSNAP method is used to enable Ethernet packets to use 802.3 SNAP encoding. By default, the stack transmits packets in Digital, Intel, Xerox(DIX) Ethernet format. Itwill always receive both formats.

SetDatabasePath

The SetDatabasePath method sets the path to the standard Internet database files (HOSTS, LMHOSTS, NETWORKS, PROTOCOLS). It is used by the Windows Sockets interface.

SetDeadGW Detect

The SetDeadGWDetect method is used to enable Dead Gateway detection. Setting this parameter to TRUE causes TCP to perform Dead Gateway Detection. With this feature enabled, TCP asks IP to change to a backup gateway if it retransmits a segment several times without receiving a response.

SetDefaultTOS

The SetDefaultTOS method is used to set the defaultType of Service (TOS)value in the header of outgoing IP packets.

SetDefaultTTL

The SetDefaultTTL method is used to set the defaultTime to Live (TTL)value in the header of outgoing IP packets. The TTL specifies the number of routers an IP packet may pass through to reach its destination before being discarded. Each router decrements the TTL count of a packet by one and discards the packets with a TTL of 0. Default: 32, Valid Range: 1 - 255

SetDNS Domain

The SetDNSDomain method allows for the setting of the DNS domain. This is an instance dependent method call that applies on a per adapter basis. On Windows 2000 the setting applies to the targeted adapter. On NT4 this setting is global.

SetDNSServerSearchOrder

The SetDNSServerSearchOrder method allows for the setting of the server search order as an array of elements. This is an instance dependent method call that applies on a per adapter basis. On Windows 2000 the setting applies to the targeted adapter. On NT4 this setting is global.

SetDNSSuffixSearchOrder

The SetDNSSuffixSearchOrder method allows for the setting of the suffix search order as an array of elements. This is an instance independent method call that applies across all adapters. Windows NT only.

SetDynamicDNS Registration

The SetDynamicDNSRegistration method is used to indicate dynamic DNS registration of IP addresses for this IP bound adapter.

SetForwardBufferMemory

The SetForwardBufferMemory method is used to specify how much memory IP allocates to store packet data in the router packet queue. When this buffer space is filled, the router begins discarding packets at random from its queue. Packet queue data buffers are 256 bytes in length, so the value of this parameter should be a multiple of 256. Multiple buffers are chained together for larger packets. The IP header for a packet is stored separately. This parameter is ignored and no buffers are allocated if the IP router is not enabled. The buffer size can range from the network MTU to the a value smaller than OxFFFFFFFF. Default: 74240 (fifty 1480-byte packets, rounded to a multiple of 256).

SetGateways

The SetGateways method is used to specify a list of gateways for routing packets destined for a different subnet than the one this adapter is connected to. A more specific route should not exist for this subnet.

SetIGMPLevel

The SetIGMPLevel method is used to set the extent to which the system supports IP multicasting and participates in the Internet Group Management Protocol.

SetIPConnectionMetric

The SetIPConnectionMetric method is used to set the routing metric associated with this IP bound adapter.

SetIPUseZeroBroadcast

The SetIPUseZeroBroadcast method is used to set IP zero broadcast usage. If this parameter is set to TRUE, then IP will use zeros-broadcasts (0.0.0.0) instead of ones-broadcasts (255.255.255.255). Most systems use ones-broadcasts, but systems derived from BSD implementations use zeros-broadcasts. Systems that use different broadcasts will not interoperate on the same network. Default: FALSE.

SetIPXFrameTypeNetworkPairs

The SetlPXFrameTypeNetworkPairs method is used to set Internetworking Packet Exchange (IPX) network number/frame pairs for this network adapter. Windows 2000 and Windows NT 3.51 and higher use an IPX network number for routing purposes. It is assigned to each configured frame type/network adapter combination on your computer system. This number is sometimes referred to as the "external network number." It must be unique for each network segment. If the frame type is set to AUTO, the network number should to zero.

SetIPXVirtualNetworkNumber

The SetIPXVirtualNetwork Number method is used to set the Internetworking Packet Exchange (IPX) virtual network number on the target computer system. Windows 2000 and Windows NT 3.51 or greater uses an internal network number for internal routing. The internal network number is also known as a virtual network number. It uniquely identifies the computer system on the network.

SetKeepAliveInterval

The SetKeepAliveInterval method is used to set the interval separating Keep Alive Retransmissions until a response is received. Once a response is received, the delay until the next Keep Alive Transmission is again controlled by the value of KeepAliveTime. The connection will be terminated after the number of retransmissions specified by TcpMaxDataRetransmissions have gone unanswered.

SetKeepAliveTime

The SetKeepAliveTime method is used to set how often TCP attempts to verify that an idle connection is still available by sending a Keep Alive packet. If the remote system is still reachable and functioning, it will acknowledge the Keep Alive transmission. Keep Alive packets are not sent by default. This feature may be enabled in a connection by an application.

SetMTU

The SetMTU method is used to set the default Maximum Transmission Unit (MTU) for a network interface. The MTU is the maximum packet size (in bytes) that the transport will transmit over the underlying network. The size includes the transport header. Note that an IP datagram may span multiple packets. Values larger than the default for the underlying network will result in the transport using the network default MTU. Values smaller than 68 will result in the transport using an MTU of 68.

SetNumForwardPackets

The SetNumForwardPackets method is used to set the number of IP packet headers allocated for the router packet queue. When all headers are in use, the router will begin to discard packets from the queue at random.

SetPMTUBHDetect

The SetPMTUBHDetect method is used to enable detection of Black Hole routers. Setting this parameter to TRUE causes TCP to try to detect Black Hole routers while doing Path MTU Discovery. A Black Hole router does not return the Internet Control Message Protocol (ICMP) Destination Unreachable messages when it needs to fragment an IP datagram with the Don't Fragment bit set. TCP depends on receiving these messages to perform Path MTU Discovery. With this feature enabled, TCP will try to send segments without the Don't Fragment bit set if several retransmissions of a segment go unacknowledged. If the segment is acknowledged as a result, the maximum segment size (MSS) will be decreased and the Don't Fragment bit will be set in future packets on the connection. Enabling Black Hole detection increases the maximum number of retransmissions performed for a given segment.

SetPMTUDiscovery

The SetPMTUDiscovery method is used to enable Maximum Transmission Unit (MTU) discovery. Setting this parameter to TRUE causes TCP to attempt to discover the MTU (or largest packet size) over the path to a remote host. By discovering the Path MTU and limiting TCP segments to this size, TCP can eliminate fragmentation at routers along the path that connect networks with different MTUs. Fragmentation adversely affects TCP throughput and network congestion. Setting this parameter to FALSE causes an MTU of 576 bytes to be used for all connections that are not connected to machines on the local subnet. Default: TRUE.

SetTcpipNetbios

The SetTcpipNetbios method is used to set the default operation of NetBIOS over TCP/IP. Windows 2000 only.

SetTcpMaxConnectRetransmissions

The SetTcpMaxConnectRetransmissions method is used to set the number of attempts TCP will retransmit a Connect Request before aborting. The initial retransmission timeout is 3 seconds and doubles for each attempt.

SetTcpMaxDataRetransmissions

The SetTcpMaxDataRetransmissions method is used to set the number of times TCP will retransmit an individual data segment before aborting the connection. The retransmission timeout doubles with each successive retransmission on a connection.

SetTcpNumConnections

The SetTcpNumConnections method is used to set the maximum number of connections that TCP may have open simultaneously.

SetTcpUseRFC1122UrgentPointer

The SetTcpUseRFC1122UrgentPointer method is used to specify whether TCP uses the RFC 1122 specification for urgent data, or the mode used by Berkeley Software Design (BSD) derived systems. The two mechanisms interpret the urgent pointer in the TCP header and the length of the urgent data differently. They are not interoperable. Windows 2000 and Windows NT version 3.51 or higher defaults to BSD mode.

SetTcpWindowSize

The SetTcpWindowSize method is used to set the maximum TCP Receive Window size offered by the system. The Receive Window specifies the number of bytes a sender can transmit without receiving an acknowledgment. In general, larger receive windows improve performance over high-delay and high-bandwidth networks. For efficiency, the receive window should be an even multiple of the TCP Maximum Segment Size (MSS).

SetWINSServer

The SetWINSServer method sets the primary and secondary Windows Internet Naming Service (WINS) servers on this TCP/IP-bound network adapter. This method is applied independently of the network adapter.

To gather more information about the parameters required by these methods, you can use the LoadCIMInXL.wsf script (see Sample 4.32 in the appendix) or refer to the Platform SDK. Because each method corresponds to a network setting, the command-line parameters required by the script represent the parameters required by each Win32_NetworkAdapterConfiguration method. Before diving into the script code (see Sample 2.12), let's examine the script parameters. This demonstrates the script capabilities in terms of network device configuration. The following output shows the script usage information with some command-line syntax samples at the end:

 C:\>SetNetworkConfiguration.wsf Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2001. All rights reserved. Usage: SetNetworkConfiguration.wsf AdapterName                                    [List]                                    [EnableDHCP]                                    [ReleaseDHCPLease]                                    [ReleaseDHCPLeaseAll]                                    [RenewDHCPLease]                                    [RenewDHCPLeaseAll]                                    [EnableStatic]                                    [SetIPConnectionMetric]                                    [SetGateways]                                    [SetDeadGWDetect]                                    [SetDNSDomain]                                    [SetDNSServerSearchOrder]                                    [SetDNSSuffixSearchOrder]                                    [SetDynamicDNSRegistration]                                    [EnableWINS]                                    [SetWINSServer]                                    [SetTcpipNetbios]                                    [EnableIPSec]                                    [DisableIPSec]                                    [EnableIPsecFilter]                                    [/Machine:value]                                    [/User:value]                                    [/Password:value] Options: AdapterName               : Define the name of the network adapter to configure. List                      : Only list the adapter names. EnableDHCP                : Enable DHCP for the given adapter. ReleaseDHCPLease          : Release DHCP lease for the given adapter. ReleaseDHCPLeaseAll       : Release DHCP lease for all adapters. RenewDHCPLease            : Renew DHCP lease for the given adapter. RenewDHCPLeaseAll         : Renew DHCP for all adapters. EnableStatic              : Enable static IP address(es) for the given adapter. SetIPConnectionMetric     : Set the IP connection metric for the given adapter. SetGateways               : Set the Gateway IP address(es) for the given adapter. SetDeadGWDetect           : Set dead gateway detection for the given adapter. SetDNSDomain              : Set DNS domain for the given adapter. SetDNSServerSearchOrder   : Set the DNS search order for the given adapter. SetDNSSuffixSearchOrder   : Set the DNS suffix search order for the given adapter. SetDynamicDNSRegistration : Set the Dynamic DNS registration for the given adapter. EnableWINS                : Enable WINS for the given adapter. SetWINSServer             : Set the WINS IP address(es) for the given adapter. SetTcpipNetbios           : Set NETBIOS over TCP/IP state for the given adapter. EnableIPSec               : Enable IPsec for all adapters. DisableIPSec              : Disable IPsec for all adapters. EnableIPsecFilter         : Enable IPsec filters for all adapters. Machine                   : determine the WMI system to connect to. (default=LocalHost) User                      : determine the UserID to perform the remote connection. (default=none) Password                  : determine the password to perform the remote connection. (default=none) Examples: SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" EnableDHCP SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" ReleaseDHCPLease SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" ReleaseDHCPLeaseAll SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" RenewDHCPLease SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" RenewDHCPLeaseAll SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC"                             EnableStatic="192.1.1.1/255.255.0.0,193.1.1.2/255.0.0.0" SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" SetIPConnectionMetric=98 SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC"                             SetGateways="192.1.1.1m98,193.1.1.2m97" SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" SetDeadGWDetect=True SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" SetDNSDomain="LissWare.Net "SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC"                             SetDNSServerSearchOrder="192.10.10.1,10.10.10.3" SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC"                             SetDNSSuffixSearchOrder="MySub1.LissWare.Net,MySub2.LissWare.Net" SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" SetDynamicDNSRegistration="True,True" SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC"                             EnableWINS="True,True,%SystemRoot%\System32\Drivers\Etc\LMHOSTS," SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" SetWINSServer="192.1.1.1,193.1.1.2" SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" SetTcpipNetbios=Disable SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" EnableIPSec="80;443,53;20;21,0;1" SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" DisableIPSec SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" EnableIPsecFilter=True 

Sample 2.12: Configuring a network adapter (Part I)

start example

   1:<?xml version="1.0"?>   .:   8:<package>   9:  <job>  ..:  13:    <runtime>  ..:  62:    </runtime>  63:  64:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeWin32_NetAdapterConfigRCFunction.vbs" />  65:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\ConvertStringInArrayFunction.vbs" />  66:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\TinyErrorHandler.vbs" />  67:  68:    <object prog  reference="true"/>  69:    <object prog  />  70:  71:    <script language="VBscript">  72:    <![CDATA[  ..:  76:    Const cComputerName = "LocalHost"  77:    Const cWMINameSpace = "root/cimv2"  78:    Const cWMIClass = "Win32_NetworkAdapterConfiguration" ...: 158:    ' ------------------------------------------------------------------------------ 159:    ' Parse the command line parameters 160:    boolAdapterList = WScript.Arguments.Named("List") 161:    If Len(boolAdapterList) = 0 Then boolAdapterList = False 162: 163:    If (WScript.Arguments.Unnamed.Count = 0 And boolAdapterList = False) Or _ 164:       (WScript.Arguments.Unnamed.Count <> 0 And boolAdapterList = True) Then 165:       WScript.Arguments.ShowUsage() 166:       WScript.Quit 167:    Else 168:       If WScript.Arguments.Unnamed.Count Then 169:          strAdapterName = WScript.Arguments.Unnamed.Item(0) 170:       End If 171:    End If 172: 173:    For intUnnamedIndice = 1 To WScript.Arguments.Unnamed.Count - 1 174:       varTemp = ConvertStringInArray (WScript.Arguments.Unnamed(intUnnamedIndice), cEqual) 175:       If Ubound (varTemp) = 0 Then 176:          strOperation = varTemp(0) 177:          strAssignment = "" 178:       Else 179:          strOperation = varTemp(0) 180:          strAssignment = varTemp(1) 181:       End If 182: 183:       Select Case Ucase(strOperation) 184: 185:              ' ------------------------------------------------------------------------------ 186:              Case "ENABLEDHCP" 187:                  boolEnableDHCP = True 188:              ' ------------------------------------------------------------------------------ 189:              Case "RELEASEDHCPLEASE" 190:                   boolReleaseDHCPLease = True 191:              ' ------------------------------------------------------------------------------ 192:              Case "RELEASEDHCPLEASEALL" 193:                   boolReleaseDHCPLeaseAll = True 194:              ' ------------------------------------------------------------------------------ 195:              Case "RENEWDHCPLEASE" 196:                   boolRenewDHCPLease = True 197:              ' ------------------------------------------------------------------------------ 198:              Case "RENEWDHCPLEASEALL" 199:                  boolRenewDHCPLeaseAll = True 200:              ' ------------------------------------------------------------------------------ 201:              Case "ENABLESTATIC" 202:                   If Len(strAssignment) Then 203:                      strAssignment = ConvertStringInArray (strAssignment, cComma) 204:                      SplitArrayInTwoArrays strAssignment, _ 205:                                            arrayIPAddresses, _ 206:                                            arrayIPMasks, _ 207:                                            cSlash 208:                      boolIPAddresses = True 209:                   End If 210:              ' ------------------------------------------------------------------------------ 211:              Case "SETIPCONNECTIONMETRIC" 212:                   If Len(strAssignment) Then 213:                      intIPConnectionMetric = Cint(strAssignment) 214:                      boolIPConnectionMetric = True 215:                   End If 216:              ' ------------------------------------------------------------------------------ 217:              Case "SETGATEWAYS" 218:                   If Len(strAssignment) Then 219:                      strAssignment = ConvertStringInArray (strAssignment, cComma) 220:                      SplitArrayInTwoArrays strAssignment, _ 221:                                            arrayIPGateways, _ 222:                                            arrayIPGatewayMetric, _ 223:                                            cMletter 224:                      boolIPGateways = True 225:                   End If 226:              ' ------------------------------------------------------------------------------ 227:              Case "SETDEADGWDETECT" 228:                   Select Case Ucase(strAssignment) 229:                          Case "TRUE" 230:                               boolSetDeadGWDetectValue = True 231:                               boolSetDeadGWDetect = True 232:                          Case "FALSE" 233:                               boolSetDeadGWDetectValue = False 234:                               boolSetDeadGWDetect = True 235:                          Case Else 236:                               boolSetDeadGWDetect = False 237:                   End Select 238:              ' ------------------------------------------------------------------------------ 239:              Case "SETDNSDOMAIN" 240:                   strDNSDomain = strAssignment 241:                   boolDNSDomain = True 242:              ' ------------------------------------------------------------------------------ 243:              Case "SETDNSSERVERSEARCHORDER" 244:                   If Len (strAssignment) Then 245:                      arrayDNSServerSearchOrder = ConvertStringInArray (strAssignment, cComma) 246:                      boolDNSServerSearchOrder = True 247:                   End If 248:              ' ------------------------------------------------------------------------------ 249:              Case "SETDNSSUFFIXSEARCHORDER" 250:                   arrayDNSSuffixSearchOrder = ConvertStringInArray (strAssignment, cComma) 251:                   boolDNSSuffixSearchOrder = True 252:              ' ------------------------------------------------------------------------------ 253:              Case "SETDYNAMICDNSREGISTRATION" 254:                   If Len(strAssignment) Then 255:                      arrayDynamicDNSRegistration = ConvertStringInArray (strAssignment, cComma) 256:                      If Ubound(arrayDynamicDNSRegistration) Then 257:                         boolDynamicDNSRegistration = True 258:                      End If 259:                   End If 260:              ' ------------------------------------------------------------------------------ 261:              Case "ENABLEWINS" 262:                   If Len(strAssignment) Then 263:                      arrayEnableWINS = ConvertStringInArray (strAssignment, cComma) 264:                      If Ubound(arrayEnableWINS) Then 265:                         boolEnableWINS = True 266:                      End If 267:                   End If 268:              ' ------------------------------------------------------------------------------ 269:              Case "SETWINSSERVER" 270:                   If Len(strAssignment) Then 271:                      arrayWINSServer = ConvertStringInArray (strAssignment, cComma) 272:                   Else 273:                      Redim arrayWINSServer (1) 274:                      arrayWINSServer (0) = "" 275:                      arrayWINSServer (1) = "" 276:                   End If 277:                   boolWINSServer = True 278:              ' ------------------------------------------------------------------------------ 279:              Case "SETTCPIPNETBIOS" 280:                   Select Case Ucase(strAssignment) 281:                   Case "BYDHCP" 282:                        intTcpipNetbios = 0 283:                        boolTcpipNetbios = True 284:                   Case "ENABLE" 285:                        intTcpipNetbios = 1 286:                        boolTcpipNetbios = True 287:                   Case "DISABLE" 288:                        intTcpipNetbios = 2 289:                        boolTcpipNetbios = True 290:              End Select 291:              ' ------------------------------------------------------------------------------ 292:              Case "ENABLEIPSEC" 293:                  If Len(strAssignment) Then 294:                     strAssignment = ConvertStringInArray (strAssignment, cComma) 295:                     arrayTCP = ConvertStringInArray (strAssignment(0), cSemiColumn) 296:                     arrayUDP = ConvertStringInArray (strAssignment(1), cSemiColumn) 297:                     arrayIP = ConvertStringInArray (strAssignment(2), cSemiColumn) 298:                     boolEnableIPSec = True 299:                  End If 300:              ' ------------------------------------------------------------------------------ 301:              Case "DISABLEIPSEC" 302:                   boolDisableIPSec = True 303:              ' ------------------------------------------------------------------------------ 304:              Case "ENABLEIPSECFILTER" 305:                   Select Case Ucase(strAssignment) 306:                          Case "TRUE" 307:                               boolEnableIPsecFilterValue = True 308:                               boolEnableIPsecFilter = True 309:                          Case "FALSE" 310:                               boolEnableIPsecFilterValue = False 311:                               boolEnableIPsecFilter = True 312:                          Case Else 313:                               boolEnableIPsecFilter = False 314:                   End Select 315:       End Select 316:    Next 317: 318:    strUserID = WScript.Arguments.Named("User") 319:    If Len(strUserID) = 0 Then strUserID = "" ...: 329: ...: ...: ...: 

end example

The biggest challenge of this script is to properly parse the command line. Sample 2.12 is 492 lines in length, but the command-line parsing easily takes 50 percent of the code (from line 160 through 319). This comes from the fact that the script exposes more than 20 command-line parameters, while some Win32_NetworkAdapterConfiguration class methods require one or more arrays as input parameters. On a command line, it is only possible to read strings. To work around this difficulty, Sample 2.12 includes a subroutine called ConvertStringInArrayFunction.vbs (line 65) and uses the SplitArrayInTwoArrays() function (lines 456 through 487). These two functions are helper functions to ease the command-line parsing and the string to array conversion required by some of the Win32_NetworkAdapterConfiguration class method parameters. Note that the command line only accepts keywords and does not make use of any keywords starting with a backslash. The script code configuring a network adapter is listed in Sample 2.12 (for the command-line parsing) and in Sample 2.13 (for the WMI network adapter configuration).

Sample 2.13: Configuring a network adapter (Part II)

start example

 ...: ...: ...: 329: 330:    Set objWMIServices = objWMILocator.ConnectServer(strComputerName, cWMINameSpace, _ 331:                                                     strUserID, strPassword) ...: 334:    Set objWMIInstances = objWMIServices.InstancesOf (cWMIClass) 335:    Set objWMIClass = objWMIServices.Get (cWMIClass) 336: 337:    For Each objWMIInstance in objWMIInstances 338:        If boolAdapterList Then 339:           WScript.Echo Mid (objWMIInstance.Caption, 12) 340:        Else 341:           If Mid (objWMIInstance.Caption, 12) = strAdapterName Then 342:              WScript.Echo "Configuring '" & objWMIInstance.Description & _ 343:                           "' adapter ..." & vbCRLF 344: 345:              If boolEnableDHCP Then 346:                 intRC = objWMIInstance.EnableDHCP () 347:                 WScript.Echo "EnableDHCP: " & Win32_NetAdapterConfigRC(intRC) 348:              End If 349: 350:              If boolReleaseDHCPLease Then 351:                 intRC = objWMIInstance.ReleaseDHCPLease () 352:                 WScript.Echo "ReleaseDHCPLease: " & Win32_NetAdapterConfigRC(intRC) 353:              End If 354: 355:              If boolReleaseDHCPLeaseAll Then 356:                 intRC = objWMIClass.ReleaseDHCPLeaseAll () 357:                 WScript.Echo "ReleaseDHCPLeaseAll: " & Win32_NetAdapterConfigRC(intRC) 358:              End If 359: 360:              If boolRenewDHCPLease Then 361:                 intRC = objWMIInstance.RenewDHCPLease () 362:                 WScript.Echo "RenewDHCPLease: " & Win32_NetAdapterConfigRC(intRC) 363:              End If 364: 365:              If boolRenewDHCPLeaseAll Then 366:                 intRC = objWMIClass.RenewDHCPLeaseAll () 367:                 WScript.Echo "RenewDHCPLeaseAll: " & Win32_NetAdapterConfigRC(intRC) 368:              End If 369: 370:              If boolIPAddresses Then 371:                 intRC = objWMIInstance.EnableStatic (arrayIPAddresses, arrayIPMasks) 372:                 WScript.Echo "EnableStatic: " & Win32_NetAdapterConfigRC(intRC) 373:              End If 374: 375:              If boolIPConnectionMetric Then 376:                 intRC = objWMIInstance.SetIPConnectionMetric (intIPConnectionMetric) 377:                 WScript.Echo "SetIPConnectionMetric: " & Win32_NetAdapterConfigRC(intRC) 378:              End If 379: 380:              If boolIPGateways Then 381:                 intRC = objWMIInstance.SetGateways (arrayIPGateways, arrayIPGatewayMetric) 382:                 WScript.Echo "SetGateways: " & Win32_NetAdapterConfigRC(intRC) 383:              End If 384: 385:              If boolSetDeadGWDetect Then 386:                 intRC = objWMIClass.SetDeadGWDetect (boolSetDeadGWDetectValue) 387:                 WScript.Echo "SetDeadGWDetect: " & Win32_NetAdapterConfigRC(intRC) 388:              End If 389: 390:              If boolDNSDomain Then 391:                 intRC = objWMIInstance.SetDNSDomain (strDNSDomain) 392:                 WScript.Echo "SetDNSDomain: " & Win32_NetAdapterConfigRC(intRC) 393:              End If 394: 395:              If boolDNSServerSearchOrder Then 396:                 intRC = objWMIInstance.SetDNSServerSearchOrder (arrayDNSServerSearchOrder) 397:                 WScript.Echo "SetDNSServerSearchOrder: " & Win32_NetAdapterConfigRC(intRC) 398:              End If 399: 400:              If boolDNSSuffixSearchOrder Then 401:                 intRC = objWMIClass.SetDNSSuffixSearchOrder (arrayDNSSuffixSearchOrder) 402:                 WScript.Echo "SetDNSSuffixSearchOrder: " & Win32_NetAdapterConfigRC(intRC) 403:              End If 404: 405:              If boolDynamicDNSRegistration Then 406:                 intRC = objWMIInstance.SetDynamicDNSRegistration _ 407:                                                    (arrayDynamicDNSRegistration (0), _ 408:                                                     arrayDynamicDNSRegistration(1)) 409:                 WScript.Echo "SetDynamicDNSRegistration: " & Win32_NetAdapterConfigRC(intRC) 410:              End If 411: 412:              If boolEnableWINS Then 413:                 intRC = objWMIClass.EnableWINS (arrayEnableWINS(0), _ 414:                                                 arrayEnableWINS(1), _ 415:                                                 arrayEnableWINS(2), _ 416:                                                 arrayEnableWINS(3)) 417:                 WScript.Echo "EnableWINS: " & Win32_NetAdapterConfigRC(intRC) 418:              End If 419: 420:              If boolWINSServer Then 421:                 intRC = objWMIInstance.SetWINSServer (arrayWINSServer(0), _ 422:                                                       arrayWINSServer(1)) 423:                 WScript.Echo "SetWINSServer: " & Win32_NetAdapterConfigRC(intRC) 424:              End If 425: 426:              If boolTcpipNetbios Then 427:                 intRC = objWMIInstance.SetTcpipNetbios (intTCPIPNetbios) 428:                 WScript.Echo "SetTcpipNetbios: " & Win32_NetAdapterConfigRC(intRC) 429:              End If 430: 431:              If boolEnableIPSec Then 432:                 intRC = objWMIInstance.EnableIPSec (arrayTCP, arrayUDP, arrayIP) 433:                 WScript.Echo "EnableIPSec: " & Win32_NetAdapterConfigRC(intRC) 434:              End If 435: 436:              If boolDisableIPSec Then 437:                 intRC = objWMIInstance.DisableIPSec () 438:                 WScript.Echo "DisableIPSec: " & Win32_NetAdapterConfigRC(intRC) 439:              End If 440: 441:              If boolEnableIPsecFilter Then 442:                 intRC = objWMIClass.EnableIPFilterSec (boolEnableIPsecFilterValue) 443:                 WScript.Echo "EnableIPFilterSec: " & Win32_NetAdapterConfigRC(intRC) 444:              End If 445: 446:              Set objWMIInstance = Nothing 447:           End If 448:        End If 449:    Next 450:    WScript.Echo ...: 455:    ' ------------------------------------------------------------------------------- 456:    Function SplitArrayInTwoArrays (varTemp, array1, array2, strSeparator) ...: 487:    End Function 488: 489:    ]]> 490:    </script> 491:  </job> 492:</package> 

end example

Each command-line parameter corresponds to a Win32_NetworkAdapterConfiguration method and uses the name of the method. Although it is interesting to look at the code in detail, we do not examine every parameter because Sample 2.12 accepts more than 20 parameters. Once the most typical parameters are explained, all other parameters parsing use the same scripting logic. Moreover, the scripting technique and principles to analyze command-line parameters in the next samples are the same. This allows us to focus on the WMI coding only. For Sample 2.12, we examine the code corresponding to the following command-line parameters:

  • EnableDHCP

  • ReleaseDHCPLease

  • ReleaseDHCPLeaseAll

  • RenewDHCPLease

  • RenewDHCPLeaseAll

  • EnableStatic

  • SetIPConnectionMetric

  • SetGateways

  • SetDeadGWDetect

  • EnableIPSec

  • DisableIPSec

  • EnableIPSecFilter

For each of these parameters, we also examine the corresponding WMI coding shown in Sample 2.13. Before configuring settings on the desired network adapter, an instance of the considered network adapter is retrieved at line 334. At line 335, the script also retrieves an instance from the Win32_NetworkAdapterConfiguration class. We will see further during the script code analysis why we need to do this.

The script code analysis is as follows:

  • EnableDHCP: Once this keyword is given on the command line, the script configures the adapter as a DHCP client. The keyword presence is tested at line 186 and the DHCP configuration is performed from line 345 through 348. The Win32_NetworkAdapterConfiguration EnableDHCP method does not require a parameter (line 346).

  • ReleaseDHCPLease: From a coding technique point of view, this command-line parameter works the same as the previous one. However, once the keyword is given on the command line, the script releases the adapter DHCP IP address. The keyword presence is tested at line 189 and the DHCP IP address release is performed from line 350 through 353. The Win32_NetworkAdapterConfiguration ReleaseDHCPLease method does not require a parameter (line 351).

  • ReleaseDHCPLeaseAll: Again, from a coding technique point of view, this command-line parameter works the same as the previous ones. However, once the keyword is given, it releases the DHCP address on all network adapters available in the computer. The keyword presence is tested at line 192, and the DHCP IP address release is performed from line 355 through 358. Note that the method invocation is a bit unusual (line 356). Because the ReleaseDHCPLeaseAll method does not relate to a specific network adapter (since it releases the IP address of all network adapters in the computer), the method is not invoked from the network adapter instance but from the network adapter class instance (line 356). The network adapter class instance is created at line 335, while the network adapter instance is created at line 334.

All methods that relate to a network setting that is not specific to a network adapter must be invoked from the class instance instead of the network adapter instance. These methods are defined in the CIM repository as static methods and contain a specific qualifier called static set on True. This specific qualifier method can be viewed with WMI CIM Studio, as shown in Figure 2.3. In this figure, we clearly see that the ReleaseDHCPLeaseAll method contains the static qualifier, while the ReleaseDHCPLease method does not contain this qualifier.

click to expand
Figure 2.3: The static method qualifier.

The same rule applies for the following Win32_NetworkAdapterConfiguration methods, since these methods are not specific to an adapter but apply to all adapters available in the system:

  • ReleaseDHCPLeaseAll (line 356)

  • RenewDHCPLeaseAll (line 366)

  • SetDeadGWDetect (line 386)

  • SetDNSSuffixSearchOrder (line 401)

  • EnableWINS (line413)

  • EnableIPFilterSec (line 442)

All these methods are static methods and must be invoked from a class instance. We see with further samples that there are other classes exposing static methods. This is not a peculiarity related to the Win32_NetworkAdapterConfiguration class only. Classes exposing static methods must all be used in the same way. Let's continue with the remaining methods:

  • ReNewDHCPLease: The ReNewDHCPLease keyword works in the exact same way as the ReleaseDHCPLease from a coding point of view. However, it requests a new DHCP IP address. The keyword presence is tested at line 195, and the DHCP renewal operation is performed from line 360 through 363. The Win32_NetworkAdapterConfiguration ReNewDHCPLease method does not require any parameter (line 361).

  • ReNewDHCPLeaseAll: The ReNewDHCPLeaseAll keyword is coded in the exact same way as the ReleaseDHCPLeaseAll. However, it requests a new DHCP IP address for all DHCP-enabled network adapters. The keyword presence is tested at line 198 and the DHCP renewal operation is performed from line 365 through 368. The Win32_NetworkAdapterConfiguration method ReNewDHCPLease does not require any parameter (line 366). This method is a static method similar to the ReleaseDHCPLeaseAll method and is invoked from the Win32_NetworkAdapterConfiguration class instance created at line 335.

  • EnableStatic: This command-line parameter requires two arrays as parameters. One array contains the IP addresses, while the second array contains the corresponding subnet masks. This keyword with its parameters must be given on the command line in the following format:

     C:\>SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC"                   EnableStatic="10.10.10.3/255.0.0.0,192.10.10.4/255.255.255.0" 

    The keyword presence is tested at line 201, and the parameters are parsed and converted in two arrays from line 203 through 207. Note the comma to separate the IP addresses if the network adapter is multihosted. We clearly have a direct application of the ConvertStringInArray() and SplitArrayInTwoArrays() functions to help with the command-line conversion into two arrays (lines 203 and 204). The IP address configuration is performed from line 370 through 373. The Win32_NetworkAdapterConfiguration method EnableStatic uses the two arrays as parameters (line 371).

  • SetIPConnectionMetric: This command-line parameter requires one parameter that contains the IP metric of the network adapter. The keyword must be given on the command line in the following format:

     C:\>SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC"                    SetIPConnectionMetric=0 

    The keyword presence is tested at line 211, and the parameter value is parsed and converted to an integer from line 212 through 215. The metric configuration is performed from line 375 through 378.

  • SetGateways: This command-line parameter requires two arrays as parameters. One array contains the gateway IP addresses, while the second array contains the corresponding gateway metrics. The keyword must be given on the command line in the following format:

     C:\>SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC"                             SetGateways="10.10.10.254ml,192.10.10.254m1" 

    The keyword presence is tested at line 217, and the parameters are parsed and converted in two arrays from line 218 through 225. Note the "m" letter to separate the metric from the IP gateway address and the comma to separate the gateway IP addresses if several gateways are specified. Again, we clearly see the use of the ConvertStringInArray() and SplitArrayInTwoArrays() functions to help with the command-line conversion into two arrays (lines 219 through 220). The IP address configuration is performed from line 380 through 383. The Win32_NetworkAdapterConfiguration method SetGateways uses the two created arrays as parameters (line 381).

  • SetDeadGWDetect: This command-line parameter requires one parameter, which contains a Boolean value, to determine if the dead gateway detection mechanism must be enabled or disabled. The keyword must be given on the command line in the following format:

     C:\>SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC" SetDeadGWDetect=True 

    The keyword presence is tested at line 227 and the parameter value is parsed from line 228 through 237. The dead gateway detection configuration is performed from line 385 through 388. Note the use of the static method, since the dead gateway detection mechanism does not relate to a specific network adapter.

  • EnableIPSec, DisableIPSec, and EnableIPSecFilter: It is important to note that these methods are used to configure the IP filtering parameters of the network adapter. Therefore, these methods have no relationship with the configuration of the IPSec protocol, which is totally different. Usually, two of these three command-line parameters are used together. The EnableIPSec requires one parameter that contains three arrays. These arrays contain the IP port numbers to be filtered in the TCP/IP configuration. Setting the IP port numbers is not enough to activate the IP filtering. The IP filters are only enabled if the EnableIPSecFilter command-line parameter is specified. The EnableIPSecFilter accepts one parameter that contains a Boolean value to enable or disable the IP filters. The keywords must be given on the command line in the following format:

     SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC"                             EnableIPSec="80;443,53;20;21,0;1"                             EnableIPsecFilter=True 

To parse the EnableIPSec parameters, the ConvertStringInArray() functions is used (lines 294 through 297). Notice that each array is separated on the command line by a comma (line 294), while a semicolumn separates each item in the array (lines 295 through 297). Each array corresponds to the TCP ports, UDP ports, and protocol filters, respectively. The execution of the EnableIPSec method is made in the script at the level of the adapter instance (line 432), while the EnableIPsecFilter static method is executed at the level of the Win32_NetworkAdapterConfiguration class instance (line 442). This implies that the activation of the IP filters is applied to any existing adapters in the system, while the IP filters are specific to one selected network adapter.

To disable the IP filters, the EnableIPSecFilter method is used with a Boolean parameter equal to False. To clear the IP filter values, the DisableIPSec command-line parameter is required. This parameter does not need any parameter, and its use is similar to the use of the ReleaseDHCPLeaseAll or ReNewDHCPLeaseAll command-line parameters. The keywords must be given on the command line in the following format:

 SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC"                             DisableIPSec                             EnableIPsecFilter=False 

All other parameters and methods from the Win32_NetworkAdapterConfiguration use the same logic and the same set of routines to parse and execute the command-line parameters. Some small changes in the command-line syntax are required based on the IP parameter specified. The following command-line sample shows how to use Sample 2.12 to completely configure a network adapter IP address. The sample also contains the resulting output:

 C:\>SetNetworkConfiguration.wsf "Compaq NC3121 Fast Ethernet NIC"                                 EnableStatic="10.10.10.3/255.0.0.0"                                 SetIPConnectionMetric=0                                 SetGateways="10.10.10.254ml"                                 SetDeadGWDetect=True                                 SetDNSDomain="LissWare.Net"                                 SetDNSServerSearchOrder="10.10.10.3"                                 SetDNSSuffixSearchOrder=""                                 EnableWINS="False,False,,"                                 SetTcpipNetbios=Enable                                 DisableIPSec Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2001. All rights reserved. Configuring 'Compaq NC3121 Fast Ethernet NIC' adapter ... EnableStatic: The method succeeded. SetIPConnectionMetric: The method succeeded. SetGateways: The method succeeded. SetDeadGWDetect: The method completed successfully. However, the system must be rebooted. SetDNSDomain: The method succeeded. SetDNSServerSearchOrder: The method succeeded. SetDNSSuffixSearchOrder: The method succeeded. EnableWINS: The method succeeded. SetTcpipNetbios: The method succeeded. DisableIPSec: The method completed successfully. However, the system must be rebooted. 

As we can see, it is also possible to specify several command-line parameters at the same time. This forces the script to execute the various Win32_NetworkAdapterConfiguration methods one by one.

2.3.5 Power device classes

The power device classes represent power supplies and batteries related to these devices. The classes in this category are listed in Table 2.8.

Table 2.8: The Power Device Classes

Name

Type

Description

Win32_PowerManagementEvent

Extrinsic event

Represents power management events resulting from power state changes.

Win32_Battery

Dynamic

Represents a battery connected to the computer system.

Win32_CurrentProbe

Dynamic

Represents the properties of a current monitoring sensor (ammeter).

Win32_PortableBattery

Dynamic

Represents the properties of a portable battery, such as one used for a notebook computer.

Win32_UninterruptiblePowerSupply

Dynamic

Represents the capabilities and management capacity of an uninterruptible power supply (UPS).

Win32_VoltageProbe

Dynamic

Represents the properties of a voltage sensor (electronic voltmeter).

Win32_AssociatedBattery

Association

Relates a logical device and the battery it is using.

It is important to make a clear distinction between the Win32_PowerManagementEvent class and other classes. Although the Win32_PowerManagementEvent class is also related to power management aspects, this class is an extrinsic event class and relates to the MS_Power_Management_Event_provider event provider. Because this class requires the examination of another WMI provider, we examine it further in the next chapter when looking at the MS_Power_Management_Event_provider event provider.

Sample 2.14 retrieves information about the batteries available in a computer.

Sample 2.14: Retrieving battery information

start example

   1:<?xml version="1.0"?>   .:   8:<package>   9:  <job>  ..:  13:    <runtime>  14:      <unnamed name="Portable" helpstring="Examine portable battery properties."                                    required="false" type="boolean" />  15:      <named name="Machine" helpstring="determine the WMI system to connect to.                                    (default=LocalHost)" required="false" type="string"/>  16:      <named name="User" helpstring="determine the UserID to perform the remote connection.                                    (default=none)" required="false" type="string"/>  17:      <named name="Password" helpstring="determine the password to perform the remote                                    connection. (default=none)" required="false" type="string"/>  18:    </runtime>  19:  20:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeDeviceAvailabilityFunction.vbs" />  21:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeCfgManErrCodeFunction.vbs" />  22:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeStatusInfoFunction.vbs" />  23:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodePwrManCapabilitiesFunction.vbs" />  24:  25:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeBatteryStatusFunction.vbs" />  26:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeBatteryChemistryFunction.vbs" />  27:  28:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DisplayFormattedPropertyFunction.vbs" />  29:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\TinyErrorHandler.vbs" />  30:  31:    <object prog  reference="true"/>  32:    <object prog  />  33:  34:    <script language="VBscript">  35:    <![CDATA[  ..:  53:    ' --------------------------------------------------------------------------------  54:    ' Parse the command line parameters  55:    boolPortableBattery = WScript.Arguments.Named("Portable")  56:    If Len(boolPortableBattery) = 0 Then boolPortableBattery = False  ..:  65:    If Len(strComputerName) = 0 Then strComputerName = cComputerName  66:  67:    objWMILocator.Security_.AuthenticationLevel = wbemAuthenticationLevelDefault  68:    objWMILocator.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate  69:  70:    Set objWMIServices = objWMILocator.ConnectServer(strComputerName, cWMINameSpace, _  71:                                                     strUserID, strPassword)  ..:  74:    Select Case boolPortableBattery  75:           Case TRUE  76:                Set objWMIInstances = objWMIServices.InstancesOf ("Win32_PortableBattery")  77:           Case FALSE  78:                Set objWMIInstances = objWMIServices.InstancesOf ("Win32_Battery")  79:    End Select  ..:  82:    If objWMIInstances.Count Then  83:       For Each objWMIInstance In objWMIInstances  84:           DisplayFormattedProperty objWMIInstance, _  85:                                    "Availability", _  86:                                    DeviceAvailability (objWMIInstance.Availability), _  87:                                    Null  88:  89:           If boolPortableBattery = False Then  90:              DisplayFormattedProperty objWMIInstance, _  91:                                       "Recharge time (min)", _  92:                                       "BatteryRechargeTime", _  93:                                       Null  94:           End If  95:  96:           DisplayFormattedProperty objWMIInstance, _  97:                                    "Battery status", _  98:                                    BatteryStatus (objWMIInstance.BatteryStatus), _  99:                                    Null 100: 101:           If boolPortableBattery = True Then 102:              DisplayFormattedProperty objWMIInstance, _ 103:                                       "Capacity multiplier", _ 104:                                       "CapacityMultiplier", _ 105:                                       Null 106:           End If 107: 108:           DisplayFormattedProperty objWMIInstance, _ 109:                                       "Chemistry", _ 110:                                       BatteryChemistry (objWMIInstance.Chemistry), _ 111:                                       Null ...: 148:           DisplayFormattedProperty objWMIInstance, _ 149:                                    "Estimated run-time (min)", _ 150:                                    "EstimatedRunTime", _ 151:                                    Null 152: 153:           If boolPortableBattery = False Then 154:              DisplayFormattedProperty objWMIInstance, _ 155:                                       "Expected battery life", _ 156:                                       "ExpectedBatteryLife", _ 157:                                       Null 158:           End If 159: 160:           DisplayFormattedProperty objWMIInstance, _ 161:                                    "Expected life", _ 162:                                    "ExpectedLife", _ 163:                                    Null ...: 177:           If boolPortableBattery = True Then 178:              DisplayFormattedProperty objWMIInstance, _ 179:                                       "Location", _ 180:                                       "Location", _ 181:                                       Null ...: 190:              DisplayFormattedProperty objWMIInstance, _ 191:                                       "Max. battery error", _ 192:                                       "MaxBatteryError", _ 193:                                       Null 194:           End If 195: 196:           DisplayFormattedProperty objWMIInstance, _ 197:                                    "Max. recharge time (min)", _ 198:                                    "MaxRechargeTime", _ 199:                                    Null ...: 224:           DisplayFormattedProperty objWMIInstance, _ 225:                                    "Time to fullcharge (min)", _ 226:                                    "TimeToFullCharge", _ 227:                                    Null 228:       Next 229:    Else 230:       WScript.Echo "No information available." 231:    End If ...: 236:    ]]> 237:    </script> 238:  </job> 239:</package> 

end example

The script retrieves information about the battery and lists its properties. Besides listing the various properties, the script uses some external functions to convert the information to a suitable display format (lines 20 through 26). If specific information related to a laptop battery must be retrieved, the script accepts the /Portable+ switch (lines 14, 55, and 56).

Once executed, the script displays the following information:

  1:    C:\>GetBatteryInformation.wsf /Machine:MyPortable.LissWare.Net  2:    Microsoft (R) Windows Script Host Version 5.6  3:    Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  4:  5:    Availability: ............................ Running/Full Power  6:    Battery status: .......................... Fully Charged  7:    Chemistry: ............................... Lithium-ion  8:    Description: ............................. Portable Battery  9:    Design capacity (milliwatt-hours): ....... 2700 10:    Design voltage (millivolts): ............. 14400 11:    *Device ID: .............................. Internal Battery 12:    Estimated charge remaining (%): .......... 100 13:    Status: .................................. OK 

If executed with a laptop, the script displays the following information:

  1:    C:\>GetBatteryInformation.wsf /Machine:MyPortable.LissWare.Net /Portable+  2:    Microsoft (R) Windows Script Host Version 5.6  3:    Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  4:  5:    Availability: ............................ Running/Full Power  6:    Battery status: .......................... Fully Charged  7:    Capacity multiplier: ..................... 1  8:    Chemistry: ............................... Lithium-ion  9:    Description: ............................. Portable Battery 10:    Design capacity (milliwatt-hours): ....... 2700 11:    Design voltage (millivolts): ............. 14400 12:    *Device ID: .............................. Internal Battery 13:    Estimated charge remaining (%): .......... 100 14:    Location: ................................ Left Hand Side 15:    Manufacturer: ............................ Compaq 16:    Manufacture date: ........................ 20001202010000.000000+060 17:    Max. battery error: ...................... 0 18:    Status: .................................. OK 

2.3.6 Modem device classes

The classes under this category represent the services and the characteristics of a Plain Old Telephone Service (POTS). This includes the plain old telephone modem devices with the associated serial port (see Figure 2.4).

click to expand
Figure 2.4: The Win32_POTSModem class associations.

The classes available in this category are listed in Table 2.9.

Table 2.9: The Telephony Classes

Name

Type

Description

Win32_POTSModem

Dynamic

Represents the services and characteristics of a Plain Old Telephone Service (POTS) modem on a Windows system.

Win32_POTSModemToSerialPort

Association

Relates a modem and the serial port the modem uses.

Instead of simply listing the properties of the Win32_POTSModem class line by line (as in Sample 2.14), we optimize the properties enumeration. The purpose is to make the coding shorter and the logic more generic while maintaining the capability to display some properties in a converted format. Sample 2.15 contains the script code listing.

Sample 2.15: Retrieving modem information

start example

   1:<?xml version="1.0"?>   .:   8:<package>   9:  <job>  ..:  13:    <runtime>  14:      <named name="Machine" helpstring="determine the WMI system to connect to.                       (default=LocalHost)" required="false" type="string"/>  15:      <named name="User" helpstring="determine the UserID to perform the remote connection.                       (default=none)" required="false" type="string"/>  16:      <named name="Password" helpstring="determine the password to perform the remote                       connection. (default=none)" required="false" type="string"/>  17:    </runtime>  18:  19:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeDeviceAvailabilityFunction.vbs" />  20:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeCfgManErrCodeFunction.vbs" />  21:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeStatusInfoFunction.vbs" />  22:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodePwrManCapabilitiesFunction.vbs" />  23:  24:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\ConvertArrayInOneStringFunction.vbs" />  25:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DisplayFormattedPropertyFunction.vbs" />  26:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\TinyErrorHandler.vbs" />  27:  28:    <object prog  reference="true"/>  29:    <object prog  />  30:  31:    <script language="VBscript">  32:    <![CDATA[  ..:  36:    Const cComputerName = "LocalHost"  37:    Const cWMINameSpace = "root/cimv2"  38:    Const cWMIPOTSModemClass = "Win32_POTSModem"  ..:  51:    ' --------------------------------------------------------------------------------  52:    ' Parse the command line parameters  53:    strUserID = WScript.Arguments.Named("User")  54:    If Len(strUserID) = 0 Then strUserID = ""  55:  56:    strPassword = WScript.Arguments.Named("Password")  57:    If Len(strPassword) = 0 Then strPassword = ""  58:  59:    strComputerName = WScript.Arguments.Named("Machine")  60:    If Len(strComputerName) = 0 Then strComputerName = cComputerName  61:  62:    objWMILocator.Security_.AuthenticationLevel = wbemAuthenticationLevelDefault  63:    objWMILocator.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate  64:  65:    Set objWMIServices = objWMILocator.ConnectServer(strComputerName, cWMINameSpace, _  66:    strUserID, strPassword)  ..:  69:    Set objWMIInstances = objWMIServices.InstancesOf (cWMIPOTSModemClass)  ..:  72:    If objWMIInstances.Count Then  73:       For Each objWMIInstance In objWMIInstances  74:           Set objWMIPropertySet = objWMIInstance.Properties_  75:           For Each objWMIProperty In objWMIPropertySet  76:               Select Case objWMIProperty.Name  77:                      Case "Availability"  78:                           DisplayFormattedProperty objWMIInstance, _  79:                              objWMIProperty.Name, _  80:                              DeviceAvailability (objWMIInstance.Availability), _  81:                              Null  82:                      Case "ConfigManagerErrorCode"  83:                           DisplayFormattedProperty objWMIInstance, _  84:                               objWMIProperty.Name, _  85:                               CfgManErrCode (objWMIInstance.ConfigManagerErrorCode), _  86:                                                    Null  87:                      Case "ConfigManagerUserConfig"  88:                           DisplayFormattedProperty objWMIInstance, _  89:                               objWMIProperty.Name, _  90:                               UCase (objWMIInstance.ConfigManagerUserConfig), _  91:                               Null  92:                      Case "PowerManagementCapabilities"  93:                           DisplayFormattedProperty objWMIInstance, _  94:                              objWMIProperty.Name, _  95:                              PwrManCapabilities (objWMIInstance.PowerMan...abilities), _  96:                              Null  97:                      Case "StatusInfo"  98:                           DisplayFormattedProperty objWMIInstance, _  99:                              objWMIProperty.Name, _ 100:                              StatusInfo (objWMIInstance.StatusInfo), _ 101:                              Null 102:                      Case "DCB" 103:                           DisplayFormattedProperty objWMIInstance, _ 104:                              objWMIProperty.Name, _ 105:                              ConvertArrayInOneString (objWMIInstance.DCB, ","), _ 106:                              Null 107:                      Case "Default" 108:                           DisplayFormattedProperty objWMIInstance, _ 109:                              objWMIProperty.Name, _ 110:                              ConvertArrayInOneString (objWMIInstance.Default, ","), _ 111:                              Null 112:                      Case "Properties" 113:                           DisplayFormattedProperty objWMIInstance, _ 114:                              objWMIProperty.Name, _ 115:                              ConvertArrayInOneString (objWMIInstance.Properties, ","), _ 116:                              Null 117:                      Case "CreationClassName" 118: 119:                      Case "SystemCreationClassName" 120: 121:                      Case "SystemName" 122: 123:                      Case "Caption" 124: 125:                      Case "Name" 126: 127:                      Case Else 128:                           DisplayFormattedProperty objWMIInstance, _ 129:                              objWMIProperty.Name, _ 130:                              objWMIProperty.Name, _ 131:                              Null 132:               End Select 133:           Next 134:           Set objWMIPropertySet = Nothing 135: 136:           Set objWMIResourceInstances = objWMIServices.ExecQuery _ 137:                                              ("Associators of {" & cWMIPOTSModemClass & "='" & 138:                                              objWMIInstance.DeviceID & _ 139:                                              "'} Where AssocClass=Win32_AllocatedResource") 140: 141:           If objWMIResourceInstances.Count Then 142:              WScript.Echo 143:              For Each objWMIResourceInstance In objWMIResourceInstances 144:                  Select Case objWMIResourceInstance.Path_.Class 145:                         Case "Win32_IRQResource" 146:                              DisplayFormattedProperty objWMIResourceInstance, _ 147:                                  "IRQ resource", _ 148:                                  "IRQNumber", _ 149:                                  Null 150:                         Case "Win32_DMAChannel" 151:                              DisplayFormattedProperty objWMIResourceInstance, _ 152:                                  "DMA channel", _ 153:                                  "DMAChannel", _ 154:                                  Null 155:                         Case "Win32_PortResource" 156:                              DisplayFormattedProperty objWMIResourceInstance, _ 157:                                  "I/O Port", _ 158:                                  "Caption", _ 159:                                  Null 160:                         Case "Win32_DeviceMemoryAddress" 161:                              DisplayFormattedProperty objWMIResourceInstance, _ 162:                                  "Memory address", _ 163:                                  "Caption", _ 164:                                  Null 165:                  End Select 166:              Next 167:           End If 168:           WScript.Echo 169:       Next 170:    Else 171:       WScript.Echo "No information available." 172:    End If ...: 177:    ]]> 178:    </script> 179:  </job> 180:</package> 

end example

As usual, the script starts by defining and parsing the command-line parameters (lines 13 through 17 and 53 through 60). Once the WMI connection is established (lines 65 and 66), the script retrieves the instances of the Win32_POTSModem class (line 69). Next, and this where the new logic starts, instead of coding the property list one by one, the script enumerates all properties available from the instance (lines 75 through 133). The peculiarity is in the Select Case statement (lines 76 through 132), where the property name is tested. If the property must be displayed with a specific label, format, or converted value, or if the property must be skipped, the Select Case statement evaluates the property name and proceeds accordingly. Lines 77 through 116 display the properties that must be displayed with a specific label, format, or converted value, while lines 117 through 126 skip the properties. The default Select Case statement displays the property with its property name (lines 128 through 131). As a result, the following output is obtained when examining a Compaq Armada M700 internal modem device:

  1:    C:\>GetPOTSModemInformation.wsf /Machine:MyPortable.LissWare.Net  2:    Microsoft (R) Windows Script Host Version 5.6  3:    Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  4:  5:    AttachedTo: .............................. COM4  6:    BlindOff: ................................ X4  7:    BlindOn: ................................. X3  8:    CompressionOff: .......................... %C0  9:    CompressionOn: ........................... %C1 10:    ConfigManagerErrorCode: .................. This device is working properly. 11:    ConfigManagerUserConfig: ................. FALSE 12:    ConfigurationDialog: ..................... modemui.dll 13:    CountrySelected: ......................... Belgium 14:    DCB: ..................................... 28,0,0,0,0,194,1,0,21,32,0,0,0,0 15:    Default: ................................. 60,0,0,0,15,0,0,0,2,0 16:    Description: ............................. Compaq 56K (V.90) Mini PCI 17:    *DeviceID: ............................... PCI\VEN_11C1&DEV_04&SUBSYS_2086&REV_00\3&601&0&49 18:    DeviceType: .............................. Internal Modem 19:    DriverDate: .............................. 20000301******.******+*** 20:    ErrorControlForced: ...................... \N4 21:    ErrorControlOff: ......................... \N1 22:    ErrorControlOn: .......................... \N3 23:    FlowControlHard: ......................... &K3 24:    FlowControlOff: .......................... &K0 25:    FlowControlSoft: ......................... &K4 26:    InactivityScale: ......................... "3c000000" 27:    InactivityTimeout: ....................... 0 28:    Index: ................................... 0 29:    MaxBaudRateToPhone: ...................... 56000 30:    MaxBaudRateToSerialPort: ................. 115200 31:    Model: ................................... Compaq 56K (V.90) Mini PCI 32:    ModemInfPath: ............................ oem5.inf 33:    ModemInfSection: ......................... Modem_PCI_DF 34:    ModulationBell: .......................... B1B16B2 35:    ModulationCCITT: ......................... B0B15B2 36:    PNPDeviceID: ............................. PCI\VEN_11C1&DEV_04&SUBSYS_2086&REV_00\3&601&0&49 37:    PortSubClass: ............................ "02" 38:    PowerManagementSupported: ................ FALSE 39:    Prefix: .................................. AT 40:    Properties: .............................. 192,1,0,0,255,0,0,0,255,0,0,0,7,0,0,0 41:    ProviderName: ............................ Lucent 42:    Pulse: ................................... P 43:    Reset: ................................... AT&F<cr> 44:    ResponsesKeyName: ........................ Compaq 56K (V.90) Mini PCI::Lucent::Lucent 45:    SpeakerModeDial: ......................... M1 46:    SpeakerModeOff: .......................... M0 47:    SpeakerModeOn: ........................... M2 48:    SpeakerModeSetup: ........................ M3 49:    SpeakerVolumeHigh: ....................... L3 50:    SpeakerVolumeLow: ........................ L0 51:    SpeakerVolumeMed: ........................ L2 52:    Status: .................................. OK 53:    StatusInfo: .............................. Enabled 54:    StringFormat: ............................ UNICODE string format 55:    Terminator: .............................. <cr> 56:    Tone: .................................... T 57: 58:    *IRQ resource: ........................... 11 59:    Memory address: .......................... 0x41300000-0x41300FFF 60:    I/O Port: ................................ 0x00003440-0x00003447 

Since some properties contain arrays (DCB at line 103, Default at line 107, and Properties at line 112), we see an application of ConvertArrayInString() function. This function is the complementary function of the ConvertStringInArray() function developed for Sample 2.12 ("Configuring a network adapter").

Apart from this new way of enumerating and displaying the instance properties, there is no further commenting required regarding the POTS classes and this script sample.

2.3.7 Printing device classes

The printing category classes represent printers, printer configurations, and print jobs. The classes in this category are listed in Table 2.10.

Table 2.10: The Printing Device Classes

Name

Type

Description

Win32_Printer

Dynamic

Represents a device connected to a Windows computer system that is capable of reproducing a visual image on a medium.

Win32_PrinterConfiguration

Dynamic

Defines the configuration for a printer device.

Win32_PrinterController

Dynamic

Relates a printer and the local device to which the printer is connected.

Win32_PrinterDriver

Dynamic

Represents the drivers for a Win32 Printer Dynamic.

Win32_PrintJob

Dynamic

Represents a print job generated by a Windows application.

Win32_TCPIPPrinterPort

Dynamic

The Win32_TCPIPPrinterPort class represents a TCP//IP service access point, for example, a TCP/IP printer port.

Win32_DriverForDevice

Association

Relates a printer to a printer driver.

Win32_PrinterDriverDII

Association

Relates a local printer and its driver file (not the driver itself).

Win32_PrinterSetting

Association

Relates a printer and its configuration settings.

Instead of simply retrieving information about printers with their print jobs, it would be useful to perform some specific tasks. We should note that the Win32_Printer class has some interesting associations to exploit when searching for printer information (see Figure 2.5).

click to expand
Figure 2.5: The Win32_Printer class associations.

To configure printers, each task corresponds to a WMI class usage. The tasks and their related WMI classes are as follows:

  • Adding a printer driver: requires the Win32_PrinterDriver class usage with its AddPrinterDriver method.

  • Adding a new printer: requires the creation of a new instance with the Win32_Printer class.

  • Creating a new printer connection: requires the Win32_Printer class usage with its AddPrinterConnection method.

  • Removing a printer: requires the deletion of the Win32_Printer instance representing the printer.

  • Removing a printer driver: requires the deletion of the Win32_ PrinterDriver instance representing the printer driver.

  • Pausing and resuming a printer: requires the Win32_Printer class usage with its Pause method or Resume method.

  • Pausing and resuming a job: requires the Win32_PrinterJob class usage with its Pause method or Resume method.

  • Canceling a job: requires the deletion of the Win32_PrinterJob instance representing the print job.

  • Canceling all jobs: requires the Win32_Printer class usage with its CancelAllJobs method.

To support these operations, the script exposes a lot of command-line parameters. The command-line parameters displayed by the script are as follows:

 C:\>WMIPrinters.Wsf Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2001. All rights reserved. Usage: WMIPrinters.wsf [/List:Value] [/AddPrinterConnection[+|-]] [/AddPrinter[+|-]]                        [/DelPrinter[+|-]] [/AddPrinterDriver[+|-]] [/DelPrinterDriver[+|-]]                        [/PrinterName[+|-]] [/PrintTestPage[+|-]] [/CancelAllJobs[+|-]]                        [/PausePrinter[+|-]] [/ResumePrinter[+|-]] [/RenamePrinter[+|-]]                        [/SetDefaultPrinter[+|-]] [/PauseJob[+|-]] [/ResumeJob[+|-]]                        [/CancelJob[+|-]] [/Machine:value] [/User:value] [/Password:value] Options: List                 : List the existing printers or jobs.                        Only [Drivers], [Printers] or [Jobs] are accepted. AddPrinterConnection : Add a printer connection. AddPrinter           : Add a printer. DelPrinter           : Remove a printer or a printer connection. AddPrinterDriver     : Add a printer driver. DelPrinterDriver     : Remove a printer driver. PrinterName          : Printer name to work with. PrintTestPage        : Print a test page. CancelAllJobs        : Cancel all jobs in the printer. PausePrinter         : Pause the printer. ResumePrinter        : Resume the printer. RenamePrinter        : Rename the printer. SetDefaultPrinter    : Set the printer as the default printer. PauseJob             : Pause a specific job. ResumeJob            : Resume a specific job. CancelJob            : Cancel a specific job. Machine              : Determine the WMI system to connect to. (default=LocalHost) User                 : Determine the UserID to perform the remote connection. (default=none) Password             : Determine the password to perform the remote connection. (default=none) Examples:       WMIPrinters.Wsf /List:Drivers       WMIPrinters.Wsf /List:Printers       WMIPrinters.Wsf /List:Jobs       WMIPrinters.Wsf /PrinterDriverName:"HP LaserJet 5" /AddPrinterDriver+       WMIPrinters.Wsf /PrinterDriverName:"HP LaserJet 5" /DelPrinterDriver+       WMIPrinters.Wsf /PrinterName:"My Printer" /PrinterDriverName:"HP LaserJet 5" /AddPrinter+       WMIPrinters.Wsf /PrinterName:"My Printer" /DelPrinter+       WMIPrinters.Wsf /PrinterName:\\MyServer\MyPrinter /AddPrinterConnection+       WMIPrinters.Wsf /PrinterName:\\MyServer\MyPrinter /DelPrinter+       WMIPrinters.Wsf /PrinterName:"MyPrinter" /PrintTestPage+       WMIPrinters.Wsf /PrinterName:\\MyServer\MyPrinter /CancelAllJobs+       WMIPrinters.Wsf /PrinterName:"MyPrinter" /PausePrinter+       WMIPrinters.Wsf /PrinterName:"MyPrinter" /ResumePrinter+       WMIPrinters.Wsf /PrinterName:\\MyServer\MyPrinter /SetDefaultPrinter+       WMIPrinters.Wsf /PrinterName:\\MyServer\MyPrinter /RenamePrinter:NewPrinterName       WMIPrinters.Wsf /PrinterName:\\MyServer\MyPrinter /PauseJob:MyDocument       WMIPrinters.Wsf /PrinterName:\\MyServer\MyPrinter /ResumeJob:MyDocument       WMIPrinters.Wsf /PrinterName:\\MyServer\MyPrinter /CancelJob:MyDocument 

The script code is presented in Samples 2.16 through 2.21. Sample 2.16 starts with the command-line parameters definition (skipped lines 13 through 64, giving the previous result) and parsing (lines 162 through 252). This first part of the script also contains some constant declarations. These constants are used later in the script.

Sample 2.16: Managing the printer drivers, the printers, and their related print jobs (Part I)

start example

   1:<?xml version="1.0"?>   .:   8:<package>   9:  <job>  ..:  13:    <runtime>  ..:  64:    </runtime>  ..:  72:    <script language="VBScript" src="/books/2/679/1/html/2/..\Functions\ConvertArrayInStringFunction.vbs" />  73:    <script language="VBScript" src="/books/2/679/1/html/2/..\Functions\DisplayFormattedPropertyFunction.vbs" />  74:    <script language="VBScript" src="/books/2/679/1/html/2/..\Functions\TinyErrorHandler.vbs" />  75:  76:    <object prog  reference="true"/>  77:    <object prog  />  78:  79:    <script language="VBscript">  80:    <![CDATA[  ..:  84:    ' -----------------------------------------------------------------------------------------  85:    Const cComputerName = "LocalHost"  86:    Const cWMINameSpace = "root/cimv2"  87:  88:    Const cWMIPrinterDriverClass = "Win32_PrinterDriver"  89:    Const cWMIPrinterClass = "Win32_Printer"  90:    Const cWMIJobClass = "Win32_PrintJob"  91:  92:    Const cPortName = "LPT1:"  93:    Const cAttributes = 2624  94:    Const cComment = ""  95:    Const cDefaultPriority = 0  96:    Const cDirect = False  97:    Const cDoCompleteFirst = True  98:    Const cEnableBIDI = True  99:    Const cEnableDevQueryPrint = False 100:    Const cHidden = False 101:    Const cKeepPrintedJobs = False 102:    Const cLocal = True 103:    Const cLocation = "" 104:    Const cNetwork = False 105:    Const cParameters = "" 106:    Const cPrintJobDataType = "RAW" 107:    Const cPrintProcessor = "WinPrint" 108:    Const cPriority = 1 109:    Const cPublished = False 110:    Const cQueued = False 111:    Const cRawOnly = True 112:    Const cSeparatorFile = "" 113:    Const cShared = False 114:    Const cShareName = "" 115:    Const cStartTime = "********080000.000000+000" 116:    Const cUntilTime = "********200000.000000+000" 117:    Const cWorkOffline = False ...: 160:    ' -------------------------------------------------------------------------------- 161:    ' Parse the command line parameters 162:    If WScript.Arguments.Named.Count = 0 Then 163:       WScript.Arguments.ShowUsage() 164:       WScript.Quit 165:    End If 166: 167:    strList = UCase (WScript.Arguments.Named("List")) 168:    If Len (strList) Then 169:       Select Case strList 170:              Case "DRIVERS" 171: 172:              Case "PRINTERS" 173: 174:              Case "JOBS" 175: 176:              Case Else 177:                   WScript.Echo "Invalid List argument. Only [Drivers], ... 178:                   WScript.Arguments.ShowUsage() 179:                   WScript.Quit 180:       End Select 181:    End If 182: 183:    boolAddPrnDriver = WScript.Arguments.Named("AddPrinterDriver") 184:    If Len(boolAddPrnDriver) = 0 Then boolAddPrnDriver = False 185: 186:    boolDelPrnDriver = WScript.Arguments.Named("DelPrinterDriver") 187:    If Len(boolDelPrnDriver) = 0 Then boolDelPrnDriver = False 188: 189:    boolAddPrn = WScript.Arguments.Named("AddPrinter") 190:    If Len(boolAddPrn) = 0 Then boolAddPrn = False 191: 192:    If boolAddPrnDriver Or boolDelPrnDriver Then 193:       strPrinterDriverName = WScript.Arguments.Named("PrinterDriverName") 194:       If Len (strPrinterDriverName) = 0 Then 195:          WScript.Echo "Invalid printer driver name." & vbCRLF 196:          WScript.Arguments.ShowUsage() 197:          WScript.Quit 198:       End If 199:    ElseIf boolAddPrn Then 200:       strPrinterDriverName = WScript.Arguments.Named("PrinterDriverName") 201:       strPrinterName = WScript.Arguments.Named("PrinterName") 202:       If Len (strPrinterDriverName) = 0 Or Len (strPrinterName) = 0 Then 203:          WScript.Echo "Invalid printer name or print driver name." & vbCRLF 204:          WScript.Arguments.ShowUsage() 205:          WScript.Quit 206:       End If 207:    Else 208:       strPrinterName = WScript.Arguments.Named("PrinterName") 209:       If Len (strPrinterName) = 0 And Len (strList) = 0 Then 210:          WScript.Echo "Invalid printer name." & vbCRLF 211:          WScript.Arguments.ShowUsage() 212:          WScript.Quit 213:       End If 214:    End If 215: 216:    boolAddPrnConnection = WScript.Arguments.Named("AddPrinterConnection") 217:    If Len(boolAddPrnConnection) = 0 Then boolAddPrnConnection = False ...: ...: ...: 243:    strCancelJob = WScript.Arguments.Named("CancelJob") 244: 245:    strUserID = WScript.Arguments.Named("User") 246:    If Len(strUserID) = 0 Then strUserID = "" 247: 248:    strPassword = WScript.Arguments.Named("Password") 249:    If Len(strPassword) = 0 Then strPassword = "" 250: 251:    strComputerName = WScript.Arguments.Named("Machine") 252:    If Len(strComputerName) = 0 Then strComputerName = cComputerName 253: 254:    objWMILocator.Security_.AuthenticationLevel = wbemAuthenticationLevelDefault 255:    objWMILocator.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate 256: 257:    Set objWMIServices = objWMILocator.ConnectServer(strComputerName, cWMINameSpace, _ ...: 260: ...: ...: ...: 

end example

The command-line parsing is quite complex, because some switches are only required for some specific actions. For instance, when /List:<value> switch is used, no other command-line parameter is needed. However, when /AddPrinter+ switch is used, some more command-line parameters are required. For instance, to install a printer driver, create a printer using the installed printer driver, make it the default printer, and print one test page, the following command lines must be used:

 WMIPrinters.Wsf /PrinterDriverName:"HP LaserJet 5" /AddPrinterDriver+ WMIPrinters.Wsf /PrinterName:"My Printer" /PrinterDriverName:"HP LaserJet 5" /AddPrinter+ WMIPrinters.Wsf /PrinterName:\\MyServer\MyPrinter /SetDefaultPrinter+ WMIPrinters.Wsf /PrinterName:\\MyServer\MyPrinter /PrintTestPage+ 

Because the script performs many different tasks with the printers, it is divided into different sections. Each section is responsible for a specific action. Sample 2.17 shows the code to retrieve information about the installed printer drivers, printers, and jobs in the printer queue.

Sample 2.17: Viewing printer drivers, printers, and job information (Part II)

start example

 ...: ...: ...: 260: 261:    ' LIST Printers or Jobs ------------------------------------------------------------------- 262:    If Len (strList) Then 263: 264:       If strList = "DRIVERS" Then 265:          Set objWMIInstances = objWMIServices.InstancesOf (cWMIPrinterDriverClass) 266:          If Err.Number Then ErrorHandler (Err) 267:          varTemp = "- Job " 268:       End If 269: 270:       If strList = "PRINTERS" Then 271:          Set objWMIInstances = objWMIServices.InstancesOf (cWMIPrinterClass) 272:          If Err.Number Then ErrorHandler (Err) 273:          varTemp = "- Printer " 274:       End If 275: 276:       If strList = "JOBS" Then 277:          Set objWMIInstances = objWMIServices.InstancesOf (cWMIJobClass) 278:          If Err.Number Then ErrorHandler (Err) 279:          varTemp = "- Job " 280:       End If 281: 282:       If objWMIInstances.Count Then 283:          For Each objWMIInstance in objWMIInstances 284:              If strList = "DRIVERS" Then 285:                 WScript.Echo "- Driver '" & objWMIInstance.Name & "' " & _ 286:                              String (60, "-") 287:              End If 288:              If strList = "PRINTERS" Then 289:                 WScript.Echo "- Printer '" & objWMIInstance.Name & "' " & _ 290:                              String (60, "-") 291:              End If 292:              If strList = "JOBS" Then 293:                 WScript.Echo "- Job '" & Ucase (objWMIInstance.Name) & _ 294:                              "' (" & objWMIInstance.Document & _ 295:                              ") " & String (60, "-") 296:              End If 297: 298:              Set objWMIPropertySet = objWMIInstance.Properties_ 299:              For Each objWMIProperty In objWMIPropertySet 300:                  Select Case objWMIProperty.Name 301:                         Case "CreationClassName" 302: 303:                         Case "SystemCreationClassName" ...: ...: ...: 340:                         Case Else 341:                              DisplayFormattedProperty objWMIInstance, _ 342:                                                       objWMIProperty.Name, _ 343:                                                       objWMIProperty.Name, _ 344:                                                       Null 345:                  End Select 346:              Next ...: 349:              WScript.Echo 350:          Next 351:       Else 352:          WScript.Echo "No information available." 353:       End If ...: 357:    End If 358: ...: ...: ...: 

end example

To retrieve information about the printer drivers, printers, and print jobs, three classes are used:

  • Win32_PrinterDrive class to display information about the installed printer drivers (lines 264 through 268).

  • Win32_Printer class to display information about the printers (lines 270 through 274).

  • Win32_PrinterJob class to display information about the printer jobs (lines 276 through 280).

Because a collection of instances for the class is created, the script enumerates the collection and displays the properties with the help of the DisplayFormattedProperty() function (lines 283 through 350). Based on the instance examined, a message specific to the printer drivers, printers, or print jobs is created (lines 284 through 296). For instance, the following command-line parameters display information about the printers:

  1:   C:\>WMIPrinters.Wsf /List:Printers  2:   Microsoft (R) Windows Script Host Version 5.6  3:   Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  4:  5:   - Printer 'My Printer' ------------------------------------------------------------  6:   Attributes: .............................. 6724  7:   AveragePagesPerMinute: ................... 0  8:   Capabilities: ............................ 4  9:                                              2 10:                                              3 11:                                              5 12:   CapabilityDescriptions: .................. Copies 13:                                              Color 14:                                              Duplex 15:                                              Collate 16:   Caption: ................................. My Printer 17:   Default: ................................. TRUE 18:   DefaultPriority: ......................... 0 19:   DetectedErrorState: ...................... 2 20:   *DeviceID: ............................... My Printer 21:   Direct: .................................. FALSE 22:   DoCompleteFirst: ......................... TRUE 23:   DriverName: .............................. HP LaserJet 5 24:   EnableBIDI: .............................. TRUE 25:   EnableDevQueryPrint: ..................... FALSE 26:   ExtendedDetectedErrorState: .............. 2 27:   ExtendedPrinterStatus: ................... 8 28:   Hidden: .................................. FALSE 29:   HorizontalResolution: .................... 600 30:   JobCountSinceLastReset: .................. 0 31:   KeepPrintedJobs: ......................... FALSE 32:   Local: ................................... TRUE 33:   Name: .................................... My Printer 34:   Network: ................................. FALSE 35:   PaperSizesSupported: ..................... 7,8,1,22,23,11,1,1,1,1 36:   PortName: ................................ LPT1: 37:   PrinterPaperNames: ....................... Letter 38:                                              Legal 39:                                              Executive 40:                                              A4 41:                                              A5 42:                                              Envelope #10 43:                                              Envelope DL 44:                                              Envelope C5 45:                                              Envelope B5 46:                                              Envelope Monarch 47:   PrinterState: ............................ 1 48:   PrinterStatus: ........................... Other 49:   PrintJobDataType: ........................ RAW 50:   PrintProcessor: .......................... WinPrint 51:   Priority: ................................ 1 52:   Published: ............................... FALSE 53:   Queued: .................................. FALSE 54:   RawOnly: ................................. TRUE 55:   Shared: .................................. FALSE 56:   SpoolEnabled: ............................ TRUE 57:   StartTime: ............................... ********080000.000000+000 58:   Status: .................................. OK 59:   SystemName: .............................. XP-DPEN6400 60:   UntilTime: ............................... ********200000.000000+000 61:   VerticalResolution: ...................... 600 62:   WorkOffline: ............................. FALSE 

It is important to note that in this set of properties, some of them are modifiable. For instance, the StartTime and the UntilTime properties of the Win32_Printer class use a DMTF date/time value that is easily modifiable. In this sample script, most of these property values are defined as constants in the beginning of the script (lines 92 through 117). These constants are used in the next segment of code to create a new printer (see Sample 2.18).

Sample 2.18: Adding printers and printer connections (Part III)

start example

 ...: ...: ...: 358: 359:    ' ADD PRINTER CONNECTION ------------------------------------------------------------------ 360:    If boolAddPrnConnection Then 361:       Set objWMIClass = objWMIServices.Get (cWMIPrinterClass) 362:       If Err.Number Then ErrorHandler (Err) 363: 364:       intRC = objWMIClass.AddPrinterConnection (strPrinterName) ...: 367:       WScript.Echo "Printer connection '" & strPrinterName & "' added (" & intRC & ")." 368: 369:       Set objWMIClass = Nothing 370: 371:       End If 372: 373:       ' ADD PRINTER -------------------------------------------------------------------- 374:       If boolAddPrn Then 375:          Set objWMIClass = objWMIServices.Get (cWMIPrinterClass) ...: 378:       Set objWMIInstance = objWMIClass.SpawnInstance_ 379: 380:       objWMIInstance.DeviceID = strPrinterName 381:       objWMIInstance.DriverName = strPrinterDriverName 382: 383:       objWMIInstance.PortName = cPortName 384:       objWMIInstance.Comment = cComment 385:       objWMIInstance.DefaultPriority = cDefaultPriority 386:       objWMIInstance.Direct = cDirect 387:       objWMIInstance.DoCompleteFirst = cDoCompleteFirst 388:       objWMIInstance.EnableBIDI = cEnableBIDI 389:       objWMIInstance.EnableDevQueryPrint = cEnableDevQueryPrint 390:       objWMIInstance.Hidden = cHidden 391:       objWMIInstance.KeepPrintedJobs = cKeepPrintedJobs 392:       objWMIInstance.Local = cLocal 393:       objWMIInstance.Location = cLocation 394:       objWMIInstance.Network = cNetwork 395:       objWMIInstance.Parameters = cParameters 396:       objWMIInstance.PrintJobDataType = cPrintJobDataType 397:       objWMIInstance.PrintProcessor = cPrintProcessor 398:       objWMIInstance.Priority = cPriority 399:       objWMIInstance.Published = cPublished 400:       objWMIInstance.Queued = cQueued 401:       objWMIInstance.RawOnly = cRawOnly 402:       objWMIInstance.SeparatorFile = cSeparatorFile 403:       objWMIInstance.Shared = cShared 404:       objWMIInstance.ShareName = cShareName 405:       objWMIInstance.StartTime = cStartTime 406:       objWMIInstance.UntilTime = cUntilTime 407:       objWMIInstance.WorkOffline = cWorkOffline 408: 409:       objWMIInstance.Put_ (wbemChangeFlagCreateOrUpdate Or wbemFlagReturnWhenComplete) ...: 412:       WScript.Echo "Printer connection '" & strPrinterName & "' added." ...: 416:    End If 417: ...: ...: ...: 

end example

To create a new printer connection (lines 360 through 371), the script uses a method that is defined as a static method (line 364). In Sample 2.12 ("Configuring a network adapter"), we saw the difference between a static method and a dynamic method. We saw that the static method must be used from a class instance. So, to create a printer connection, Sample 2.18 creates an instance of the Win32_Printer class (line 361) and invokes the AddPrinterConnection method (line 364). The method requires one parameter, the printer name of the printer to install (i.e., "My Printer"), or the share name of the network printer to connect to (i.e., \\MyServer\MyPrinterShare).

To create a new printer (lines 374 through 416), the script spawns a new instance of the Win32_Printer class (lines 375 through 378). Next, it initializes the miscellaneous values defining the new printer (lines 380 through 407). Once the values are assigned to the properties, the script invokes the Put_ method of the SWBemObject object (line 409). Two of these properties are assigned from the command-line parameters: These are the printer name and the printer driver name. All other properties come from constants defined in the script header (see Sample 2.16, lines 92 through 117). We proceed like this to minimize the number of parameters to specify from the command line. Moreover, the constants are set on a value that suits the requirement of a local printer. If needed, the script can be easily modified or extended to expose some more command-line parameters.

The next task supported by this WMI script sample is the deletion of an existing printer. The coding technique is presented in Sample 2.19, with some extra code to pause, resume, and print a test page. We also see that it is possible to rename a printer. All these tasks require an instance of the printer to be managed (lines 427 and 428). This is the reason why this piece of the code corresponds to many actions supported by WMI on a printer instance (lines 419 through 425).

Sample 2.19: Deleting, managing (test page, pause, resume, etc.) and renaming printers (Part IV)

start example

 ...: ...: ...: 417 418:    ' ---------------------------------------------------------------------------------------- 419:    If boolDelPrn Or _ 420:       boolTestPage Or _ 421:       boolCancelAllJobs Or _ 422:       boolPausePrinter Or _ 423:       boolResumePrinter Or _ 424:       boolSetDefaultPrinter Or _ 425:       Len (strRenamePrinter) Then 426: 427:       Set objWMIInstance = objWMIServices.Get (cWMIPrinterClass & "='" & _ 428:                                                    strPrinterName & "'") ...: 431:       ' DELETE PRINTER & PRINTER CONNECTION --------------------------------------------------- 432:       If boolDelPrn Then 433:          objWMIInstance.Delete_ 434:          If Err.Number Then ErrorHandler (Err) 435:          WScript.Echo "Printer '" & strPrinterName & "' deleted." 436:       End If 437: 438:      ' TEST PAGE ----------------------------------------------------------------------------- 439:       If boolTestPage Then 440:          intRC = objWMIInstance.PrintTestPage 441:          If Err.Number Then ErrorHandler (Err) 442:          WScript.Echo "Test page for printer '" & strPrinterName & _ 443:                       "' requested (" & intRC & ")." 444:       End If 445: 446:      ' CANCEL ALL JOBS ----------------------------------------------------------------------- 447:       If boolCancelAllJobs Then 448:          intRC = objWMIInstance.CancelAllJobs 449:          If Err.Number Then ErrorHandler (Err) 450:          WScript.Echo "All jobs for printer '" & strPrinterName & _ 451:                       "' cancelled (" & intRC & ")." 452:       End If 453: 454:       ' PAUSE PRINTER ------------------------------------------------------------------------- 455:       If boolPausePrinter Then 456:          intRC = objWMIInstance.Pause 457:          If Err.Number Then ErrorHandler (Err) 458:          WScript.Echo "Printer '" & strPrinterName & "' paused (" & intRC & ")." 459:       End If 460: 461:      ' RESUME PRINTER ------------------------------------------------------------------------ 462:       If boolResumePrinter Then 463:          intRC = objWMIInstance.Resume 464:          If Err.Number Then ErrorHandler (Err) 465:          WScript.Echo "Printer '" & strPrinterName & "' resumed (" & intRC & ")." 466:       End If 467: 468:      ' DEFAULT PRINTER ----------------------------------------------------------------------- 469:       If boolSetDefaultPrinter Then 470:          intRC = objWMIInstance.SetDefaultPrinter 471:          If Err.Number Then ErrorHandler (Err) 472:          WScript.Echo "Printer '" & strPrinterName & _ 473:                       "' set as default printer (" & intRC & ")." 474:       End If 475: 476:      ' RENAME PRINTER ------------------------------------------------------------------------ 477:       If Len (strRenamePrinter) Then 478:          intRC = objWMIInstance.RenamePrinter (strRenamePrinter) 479:          If Err.Number Then ErrorHandler (Err) 480:          WScript.Echo "Printer '" & strPrinterName & "' renamed to '" & _ 481:                       strRenamePrinter & "' (" & intRC & ")." 482:       End If ...: 485:    End If 486: ...: ...: ...: 

end example

Once the managed printer is instantiated (lines 427 and 428), based on the command-line parameters, the first possible action is the printer deletion. To do this, the script must simply delete the corresponding printer instance (line 433) by invoking the Delete_ method of the SWBemObject object. Note that this delete operation can remove an existing printer connection or delete a local printer.

The subsequent operations (lines 438 through 482) use the method instance that corresponds to the task to be performed. It is possible to send a test page (line 440), to cancel all jobs (line 448), to pause (line 456) and resume (line 463) the printer, set the printer as the default printer (line 470), and rename the printer (line 478). Note that to rename the printer a specific command-line parameter is required, which is the new printer name (i.e., /RenamePrinter:NewPrinterName).

To add and delete printer drivers, the technique is very similar to that used previously. However, the script must use the Win32_PrinterDrive class. The code is shown in Sample 2.20.

Sample 2.20: Adding and deleting printer drivers (Part V)

start example

 ...: ...: ...: 486: 487:    ' ADD PRINTER DRIVER ---------------------------------------------------------------------- 488:    If boolAddPrnDriver Then 489:       Set objWMIPrnDrvClass = objWMIServices.Get (cWMIPrinterDriverClass) ...: 492:       Set objWMIPrnDrvInstance = objWMIPrnDrvClass.SpawnInstance_ 493:       objWMIPrnDrvInstance.Name = strPrinterDriverName 494: 495:       Set objWMIClass = objWMIServices.Get (cWMIPrinterDriverClass) ...: 498:       intRC = objWMIClass.AddPrinterDriver (objWMIPrnDrvInstance) ...: 501:       WScript.Echo "Printer driver '" & strPrinterDriverName & "' added (" & intRC & ")." ...: 507:    End If 508: 509:    ' DELETE PRINTER DRIVER ------------------------------------------------------------------- 510:    If boolDelPrnDriver Then 511:       Set objWMIInstance = objWMIServices.Get (cWMIPrinterDriverClass & "='" & _ 512:                                                    strPrinterDriverName & "'") 513:       objWMIInstance.Delete_ 514:       If Err.Number Then ErrorHandler (Err) 515:       WScript.Echo "Printer driver '" & strPrinterDriverName & "' Cancelled." ...: 518:    End If 519: ...: ...: ...: 

end example

To add a new printer driver, the script must use a specific method (called AddPrinterDriver), which is defined as a static method of the Win32_PrinterDrivers class (lines 495 through 498). Because AddPrinterDriver method requires one parameter, which is an instance of the Win32_Printer driver to install, the script first creates a printer driver instance with the name given on the command line (lines 489 through 493). For instance:

 WMIPrinters.Wsf /PrinterDriverName:"HP LaserJet 5" /AddPrinterDriver+ 

To delete a printer driver, the following command line is used:

 WMIPrinters.Wsf /PrinterDriverName:"HP LaserJet 5" /DelPrinterDriver+ 

The deletion is performed from line 511 through 516 and consists of the deletion of the printer driver instance by invoking the Delete_ method of the SWBemObject object representing the printer driver.

The last type of task to be performed at the printer level is the print job management. WMI exposes the Win32_PrintJob class with some specific methods to manage the print jobs of a printer. This piece of code is shown in Sample 2.21.

Sample 2.21: Managing printer jobs (pause, resume, and delete) (Part VI)

start example

 ...: ...: ...: 519: 520:    ' PAUSE JOB ------------------------------------------------------------------------------- 521:    If Len (strPauseJob) Then 522:       Set objWMIInstance = objWMIServices.Get (cWMIJobClass & "='" & strPauseJob & "'") 523:       intRC = objWMIInstance.Pause 524:       WScript.Echo "Job '" & strPauseJob & "' paused (" & intRC & ")." 525:       Set objWMIInstance = Nothing 526:    End If 527: 528:    ' RESUME JOB ------------------------------------------------------------------------------ 529:    If Len (strResumeJob) Then 530:       Set objWMIInstance = objWMIServices.Get (cWMIJobClass & "='" & strResumeJob & "'") 531:       intRC = objWMIInstance.Resume 532:       WScript.Echo "Job '" & strResumeJob & "' Resumed (" & intRC & ")." 533:       Set objWMIInstance = Nothing 534:    End If 535: 536:    ' CANCEL JOB ------------------------------------------------------------------------------ 537:    If Len (strCancelJob) Then 538:       Set objWMIInstance = objWMIServices.Get (cWMIJobClass & "='" & strCancelJob & "'") 539:       objWMIInstance.Delete_ 540:       If Err.Number Then ErrorHandler (Err) 541:       WScript.Echo "Job '" & strCancelJob & "' Cancelled." 542:       Set objWMIInstance = Nothing 543:    End If ...: 547:    ]]> 548:    </script> 549:  </job> 550:</package> 

end example

The command-line parameters to manage print jobs require one parameter, which is the print job name itself. Since the print job name is not exactly the one visible from the user interface (an index is appended to the printer name), it is recommended that you use the /List:PrintJobs switch to display the print job name list. A sample output of the existing print jobs looks like this:

  1:   C:\>WMIPrinters.Wsf /List:Jobs  2:   Microsoft (R) Windows Script Host Version 5.6  3:   Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  4:  5:   - Job 'MY PRINTER, 3' (Microsoft Word - My Document.doc) -----------------------------------  6:   Caption: ................................. My Printer, 3  7:   DataType: ................................ RAW  8:   Description: ............................. My Printer, 3  9:   Document: ................................ Microsoft Word - My Document.doc 10:   DriverName: .............................. HP LaserJet 5 11:   ElapsedTime: ............................. 00000000000000.000000:000 12:   HostPrintQueue: .......................... \\XP-DPEN6400 13:   JobId: ................................... 3 14:   *Name: ................................... My Printer, 3 15:   Notify: .................................. Alain.Lissoir 16:   Owner: ................................... Alain.Lissoir 17:   PagesPrinted: ............................ 0 18:   PrintProcessor: .......................... WinPrint 19:   Priority: ................................ 1 20:   Size: .................................... 359 21:   StartTime: ............................... ********080000.000000+000 22:   Status: .................................. UNKNOWN 23:   StatusMask: .............................. 0 24:   TimeSubmitted: ........................... 01-11-2001 16:37:23 25:   TotalPages: .............................. 1 26:   UntilTime: ............................... ********200000.000000+000 

To delete this print job, the following command line must be used:

 C:\>WMIPrinters.Wsf /PrinterName:"My Printer" /CancelJob:"My Printer, 3" Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2001. All rights reserved. Job 'My Printer, 3' Cancelled. 

From a scripting point of view, the job deletion is nothing more than the deletion of the instance representing the print job (lines 537 through 543) by invoking the Delete_ method of the SWBemObject object.

2.3.8 Video and monitor classes

The video and monitor classes represent monitors, video cards, and their associated settings. The Microsoft classes in this category are listed in Table 2.11.

Table 2.11: The Video and Monitor Classes

Name

Type

Description

Win32_DesktopMonitor

Dynamic

Represents the type of monitor or display device attached to the computer system.

Win32_DisplayConfiguration

Dynamic

Represents configuration information for the display device on a Windows system. This class is obsolete. In place of this class, you should use the properties in the Win32_VideoController, Win32_DesktopMonitor, and CIM_VideoControllerResolution classes.

Win32_DisplayControllerConfiguration

Dynamic

Represents the video adapter configuration information of a Windows system. This class is obsolete. In place of this class, you should use the properties in the Win32_VideoController, Win32_DesktopMonitor, and CIM_VideoControllerResolution classes.

Win32_VideoConfiguration

Dynamic

This class has been eliminated from Windows XP and later; attempts to use it will generate a fatal error. In place of this class, you should use the properties contained in the Win32_VideoController, Win32_DesktopMonitor, and CIM_VideoControllerResolution dasses.

Win32_VideoController

Dynamic

Represents the capabilities and management capacity of the video controller on a Windows computer system.

Win32_VideoSettings

Association

Relates a video controller and video settings that can be applied to it.

The Win32_DisplayConfiguration, the Win32_DisplayControllerConfiguration, and the Win32_VideoConfiguration are obsolete classes and should not be used anymore. Moreover, the Win32_DisplayControllerConfiguration contains a subset of information already available from the Win32_DisplayConfiguration class.

Sample 2.22 retrieves the desktop monitor information. The script is not different from Sample 2.15 ("Retrieving modem information") except for the fact that it uses the Win32_DesktopMonitor class.

Sample 2.22: Retrieving the desktop monitor information

start example

   1:<?xml version="1.0"?>   .:   8:<package>   9:  <job>  ..:  13:    <runtime>  14:      <named name="Machine" helpstring="determine the WMI system to connect to.                                 (default=LocalHost)" required="false" type="string"/>  15:      <named name="User" helpstring="determine the UserID to perform the remote connection.                                 (default=none)" required="false" type="string"/>  16:      <named name="Password" helpstring="determine the password to perform the remote                                 connection. (default=none)" required="false" type="string"/>  17:    </runtime>  18:  19:    <script language="VBScript" src="/books/2/679/1/html/2/..\Functions\DecodeDeviceAvailabilityFunction.vbs" />  20:    <script language="VBScript" src="/books/2/679/1/html/2/..\Functions\DecodeCfgManErrCodeFunction.vbs" />  21:    <script language="VBScript" src="/books/2/679/1/html/2/..\Functions\DecodeStatusInfoFunction.vbs" />  22:    <script language="VBScript" src="/books/2/679/1/html/2/..\Functions\DecodePwrManCapabilitiesFunction.vbs" />  23:  24:    <script language="VBScript" src="/books/2/679/1/html/2/..\Functions\DisplayFormattedPropertyFunction.vbs" />  25:    <script language="VBScript" src="/books/2/679/1/html/2/..\Functions\TinyErrorHandler.vbs" />  26:  27:    <object prog  reference="true"/>  28:    <object prog  />  29:  30:    <script language="VBscript">  31:    <![CDATA[  ..:  35:    Const cComputerName = "LocalHost"  36:    Const cWMINameSpace = "root/cimv2"  ..:  48:    ' --------------------------------------------------------------------------------  49:    ' Parse the command line parameters  50:    strUserID = WScript.Arguments.Named("User")  51:    If Len(strUserID) = 0 Then strUserID = ""  52:  53:    strPassword = WScript.Arguments.Named("Password")  54:    If Len(strPassword) = 0 Then strPassword = ""  55:  56:    strComputerName = WScript.Arguments.Named("Machine")  57:    If Len(strComputerName) = 0 Then strComputerName = cComputerName  58:  59:    objWMILocator.Security_.AuthenticationLevel = wbemAuthenticationLevelDefault  60:    objWMILocator.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate  61:  62:    Set objWMIServices = objWMILocator.ConnectServer(strComputerName, cWMINameSpace, _  63:    strUserID, strPassword)  ..:  66:    Set objWMIInstances = objWMIServices.InstancesOf ("Win32_DesktopMonitor")  ..:  69:    If objWMIInstances.Count Then  70:       For Each objWMIInstance In objWMIInstances  71:           Set objWMIPropertySet = objWMIInstance.Properties_  72:           For Each objWMIProperty In objWMIPropertySet  73:               Select Case objWMIProperty.Name  74:                      Case "Availability"  75:                           DisplayFormattedProperty objWMIInstance, _  76:                              objWMIProperty.Name, _  77:                              DeviceAvailability (objWMIInstance.Availability), _  78:                              Null  79:                      Case "ConfigManagerErrorCode"  80:                           DisplayFormattedProperty objWMIInstance, _  81:                              objWMIProperty.Name, _  82:                              CfgManErrCode (objWMIInstance.ConfigManagerErrorCode), _  83:                              Null  84:                      Case "ConfigManagerUserConfig"  85:                           DisplayFormattedProperty objWMIInstance, _  86:                              objWMIProperty.Name, _  87:                              UCase (objWMIInstance.ConfigManagerUserConfig), _  88:                              Null  89:                      Case "PowerManagementCapabilities"  90:                           DisplayFormattedProperty objWMIInstance, _  91:                              objWMIProperty.Name, _  92:                              PwrManCapabilities (objWMIInstance.Power...entCapabilities), _  93:                              Null  94:                      Case "StatusInfo"  95:                           DisplayFormattedProperty objWMIInstance, _  96:                              objWMIProperty.Name, _  97:                              StatusInfo (objWMIInstance.StatusInfo), _  98:                              Null  99:                      Case "CreationClassName" 100: 101:                      Case "SystemCreationClassName" 102: 103:                      Case "SystemName" 104: 105:                      Case "Caption" 106: 107:                      Case "Name" 108: 109:                      Case Else 110:                           DisplayFormattedProperty objWMIInstance, _ 111:                                                    objWMIProperty.Name, _ 112:                                                    objWMIProperty.Name, _ 113:                                                    Null 114:               End Select 115:           Next 116:           Set objWMIPropertySet = Nothing 117:           WScript.Echo 118:       Next 119:    Else 120:       WScript.Echo "No information available." 121:    End If ...: 126:    ]]> 127:    </script> 128:  </job> 129:</package> 

end example

Once started, the script displays the following information:

  1:    C:\>GetDesktopMonitorInformation.wsf  2:    Microsoft (R) Windows Script Host Version 5.6  3:    Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  4:  5:    Availability: ............................ Running/Full Power  6:    ConfigManagerErrorCode: .................. This device is working properly.  7:    ConfigManagerUserConfig: ................. FALSE  8:    Description: ............................. COMPAQ S700 Color Monitor  9:    *DeviceID: ............................... DesktopMonitor1 10:    MonitorManufacturer: ..................... COMPAQ 11:    MonitorType: ............................. COMPAQ S700 Color Monitor 12:    PixelsPerXLogicalInch: ................... 96 13:    PixelsPerYLogicalInch: ................... 96 14:    PNPDeviceID: ............................. DISPLAY\CPQ1349\4&2E81F5BD&0&80000001&01&00 15:    ScreenHeight: ............................ 864 16:    ScreenWidth: ............................. 1152 17:    Status: .................................. OK 

The two last classes of this category are Win32_VideoController and Win32_VideoSettings. The Win32_VideoSettings class is an association class, which can be used in the script to retrieve a complementary set of information coming from the CIM_VideoControllerResolution (see Figure 2.6). This last class contains the available video resolution.

click to expand
Figure 2.6: Associated instances of one video controller.

Sample 2.23 shows how to retrieve the video adapter information with these classes.

Sample 2.23: Retrieving the video adapter information

start example

   1:<?xml version="1.0"?>   .:   8:<package>   9:  <job>  ..:  13:    <runtime>  14:      <unnamed name="Resolutions" helpstring="Display available resolutions." required="false"                          type="boolean" />  15:      <named name="Machine" helpstring="determine the WMI system to connect to.                          (default=LocalHost)" required="false" type="string"/>  16:      <named name="User" helpstring="determine the UserID to perform the remote connection.                          (default=none)" required="false" type="string"/>  17:      <named name="Password" helpstring="determine the password to perform the remote                           connection. (default=none)" required="false" type="string"/>  18:    </runtime>  19:  20:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeDeviceAvailabilityFunction.vbs" />  21:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeCfgManErrCodeFunction.vbs" />  22:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodeStatusInfoFunction.vbs" />  23:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DecodePwrManCapabilitiesFunction.vbs" />  24:  25:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\ConvertArrayInOneStringFunction.vbs" />  26:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\DisplayFormattedPropertyFunction.vbs" />  27:    <script language="VBScript" src="/books/2/679/1/html/2/.\Functions\TinyErrorHandler.vbs" />  28:  29:    <object prog  reference="true"/>  30:    <object prog  />  31:  32:    <script language="VBscript">  33:    <![CDATA[  ..:  37:    Const cComputerName = "LocalHost"  38:    Const cWMINameSpace = "root/cimv2"  ..:  56:    ' --------------------------------------------------------------------------------  57:    ' Parse the command line parameters  58:    boolResolutionList = WScript.Arguments.Named("Resolutions")  59:    If Len(boolResolutionList) = 0 Then boolResolutionList = False  60:  61:    strUserID = WScript.Arguments.Named("User")  62:    If Len(strUserID) = 0 Then strUserID = ""  63:  64:    strPassword = WScript.Arguments.Named("Password")  65:    If Len(strPassword) = 0 Then strPassword = ""  66:  67:    strComputerName = WScript.Arguments.Named("Machine")  68:    If Len(strComputerName) = 0 Then strComputerName = cComputerName  69:  70:    objWMILocator.Security_.AuthenticationLevel = wbemAuthenticationLevelDefault  71:    objWMILocator.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate  72:  73:    Set objWMIServices = objWMILocator.ConnectServer(strComputerName, cWMINameSpace, _  74:                                                     strUserID, strPassword)  ..:  77:    Set objWMIInstances = objWMIServices.InstancesOf ("Win32_VideoController")  ..:  80:    If objWMIInstances.Count Then  81:       For Each objWMIInstance In objWMIInstances  82:           Set objWMIPropertySet = objWMIInstance.Properties_  83:               For Each objWMIProperty In objWMIPropertySet  84:                   Select Case objWMIProperty.Name  85:                          Case "Availability"  86:                               DisplayFormattedProperty objWMIInstance, _  87:                                  objWMIProperty.Name, _  88:                                  DeviceAvailability (objWMIInstance.Availability), _  89:                                  Null  90:                          Case "ConfigManagerErrorCode"  91:                               DisplayFormattedProperty objWMIInstance, _  92:                                  objWMIProperty.Name, _  93:                                  CfgManErrCode (objWMIInstance.ConfigManagerErrorCode), _  94:                                  Null  95:                          Case "ConfigManagerUserConfig"  96:                               DisplayFormattedProperty objWMIInstance, _  97:                                  objWMIProperty.Name, _  98:                                  UCase (objWMIInstance.ConfigManagerUserConfig), _  99:                                  Null 100:                          Case "PowerManagementCapabilities" 101:                               DisplayFormattedProperty objWMIInstance, _ 102:                                  objWMIProperty.Name, _ 103:                                  PwrManCapabilities (objWMIInstance.PowerMan...abilities), _ 104:                                   Null 105:                          Case "StatusInfo" 106:                               DisplayFormattedProperty objWMIInstance, _ 107:                                   objWMIProperty.Name, _ 108:                                   StatusInfo (objWMIInstance.StatusInfo), _ 109:                                   Null 110:                          Case "CreationClassName" 111: 112:                          Case "SystemCreationClassName" 113: 114:                          Case "SystemName" 115: 116:                          Case "Caption" 117: 118:                          Case "Name" 119: 120:                          Case Else 121:                               DisplayFormattedProperty objWMIInstance, _ 122:                                  objWMIProperty.Name, _ 123:                                  objWMIProperty.Name, _ 124:                                  Null 125:                   End Select 126:               Next 127:           Set objWMIPropertySet = Nothing 128: 129:           Set objWMIResourceInstances = objWMIServices.ExecQuery _ 130:                                              ("Associators of {Win32_VideoController='" & _ 131:                                              objWMIInstance.DeviceID & _ 132:                                              "'} Where AssocClass=Win32_AllocatedResource") 133: 134:           If objWMIResourceInstances.Count Then 135:              WScript.Echo 136:              For Each objWMIResourceInstance In objWMIResourceInstances 137:                  Select Case objWMIResourceInstance.Path_.Class 138:                         Case "Win32_IRQResource" 139:                              DisplayFormattedProperty objWMIResourceInstance, _ 140:                                 "IRQ resource", _ 141:                                 "IRQNumber", _ 142:                                 Null 143:                         Case "Win32_DMAChannel" 144:                              DisplayFormattedProperty objWMIResourceInstance, _ 145:                                 "DMA channel", _ 146:                                 "DMAChannel", _ 147:                                 Null 148:                         Case "Win32_PortResource" 149:                              DisplayFormattedProperty objWMIResourceInstance, _ 150:                                 "I/O Port", _ 151:                                 "Caption", _ 152:                                 Null 153:                         Case "Win32_DeviceMemoryAddress" 154:                              DisplayFormattedProperty objWMIResourceInstance, _ 155:                                 "Memory address", _ 156:                                 "Caption", _ 157:                                 Null 158:                  End Select 159:              Next 160:           End If 161: 162:           If boolResolutionList Then 163:              Set objWMISettingInstances = objWMIServices.ExecQuery _ 164:                                                 ("Associators of {Win32_VideoController='" & _ 165:                                                 objWMIInstance.DeviceID & _ 166:                                                 "'} Where AssocClass=Win32_VideoSettings") 167: 168:              If objWMISettingInstances.Count Then 169:                 WScript.Echo 170:                 intIndice = 0 171:                 ReDim strVideoSetting(0) 172:                 For Each objWMISettingInstance In objWMISettingInstances 173:                     ReDim Preserve strVideoSetting(intIndice) 174:                     strVideoSetting (intIndice) = objWMISettingInstance.SettingID 175:                     intIndice = intIndice + 1 176:                 Next 177:                 DisplayFormattedProperty objWMISettingInstances, _ 178:                                          "Available resolutions", _ 179:                                          strVideoSetting, _ 180:                                          Null 181:              End If 182:           End If 183: 184:           WScript.Echo 185:       Next 186:    Else 187:       WScript.Echo "No information available." 188:    End If ...: 193:    ]]> 194:    </script> 195:  </job> 196:</package> 

end example

Sample 2.23 uses the same logic as previous scripts and contains three main parts:

  • A first part, which lists the Win32_VideoController properties (lines 81 through 126).

  • A second part, which lists the hardware resources used by the video adapter (lines 128 through 159).

  • A third part, which retrieves the available resolutions if the switch /Resolutions+ is specified on the command line (lines 161 through 181).

Each of these parts uses a logic that we discovered in the previous samples. The new element in this script code is a combination of all the scripting techniques in one script. The obtained output is as follows:

   1:    C:\>GetVideoAdapterInformation.wsf /Machine:MyPortable.LissWare.Net /Resolutions+   2:    Microsoft (R) Windows Script Host Version 5.6   3:    Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.   4:   5:    AdapterCompatibility: .................... ATI   6:    AdapterDACType: .......................... ATI Internal DAC   7:    AdapterRAM: .............................. 8388608   8:    Availability: ............................ Running/Full Power   9:    ConfigManagerErrorCode: .................. This device is working properly.  10:    ConfigManagerUserConfig: ................. FALSE  11:    CurrentBitsPerPixel: ..................... 32  12:    CurrentHorizontalResolution: ............. 1024  13:    CurrentNumberOfColors: ................... 4294967296  14:    CurrentNumberOfColumns: .................. 0  15:    CurrentNumberOfRows: ..................... 0  16:    CurrentRefreshRate: ...................... 60  17:    CurrentScanMode: ......................... 4  18:    CurrentVerticalResolution: ............... 768  19:    Description: ............................. ATI RAGE MOBILITY-P AGP (English)  20:    *DeviceID: ............................... VideoController1  21:    DeviceSpecificPens: ...................... -1  22:    DriverDate: .............................. 20-12-2000 12:36:46  23:    DriverVersion: ........................... 5.00.2195.4050  24:    InfFilename: ............................. oem14.inf  25:    InfSection: .............................. ati2mpab_ENU  26:    InstallDate: ............................. 20-12-2000 12:36:46  27:    InstalledDisplayDrivers: ................. ati2drab.dll  28:    MaxRefreshRate: .......................... 120  29:    MinRefreshRate: .......................... 58  30:    Monochrome: .............................. FALSE  31:    NumberOfColorPlanes: ..................... 1  32:    PNPDeviceID: ............................. PCI\VEN_12&DEV_4C4D&SUBSYS_B1E11&REV_64\4&4E&0&08  33:    Status: .................................. OK  34:    TimeOfLastReset: ......................... 20-12-2000 12:36:46  35:    VideoArchitecture: ....................... 5  36:    VideoMemoryType: ......................... 2  37:    VideoModeDescription: .................... 1024 x 768 x 4294967296 colors  38:    VideoProcessor: .......................... ATI RAGE Mobility P/M AGP 2X (A21/2)  39:  40:    *IRQ resource: ........................... 11  41:    Memory address: .......................... 0x40000000-0x410FFFFF  42:    Memory address: .......................... 0x41000000-0x41000FFF  43:    Memory address: .......................... 0xA0000-0xBFFFF  44:    I/O Port: ................................ 0x00002000-0x00002FFF  45:    I/O Port: ................................ 0x000003B0-0x000003BB  46:    I/O Port: ................................ 0x000003C0-0x000003DF  47:  48:    Available resolutions: ................... 320 x 200 x 256 colors @ 60 Hertz  ..:  52:                                               320 x 200 x 65536 colors @ 75 Hertz  53:                                               320 x 200 x 65536 colors @ 85 Hertz ...: 160:                                               800 x 600 x 4294967296 colors @ 75 Hertz 161:                                               800 x 600 x 4294967296 colors @ 85 Hertz 162:                                               800 x 600 x 4294967296 colors @ 90 Hertz 163:                                               800 x 600 x 4294967296 colors @ 100 Hertz 164:                                               1024 x 768 x 256 colors @ 60 Hertz 165:                                               1024 x 768 x 256 colors @ 70 Hertz 166:                                               1024 x 768 x 256 colors @ 72 Hertz 167:                                               1024 x 768 x 256 colors @ 75 Hertz 168:                                               1024 x 768 x 256 colors @ 85 Hertz ...: 175:                                               1024 x 768 x 65536 colors @ 85 Hertz 176:                                               1024 x 768 x 65536 colors @ 90 Hertz 177:                                               1024 x 768 x 65536 colors @ 100 Hertz 178:                                               1024 x 768 x 16777216 colors @ 60 Hertz 179:                                               1024 x 768 x 16777216 colors @ 70 Hertz ...: 233:                                               1600 x 1200 x 4294967296 colors @ 66 Hertz 234:                                               1600 x 1200 x 4294967296 colors @ 70 Hertz 235:                                               1600 x 1200 x 4294967296 colors @ 75 Hertz 




Leveraging WMI Scripting
Leveraging WMI Scripting: Using Windows Management Instrumentation to Solve Windows Management Problems (HP Technologies)
ISBN: 1555582990
EAN: 2147483647
Year: 2003
Pages: 82
Authors: Alain Lissoir

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