JGH
JGH

Reputation: 1

Find the drive letter of an external connected drive in powershell

I am trying to get the drive letter of a externally connected drive in powershell. I don't want usb flashdrives just an external usb hard drive. I've tried combinations of using get-cimInstance win32_diskdrive, get-physicaldisk, and getwmiobject win32_logicaldisk, but none give me everything I need.

get-ciminstance win32_diskdrive | select mediatype tells me if its an external drive which is great, but there is no way to get the drive letter from win32_diskdrive that I'm aware of.

Can anyone help?

Upvotes: 0

Views: 278

Answers (3)

JGH
JGH

Reputation: 1

I found a bit of code and modified it slightly to get what I wanted. Here it is:

$drive = Get-WmiObject win32_diskdrive |
  Where-Object {$_.mediatype -eq "External hard disk media"} | 
    ForEach-Object {
      Get-WmiObject -query "associators of {win32_diskdrive.deviceid=`"$($_.deviceid.replace('\','\\'))`"} where assocclass = win32_diskdrivetodiskpartition"
      } |
        ForEach-Object {
          Get-WmiObject -query "associators of {win32_diskpartition.deviceid=`"$($_.deviceid)`"} where assocclass = win32_logicaldisktopartition"
        } |
          ForEach-Object {$_.deviceid}

Upvotes: 0

Dennis
Dennis

Reputation: 1855

Is adding the drive letter to Win32_DiskDrive for all removable drives what you are looking for?

[array](Get-Volume | where DriveType -eq 'Removable') | foreach {
  $ThisRemovableDriveLetter = $_.DriveLetter

  $ThisPartition = Get-Partition | where DriveLetter -eq $ThisRemovableDriveLetter

  $ThisPartitionId = $ThisPartition.UniqueId.Replace(":$ENV:ComputerName",'').remove(0,38)

  Get-CimInstance Win32_DiskDrive |
    where PNPDeviceID -eq $ThisPartitionId |
      select *, @{ l = 'Drive'; e = {$RemovableDriveLetter} }
}

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

You can use WMI associations to find the corresponding drive letter(s):

# discover connected physical disks
$diskDrives = Get-CimInstance Win32_DiskDrive 

# filter on type
$diskDrives = $diskDrives |Where-Object MediaType -eq '<device type description goes here>'

# discover associated partitions
$diskPartitions = $diskDrives |Get-CimAssociatedInstance -ResultClassName Win32_DiskPartition

# discover associated logical drives
$logicalDrives = $diskPartitions |Get-CimAssociatedInstance -ResultClassName Win32_DiskPartition

# output drive letter
#logicalDrives |Select @{Name='DriveLetter';Expression='DeviceID'}

Upvotes: 0

Related Questions