Add to Technorati Favorites
Welcome to ThePowerShellGuy.com Sign in | Join | Help

nested relative WMI Queries in PowerShell

In this Newsgroup thread, from the PowerShell newsgroup , there is an question that involves 2 nested relative WMI Queries,  former answers included  difficult querystring contstructing and escaping work, this is where the .NET WMI query helpers become of incredible use see the following script :

# Nested related WMI query example
#
by using RelatedobjectQuery helpers
#
http://thePowerShellGuy.com

$computer = '.'
$drives = Get-WmiObject Win32_DiskDrive -ComputerName $computer

$s = New-Object System.Management.ManagementObjectSearcher
$s2 = New-Object System.Management.ManagementObjectSearcher

$qPartition = new-object System.Management.RelatedObjectQuery
$qPartition.RelationshipClass = 'Win32_DiskDriveToDiskPartition'

$qLogicalDisk = new-object System.Management.RelatedObjectQuery
$qLogicalDisk.RelationshipClass = 'Win32_LogicalDiskToPartition'

$drives |% {
  
"Physical Disk:" + $_.Caption
  
$qPartition.SourceObject = $_
  
$s.Query= $qPartition
  
$s.get()|%
      
"  Disk Partition:" + $_.DeviceID
      
$qLogicalDisk.SourceObject = $_
      
$s2.query= $qLogicalDisk
      
$s2.get()|% {
          
"    Logical Disk:" + $_.deviceid
        }
    }
}

Note that we can use the WMI object we aleady have as the source (so no messing with WMI paths and escaping ) and also can re-use the Query object by only updating the SourceObject property instead of contructing a new querystring every time.

I discussed the use of those helper objects before on my old blog here : /\/\o\/\/ PowerShelled: PowerShell : WMI Support in RC2 (Series ... with more information about those Query helper classes examples, even showing how you can edit the quey in a GUI.

Enjoy,

Greetings /\/\o\/\/

Published Tuesday, January 29, 2008 5:51 PM by MoW
Filed under: ,

Comments

# Interesting Finds: January 30, 2008

Wednesday, January 30, 2008 10:22 AM by Jason Haley
Anonymous comments are disabled