Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the drive letter of USB drive in PowerShell

I've seen articles in C# and some other languages that explain how to achieve what I'm looking for but I don't know how to convert them.

  • The following link explains how to get the answer:
    How can I get the drive letter of an USB device?
    Win32_DiskDrive-> Win32_DiskDriveToDiskPartition -> Win32_DiskPartition -> Win32_LogicalDiskToPartition -> Win32_LogicalDisk

  • The answer by GEOCHET explains also explains how to achieve the answer but again, not in PowerShell: How to find USB drive letter?

like image 598
resolver101 Avatar asked May 17 '12 10:05

resolver101


4 Answers

Try:

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

Tested with one and more than one USB device plugged-in.

like image 128
CB. Avatar answered Nov 18 '22 11:11

CB.


I know the subject has been dropped for a while, but since it's something I come back to pretty often, I thought I'd update things a bit.

If using Windows 7 and above, a much simpler solution would be:

Get-WmiObject Win32_Volume -Filter "DriveType='2'"

And if you want to avoid magic numbers:

Get-WmiObject Win32_Volume -Filter ("DriveType={0}" -f [int][System.IO.DriveType]::Removable)

References:
https://learn.microsoft.com/en-us/previous-versions/windows/desktop/vdswmi/win32-volume
https://learn.microsoft.com/en-us/dotnet/api/system.io.drivetype

like image 34
Poorkenny Avatar answered Nov 18 '22 09:11

Poorkenny


Beginning with PowerShell v3.0, Microsoft introduce the Get-Cim* commands which make this easier than the ugliness of the Get-WmiObject ASSOCIATORS query method:

Get-CimInstance -Class Win32_DiskDrive -Filter 'InterfaceType = "USB"' -KeyOnly | 
    Get-CimAssociatedInstance -ResultClassName Win32_DiskPartition -KeyOnly |
    Get-CimAssociatedInstance -ResultClassName Win32_LogicalDisk |
    Format-List *

Or:

Get-CimInstance -Class Win32_DiskDrive -Filter 'InterfaceType = "USB"' -KeyOnly |
    Get-CimAssociatedInstance -Association Win32_DiskDriveToDiskPartition -KeyOnly |
    Get-CimAssociatedInstance -Association Win32_LogicalDiskToPartition |
    Format-List *

The above commands are equivalent.

like image 4
Bacon Bits Avatar answered Nov 18 '22 11:11

Bacon Bits


get-volume | where drivetype -eq removable | foreach driveletter

volume | ? drivetype -eq removable | % driveletter
like image 4
js2010 Avatar answered Nov 18 '22 11:11

js2010