Search code examples
powershellget-wmiobject

Basic Powershell question on getting piped values in result


New to Powershell coding here.

Given this means of looking up USB drive letter assignments:

$Foo2 = Get-WMIObject win32_diskdrive | ?{$_.interfacetype -eq "USB"} | %{Get-WMIObject -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`"$($_.DeviceID.replace('\','\\'))`"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"} |  %{Get-WMIObject -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`"$($_.DeviceID)`"} WHERE AssocClass = Win32_LogicalDiskToPartition"} | %{$_.deviceid}

How would I go about getting each deviceID of the first two sections of code, namely:

Get-WMIObject win32_diskdrive | ?{$_.interfacetype -eq "USB"}

in the final result? So instead of the current result being just drive letters, the output would include the lookup value alongside the result, for example:

deviceID             driveLetter
-------------------  -----------
 \\.\PHYSICALDRIVE1  D:
 \\.\PHYSICALDRIVE3  F:
 \\.\PHYSICALDRIVE2  G:

Solution

  • Aside from just running get-volume | ? drivetype -eq removable, -pipelinevariable or -pv to the rescue, with a custom "disk" variable. It's a bit confusing that the drive letter is originally called a "deviceid" property.

    Get-Ciminstance win32_diskdrive | ?{$_.interfacetype -eq "USB"} -pv disk |
    %{Get-Ciminstance -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`"$($_.
      DeviceID.replace('\','\\'))`"} WHERE 
      AssocClass = Win32_DiskDriveToDiskPartition"} |
    %{Get-Ciminstance -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`"$($_.
      DeviceID)`"} WHERE AssocClass = Win32_LogicalDiskToPartition"} |
    select @{n='deviceid';e={$disk.deviceid}},@{n='driverletter';e={$_.deviceid}}
    
    deviceid           driveletter
    --------           -----------
    \\.\PHYSICALDRIVE2 E:
    \\.\PHYSICALDRIVE3 F: