0
votes

I am trying to accomplish this:

When I insert a USB drive in Windows (Win7 and Win8), I want a script to be started (Powershell or batch command) automatically. The machine has autoplay disabled.

I setup a scheduled task with event id 2010 in DriveFrameworks-UserMode as trigger. The scheduled task works. However, I am having difficulties finding the drive letter of the newly inserted USB drive.

I found a few solutions on the Internet, but they didn't fit my requirements. The solutions either check for all drive letters (A to Z), or check for USB drive. I would like to correlate the drive letter that is associated with the event in the DriveFrameworks-UserMode trigger.

This post (How do i get the drive letter of a USB Drive in Powershell?) gave me some hints and I checked classes win32_logicaldisk, win32_diskdrive, and win32_pnpentity, but I couldn't find a clue matching them.

Any help is appreciated.

1
Have you tried anything so far? Any code to review?Alfabravo

1 Answers

1
votes

This should help:

$diskdrive = gwmi win32_diskdrive | ?{$_.interfacetype -eq "USB"}
$letters = $diskdrive | %{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} 

$drive = gwmi win32_volume | ? {$letters -contains ($_.name -replace "\\")}
$drive.DriveLetter

PS. There is a similar discussion here