tripleq
tripleq

Reputation: 99

Start PowerShell script when USB drive is inserted

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?

Upvotes: 8

Views: 29423

Answers (2)

user189198
user189198

Reputation:

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.

Upvotes: 12

Adil Hindistan
Adil Hindistan

Reputation: 6615

Well, I cannot test this, but I think you can probably use AutoPlay feature of windows if that's not disabled.

So, let's say you have MyPowerShell.ps1 on the root of the USB drive. You would create an Autorun.ini file that would launch a cmd, which can launch the powershell script. You might even be able to bypass the cmd but as I said, I cannot test right now.

Autorun.ini would include:

[autorun]
icon=yourIconFile.ico
open=autorun.cmd
Action=Click "OK" to copy PDF files!

Then your Autorun.cmd would include the following line

%Windir%\System32\WindowsPowerShell\v1.0\PowerShell.exe -exec bypass -noprofile -file MyPowerShell.ps1

Upvotes: 7

Related Questions