Friday, October 29, 2021

[SOLVED] How to get name of a USB device that is already mounted?

Issue

I'm actually writing a node script that detect if a specific USB is plugged, then it copy it content to Desktop. This is for Windows principally. To do this I manually check if 'E:\' path exists , 'F:\' , etc...

But I need to be sure that devices are the ones that I need. They got specific names, for example:

MTR12345 or MTR23RR5 or MTRTGX23.

And I need to know theses names. I searched for differents nodejs and powershell solutions but no ones fit my needs.

I need to get the name of the device that is mounted at E:\ . I'm totally new to PowerShell and NodeJS as well.

How can I do this ? Thanks for your help.


Solution

Sounds like you are just looking for the volume names. The WMI class Win32_logicaldisk would return that for mounted devices. Assuming it was populated of course. In it's simplest form:

Get-WmiObject Win32_logicaldisk | Where-Object{$_.VolumeName -eq "MyUSBKey"}

You have some specific examples and a regex query that you are trying to use to narrow down the results. So if you want to match a regex query:

Get-WmiObject Win32_logicaldisk | 
    Where-Object{Where-Object{$_.VolumeName -match "MTR[A-Za-z0-9]+"}} |          
    Select -Expand DeviceID

You could even simplify that if you wanted. Just match volumes that start with "MTR". Not as perfect as the other one but just as simple.

Get-WmiObject Win32_logicaldisk | 
    Where-Object{Where-Object{$_.VolumeName -match "^MTR"}} |          
    Select -Expand DeviceID


Answered By - Matt