Good day. I have a script fragment: #Query that will run when a USB device is plugged
$query1 = “SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA ‘Win32_PnPEntity’ AND TargetInstance.Description LIKE ‘%FIDO%’”
Register-WmiEvent -Query $query1 -Action {
“FIDO” | Set-Content -Path “$env:TEMP\FIDOWitnessToken2.txt”
}
Query will listen to unplug event
$query = “SELECT * FROM __InstanceDeletionEvent WITHIN 5 WHERE TargetInstance ISA ‘Win32_PnPEntity’ AND TargetInstance.Description LIKE ‘%FIDO%’”
Register-WmiEvent -Query $query -Action {
If (Test-Path “$env:TEMP\FIDOWitnessToken2.txt”) {
rundll32.exe user32.dll,LockWorkStation
Remove-Item “$env:TEMP\FIDOWitnessToken2.txt”
}
}
It works when powershell cmd is opened. How can i make it work at any time? For example it runs as service never stops.
As far as an answer to your question, typically my go to for something like this is a scheduled task. Assuming USB connections are monitored, you should be able to find a corresponding log event that happens and use that as a trigger. It might not be enabled by default either, so you may have to enable it on the system(s) you’re wanting that info. This might get you started: How to track down USB flash drive usage with Windows 10’s Event Viewer | TechRepublic and once you can confirm you can trigger on a specific log, you should be able to set the trigger of scheduled task to ‘on an event’ and go from there. Looks like 2100 or 2102 are the events that you’d likely be looking for.