Skip to content

Instantly share code, notes, and snippets.

@sr10952
Last active April 28, 2023 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sr10952/f87463c69291503dbd216925071fb5c5 to your computer and use it in GitHub Desktop.
Save sr10952/f87463c69291503dbd216925071fb5c5 to your computer and use it in GitHub Desktop.
Prerequisites
Ensure that the 'Microsoft-Windows-DriverFrameworks-UserMode/Operational' event log is enabled on your system.
Identify the serial number of the USB device you want to monitor. You can use the wmic command to get this information.
Script
The script uses a $Query variable that contains a filter expression that selects events with EventID 2003 from the 'Microsoft-Windows-DriverFrameworks-UserMode/Operational' event log.
The script then retrieves the most recent event that matches the filter using the Get-WinEvent cmdlet.
It checks if the message of the most recent event contains the serial number of the USB device you want to monitor. If the serial number is found, a message box with the title 'Title' and the text 'Sure about it?' is displayed with 'Yes', 'No', and 'Cancel' buttons. If the serial number is not found, a message box with the title 'Title' and the text 'Not expecting this USB' is displayed.
To use this script to monitor a specific USB device, replace 'Seriel Number Goes Here' in the script with the serial number of the device you want to monitor. You can then create a scheduled task that runs this script on event ID 2003.
In the scheduled tasks actions select Start a program, powershell and for arguments use -file c:\filepath.ps1
Note: This script is only a partial solution, as it only filters events by EventID and then performs a partial match on the message text. It does not provide a complete solution for monitoring USB devices, as it may generate false positives if there are multiple USB devices with the same partial serial number.
$Query = @"
<QueryList>
<Query Id="0" Path="Microsoft-Windows-DriverFrameworks-UserMode/Operational">
<Select Path="Microsoft-Windows-DriverFrameworks-UserMode/Operational">*[System[(EventID=2003)]]</Select>
</Query>
</QueryList>
"@
$events = Get-WinEvent -FilterXml $Query
($events | select -First 1).message
$lastevent = (Get-WinEvent -FilterXml $Query | select -First 1).message
if($lastevent.Contains("Seriel Number Goes Here")){
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show('Sure about it?','Title', 'YesNoCancel')
} else {
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show('Not expecting this USB')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment