Alternate Ways to Connect to WMI


In Chapter 5, “Using WMI,” we learned about using the Get-WmiObject cmdlet to produce some basic WMI queries. We also looked briefly at connecting to WMI using the SWbemLocator object. When we make a connection to WMI by either method, it is important to realize there are default values being specified for the WMI connection.

The default values are stored in the following registry location: HKEY_LOCAL_MACHINE\ SOFTWARE\Microsoft\WBEM\Scripting. There are two keys: Default Impersonation Level and Default Damespace. Default Impersonation Level is set to a default of 3, which means that WMI impersonates the logged-on user. The Default Namespace is set to Root\cimv2. In reality, these are pretty good defaults. The default computer is the local machine, so you don’t need to specify the computer name when you’re simply running against the local machine.

Tip 

Use default WMI values to simplify your WMI scripts. If you only want to return information from the local machine, the WMI class resides in the default namespace, and you intend to impersonate the logged-on user, then the defaults are perfect.

image from book SmallBios.ps1

 Get-WmiObject win32_bios

When we use the Get-WmiObject cmdlet and only supply the name of the WMI class, then we are relying on the default values: default computer, default WMI namespace, and default impersonation level. The image from book SmallBios.ps1 script produces the information shown here, which is the main information you would want to see about the bios: the version, name, serial number, and maker.

 SMBIOSBIOSVersion : Version 1.40 Manufacturer      : TOSHIBA Name              : v1.40 SerialNumber      : 55061728HU Version           : TOSHIB – 970814

The amazing thing is that you can obtain such useful information by typing about 15 characters on the keyboard (using Tab completion). To do this in VBScript would require much more typing. However, if you want to retrieve different information from the WIN32_Bios WMI class, or if you would like to see a different kind of output, then you will need to work with the Format cmdlets. This is illustrated next in the retrieving properties procedure.

Retrieving properties

  1. Open Windows PowerShell.

  2. Use the Get-WmiObject cmdlet to retrieve the default properties of the WIN32_ComputerSystem WMI class.

     Get-WmiObject win32_computersystem

  3. The results, with the default properties, are shown here:

     Domain              : nwtraders.com Manufacturer        : TOSHIBA Model               : TECRA M3 Name                : MRED1 PrimaryOwnerName    : Mred TotalPhysicalMemory : 2146680832

  4. If you are only interested in the name and the make and model of the computer, then you will need to pipeline the results into a Format-List cmdlet and choose only the properties you wish. This revised command is shown here:

     Get-WmiObject win32_computersystem | Format-List name,model, manufacturer

  5. The results are shown here:

     name         : MRED1 model        : TECRA M3 manufacturer : TOSHIBA

  6. If you are interested in all the properties from the WIN32_computersystem class, you have several options. The first is to use the up arrow and modify the Format-List cmdlet. Instead of choosing three properties, change it to an asterisk (*). This revised command is shown here:

     Get-WmiObject win32_computersystem | Format-List *

  7. The results from this command are shown here. Notice, however, that although the results seem impressive at first, they quickly degenerate into seemingly meaningless drivel. Note the number of classes that begin with double underscore, such as __CLASS. These are system properties that get attached to every WMI class when they are created. Although useful to WMI gurus, they are less exciting to normal network administrators.

     AdminPasswordStatus         : 0 BootupState                 : Normal boot ChassisBootupState          : 3 KeyboardPasswordStatus      : 0 PowerOnPasswordStatus       : 0 PowerSupplyState            : 3 PowerState                  : 0 FrontPanelResetStatus       : 0 ThermalState                : 3 Status                      : OK Name                        : MRED1 PowerManagementCapabilities : PowerManagementSupported    : __GENUS                     : 2 __CLASS                     : Win32_ComputerSystem __SUPERCLASS                : CIM_UnitaryComputerSystem __DYNASTY                   : CIM_ManagedSystemElement __RELPATH                   : Win32_ComputerSystem.Name="MRED1" __PROPERTY_COUNT            : 54 __DERIVATION                : {CIM_UnitaryComputerSystem, CIM_ComputerSystem, C                               IM_System, CIM_LogicalElement...} __SERVER                    : MRED1 __NAMESPACE                 : root\cimv2 __PATH                      : \\MRED1\root\cimv2:Win32_ComputerSystem.Name="MRE                               D1" AutomaticResetBootOption    : True AutomaticResetCapability    : True BootOptionOnLimit           : BootOptionOnWatchDog        : BootROMSupported            : True Caption                     : MRED1 CreationClassName           : Win32_ComputerSystem CurrentTimeZone             : 60 DaylightInEffect            : False Description                 : AT/AT COMPATIBLE Domain                      : northamerica.corp.microsoft.com DomainRole                  : 1 EnableDaylightSavingsTime   : True InfraredSupported           : False InitialLoadInfo             : InstallDate                 : LastLoadInfo                : Manufacturer                : TOSHIBA Model                       : TECRA M3 NameFormat                  : NetworkServerModeEnabled    : NumberOfProcessors          : 1 OEMLogoBitmap               : OEMStringArray              : {PTM30U-0H001V59,SQ003648A83,138} PartOfDomain                : True PauseAfterReset             : -1 PrimaryOwnerContact         : PrimaryOwnerName            : Mred ResetCapability             : 1 ResetCount                  : -1 ResetLimit                  : -1 Roles                       : SupportContactDescription   : SystemStartupDelay          : 15 SystemStartupOptions        : {"Microsoft Windows XP Professional" /noexecute=o                               ptin /fastdetect} SystemStartupSetting        : 0 SystemType                  : X86-based PC TotalPhysicalMemory         : 2146680832 UserName                    : NORTHAMERICA\edwils WakeUpType                  : 6 Workgroup                   :

  8. To remove the system properties from the list, use the up arrow to retrieve the Get-WmiObject win32_computersystem | Format-List * command. Delete the asterisk in the Format-List command and replace it with an expression that limits the results to property names that are returned to only those that begin with the letters a through z. This command is shown here:

     Get-WmiObject win32_computersystem | Format-List [a-z]*

  9. To see a listing of properties that begin with the letter d, use the up arrow to retrieve the Get-WmiObject win32_computersystem | Format-List [a-z]* command and change the Format-List cmdlet to retrieve only properties that begin with the letter d. To do this, substitute d* for [a-z]*. The revised command is shown here:

     Get-WmiObject win32_computersystem | Format-List D*

  10. Retrieve a listing of all the properties and their values from the WIN32_computersystem WMI class that begin with either the letter d or the letter t. Use the up arrow to retrieve the previous Get-WmiObject win32_computersystem | Format-List D* command. Use a comma to separate the t* from the previous command. The revised command is shown here:

     Get-WmiObject win32_computersystem | Format-List d*,t*

  11. This concludes the retrieving properties procedure.

Tip 

After you use the Get-WmiObject cmdlet for a while, you may get tired of using Tab completion and having to type Get-W<tab>. It may be easier to use the default alias of gwmi. This alias was discovered by using the following command:

 Get-Alias | where {$_.definition -eq 'Get-WmiObject'}

Working with disk drives

  1. Open Windows PowerShell.

  2. Use the gwmi alias to retrieve the default properties for each drive defined on your system. To do this, use the WIN32_LogicalDisk WMI class. This command is shown here:

     gwmi win32_logicaldisk

  3. The result of the gwmi win32_logicaldisk command is shown here:

     DeviceID     : C: DriveType    : 3 ProviderName : FreeSpace    : 6164701184 Size         : 36701163520 VolumeName   : c  DeviceID     : D: DriveType    : 3 ProviderName : FreeSpace    : 11944701952 Size         : 23302184960 VolumeName   : d  DeviceID     : E: DriveType    : 5 ProviderName : FreeSpace    : Size         : VolumeName   :

  4. To limit the disks returned by the WMI query to only local disk drives, we can supply a value of 3 for the drive type property. Use the up arrow to retrieve the previous command. Add the drivetype property to the filter parameter of the Get-WMIObject cmdlet with a value of 3. This revised command is shown here:

     gwmi win32_logicaldisk -filter drivetype=3

  5. The resulting output from the gwmi win32_logicaldisk -filter drivetype=3 command is shown here:

     DeviceID     : C: DriveType    : 3 ProviderName : FreeSpace    : 6163599360 Size         : 36701163520 VolumeName   : c DeviceID     : D: DriveType    : 3 ProviderName : FreeSpace    : 11944701952 Size         : 23302184960 VolumeName   : d

  6. Open Notepad.exe, or some other script editor, and save the file as yournameLogical Disk.ps1.

  7. Use the up arrow in PowerShell to retrieve the gwmi win32_logicaldisk -filter drivetype=3 command. Highlight it with your mouse, and press Enter.

  8. Paste the command into the yournameimage from book LogicalDisk.ps1 script.

  9. Declare a variable called $objDisk at the top of your script. This command is shown here:

     $objDisk

  10. Use the $objDisk variable to hold the object returned by the command you copied from your PowerShell console. As we are planning on saving the script, replace the gwmi alias with the actual name of the cmdlet. The resulting command is shown here:

     $objDisk=Get-WmiObject win32_logicaldisk -filter drivetype=3

  11. Use the Measure-Object cmdlet to retrieve the minimum and the maximum values for the freespace property. To do this, pipeline the previous object into the Measure-Object cmdlet. Specify freespace for the property argument, and use the minimum and the maximum switches. Use the pipeline character to break your code into two lines. This command is shown here:

     $objDisk=Get-WmiObject win32_logicaldisk -filter drivetype=3 |    Measure-Object -property freespace -Minimum -Maximum

  12. Print out the resulting object that is contained in the $objDisk variable. This command is shown here:

     $objDisk

  13. The resulting printout on my computer is shown here:

     Count    : 2 Average  : Sum      : Maximum  : 11944701952 Minimum  : 6163550208 Property : freespace

  14. To dispose of the empty properties, pipeline the previous command into a Select-Object cmdlet. Choose the property and the minimum and maximum properties. Use the pipeline character to break your code into multiple lines The revised command is shown here:

     $objDisk=Get-WmiObject win32_logicaldisk -filter drivetype=3 |    Measure-Object -property freespace  -Minimum -Maximum |    Select-Object -Property property, maximum, minimum

  15. Save and run the script. Notice how the output is spread over the console. To tighten up the display, pipeline the resulting object into the Format-Table cmdlet. Use the autosize switch. The revised command is shown here:

     $objDisk=Get-WmiObject win32_logicaldisk -filter drivetype=3 |    Measure-Object -property freespace  -Minimum -Maximum |    Select-Object -Property property, maximum, minimum |    Format-Table -autosize

  16. Save and run the script. The output on my computer is shown here:

     Property      Maximum    Minimum --------      -------    ------- freespace 11944685568 6164058112

  17. If your results are not similar, compare yournameimage from book LogicalDisk.ps1 with image from book LogicalDisk.ps1.

    Note 

    The WMI class WIN32_LogicalDisk property DriveType can have a value of 0 to 6 inclusive. The most useful of these values are as follows: 3 local disk, 4 network drive, 5 compact disk, and 6 ram disk.




Microsoft Press - Microsoft Windows PowerShell Step by Step
MicrosoftВ® Windows PowerShell(TM) Step By Step (Step By Step (Microsoft))
ISBN: 0735623953
EAN: 2147483647
Year: 2007
Pages: 128
Authors: Ed Wilson

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