Powershell: Grab USB Drive letter

drive-letterpowershellusbwmi

I am trying to figure out a Powershell command that would allow me to capture the drive letter of the only USB drive plugged into the computer, and then be able to recall that variable like this:

dir %usbdrive%

I have used this command to show the stats of the only USB drive:

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

But how can I either store the drive letter in a variable or just change the drive letter to a completely different letter like "T"?

Best Answer

Storing the drive letter is simple, you pipe your result to Select -ExpandProperty DriveLetter, and as is pretty basic in PowerShell you assign the result of that command to a variable like:

$USBDrive = Get-WmiObject Win32_Volume -Filter "DriveType='2'"|select -expand driveletter

Now, that does include a trailing colon on it, so you might want to trim that off like:

$USBDrive = $USBDrive.Trim(":")

That would leave you with only the letter of the drive. Changing the drive letter of a known drive is another matter. If you really want to get into that let us know, or possibly better yet post a new question asking how to change a drive letter.