2
1
I would like to use PowerShell to detect if an SD card is there. After an SD card has been detected, a PowerShell script should automatically copy some files to the SD card.
I already found and tried a PS script, but it only detects USB sticks.
Register-WmiEvent -Class win32_VolumeChangeEvent -SourceIdentifier volumeChange
write-host (get-date -format s) " Beginning script..."
do{
$newEvent = Wait-Event -SourceIdentifier volumeChange
$eventType = $newEvent.SourceEventArgs.NewEvent.EventType
$eventTypeName = switch($eventType)
{
1 {"Configuration changed"}
2 {"Device arrival"}
3 {"Device removal"}
4 {"docking"}
}
write-host (get-date -format s) " Event detected = " $eventTypeName
if ($eventType -eq 2)
{
$driveLetter = $newEvent.SourceEventArgs.NewEvent.DriveName
$driveLabel = ([wmi]"Win32_LogicalDisk='$driveLetter'").VolumeName
write-host (get-date -format s) " Drive name = " $driveLetter
write-host (get-date -format s) " Drive label = " $driveLabel
# Execute process if drive matches specified condition(s)
if ($driveLetter -eq 'E:' -and $driveLabel -eq 'Test 1')
{
write-host (get-date -format s) " Starting task in 3 seconds..."
start-sleep -seconds 3
start-process "E:test.bat"
}
}
Remove-Event -SourceIdentifier volumeChange
} while (1-eq1) #Loop until next event
Unregister-Event -SourceIdentifier volumeChange
I have no SD card in handy so I cannot test my suggestion. But try to change
if ($eventType -eq 2)
toif ($eventType -eq 4)
. The script then does not watch for Device arrival (new drive letter added?) but rather for the docking of new hardware. I also assume that you already changedif ($driveLetter -eq 'E:' -and $driveLabel -eq 'Test 1')
to your own needs? – nixda – 2016-09-10T10:52:09.797Hi nixda and thank you for your reply. I have already modified script but it still doesn't detect SD card. The main reason (I think) why script doesn't work it is if you have an built-in SD card reader, and you eject the SD card, you are still able to find card reader under Disk Management with assigned letter. – saygon – 2016-09-10T11:39:43.880
I think you're right about the drive letter. That's why I thought Device arrival won't work. Now that I read MSDN again it says includes changes in the hardware configuration (docking and undocking). So docking will probably also not work. Hmmm
– nixda – 2016-09-10T12:17:02.677