How to get the drive letter of a USB drive in Powershell?

I have seen articles in C # and some other languages ​​that explain how to achieve what they are looking for, but I don’t know how to convert them.

The following link explains how to get the answer: How to get the drive letter of a USB device?

Win32_DiskDrive-> Win32_DiskDriveToDiskPartition β†’ Win32_DiskPartition β†’ Win32_LogicalDiskToPartition β†’ Win32_LogicalDisk

the third answer down (by GEOCHET) explains also explains how to achieve an answer, but again, not in powershell.

How to find the letter of a USB drive?

+4
source share
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 by one or more connected USB devices.

+7
source

I know that the topic has been discarded for a while, but since it is something that I often return, although I update things a bit.

If you use 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: http://msdn.microsoft.com/en-us/library/windows/desktop/aa394515(v=vs.85).aspx http://msdn.microsoft.com/en-us/library/system. io.drivetype.aspx

+4
source

Starting with PowerShell v3.0, Microsoft has introduced Get-Cim* commands that make this easier than the ugliness of the Get-WmiObject ASSOCIATORS request 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.

+1
source
 get-volume | where drivetype -eq removable 
0
source

All Articles