Skip to content

Instantly share code, notes, and snippets.

@DieKatzchen
Last active September 20, 2025 18:59
Show Gist options
  • Save DieKatzchen/f3c093c30df5ab6c5d8b5defe339dc09 to your computer and use it in GitHub Desktop.
Save DieKatzchen/f3c093c30df5ab6c5d8b5defe339dc09 to your computer and use it in GitHub Desktop.
#Requires -version 2.0
<#
.SYNOPSIS
Copies files to a USB drive whenever one is plugged in.
.DESCRIPTION
Waits for a USB drivwe to be pugged in and then immediately copies the
contents of ./payload/ to the root of it. Primarily intended for batch
programming of microcontrollers that emulate a USB drive to which you
copy a .uf2 file, but there's no check, you can copy whatever you want
.NOTES
File Name : uf2copy.ps1
Author : DasKatzchen, based on code posted on SuperUser.com
Prerequisite : PowerShell V2 over Vista and upper.
.LINK
Original post:
https://superuser.com/questions/219401/starting-scheduled-task-by-detecting-connection-of-usb-device
.LINK
Script downloaded from:
https://gist.github.com/DieKatzchen/f3c093c30df5ab6c5d8b5defe339dc09
#>
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)
write-host (get-date -format s) " Copying payload..."
Copy-Item -Path ".\payload\*.*" -Destination $driveLetter
}
Remove-Event -SourceIdentifier volumeChange
} while (1-eq1) #Loop until next event
Unregister-Event -SourceIdentifier volumeChange
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment