Create WMI Event

Hi, I’m trying to create this wmi event so that when a SANDISK usb connects, script will. So far it doesn’t work. Any help would be appreciated.

$filter = ([wmiclass]"\\.\root\subscription:__EventFilter").CreateInstance()

$filter.QueryLanguage = "WQL"
$filter.Query = "Select * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'win32_PNPEntity' and TargetInstance.DeviceID like 'USBSTOR%SANDISK%'"
$filter.Name = "USBFilter"
$filter.EventNamespace = 'root\cimv2'

$result = $filter.Put()
$filterPath = $result.Path

$consumer = ([wmiclass]"\\.\root\subscription:CommandLineEventConsumer").CreateInstance()
$consumer.Name = 'USBConsumer'
$consumer.CommandLineTemplate = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe –ExecutionPolicy Bypass -file C:\scripts\COPY.ps1"
$consumer.ExecutablePath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
$consumer.WorkingDirectory = "C:\scripts"
$result = $consumer.Put()
$consumerPath = $result.Path

$bind = ([wmiclass]"\\.\root\subscription:__FilterToConsumerBinding").CreateInstance()

$bind.Filter = $filterPath
$bind.Consumer = $consumerPath
$result = $bind.Put()
$bindPath = $result.Path

What’s your end goal? for the copy.ps1 script to fire when someone plugs in a USB? You didn’t really finish your thought…seems like that’s probably it though - probably following something like this: Monitoring and Responding to Events with Standard Consumers - Win32 apps | Microsoft Learn potentially

Also… it would help if you told us what did not work about it, though i’m guessing it just doesn’t do anything. Nontheless, please avoid blanketed statements and provide detail so people can better assist. Don’t be afraid to explain in detail what you actually are doing with your code; don’t make assumptions about what your audience knows.

Lastly, always provide the expected output/behavior and actual output/behavior in simple terms so people know what you are trying to accomplish.

I’ve not worked that much with this type of stuff, but if you are indeed trying to run a script when a USB device is connected, it seems like lots of folks online use task scheduler instead based on EventViewer logs. Take a look at my previous link and vbscript - WMI Event Subscription and PowerShell execution - Stack Overflow

So when I plug in USB, script will run and backup files and folders from computer to USB. I created the WMI event, there was no error. I plugged in USB, and COPY.ps1 script did not start at all.

My script does not produce any noticeable error so I don’t know whats wrong or what criteria is missing. Can anyone shed some light ?