Start PowerShell script when USB drive is inserted
powershell, windows
Solution
You can use Windows Management Instrumentation (WMI) events to detect when a USB flash drive is inserted. You can create a temporary event registration using the `Register-WmiEvent` cmdlet.
Let's say that you have a script file called `c:\test\script.ps1`. This script will be used to respond to events when they occur.
Add-Content -Path $PSScriptRoot\test.txt -Value 'USB Flash Drive was inserted.';
Then, you need to register for WMI events using the `Register-WmiEvent` cmdlet in a separate script. You will need to specify the `-Action` and `-Query` parameters at a minimum. The PowerShell `ScriptBlock` that is passed to the `-Action` parameter will be invoked when an event occurs. The `-Query` parameter contains the WMI event query that will be used to poll WMI for events. I have provided a sample below.
# Define a WMI event query, that looks for new instances of Win32_LogicalDisk where DriveType is "2"
# http://msdn.microsoft.com/en-us/library/aa394173(v=vs.85).aspx
$Query = "select * from __InstanceCreationEvent within 5 where TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2";
# Define a PowerShell ScriptBlock that will be executed when an event occurs
$Action = { & C:\test\script.ps1; };
# Create the event registration
Register-WmiEvent -Query $Query -Action $Action -SourceIdentifier USBFlashDrive;
Since you mentioned that you wanted to launch a PowerShell script file on the USB drive, when this event occurs, you can change the `-Action` `ScriptBlock` to this:
$Action = { & ('{0}\ufd.ps1' -f $event.SourceEventArgs.NewEvent.TargetInstance.Name); };
The above code will dynamically execute the `ufd.ps1` script file on the root of the USB drive that was just inserted.
Problem
Is there any way the PowerShell script located on a USB drive can be started the moment the drive is inserted in PC? It has to copy all PDF files from PC to the USB drive, but that's not the question. The only thing I don't know is how to start the script as soon as the USB drive is inserted. Can anyone help?