Created
January 6, 2025 18:53
-
-
Save AldeRoberge/a14cfd0a98196961356b8fa8761ae7cf to your computer and use it in GitHub Desktop.
This PowerShell script monitors and logs USB device connection and disconnection events on the system. Whenever a USB device is plugged in or removed, the script captures relevant details and logs them.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Function to display USB event information | |
function Display-USBEvent { | |
param ( | |
[string]$EventType, | |
[string]$DeviceName | |
) | |
Write-Host "[$(Get-Date -Format 'HH:mm:ss')] ${EventType}: ${DeviceName}" -ForegroundColor Yellow | |
} | |
# Query for monitoring USB device connections | |
$queryConnect = "SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_USBControllerDevice'" | |
# Query for monitoring USB device disconnections | |
$queryDisconnect = "SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_USBControllerDevice'" | |
# Register WMI event for USB device connections | |
Register-WmiEvent -Query $queryConnect -SourceIdentifier "USBConnectEvent" -Action { | |
$device = $event.SourceEventArgs.NewEvent.TargetInstance.Dependent | |
Display-USBEvent "Connected" $device | |
} | |
# Register WMI event for USB device disconnections | |
Register-WmiEvent -Query $queryDisconnect -SourceIdentifier "USBDisconnectEvent" -Action { | |
$device = $event.SourceEventArgs.NewEvent.TargetInstance.Dependent | |
Display-USBEvent "Disconnected" $device | |
} | |
Write-Host "Monitoring USB device connections/disconnections. Press Ctrl+C to stop." -ForegroundColor Green | |
# Wait indefinitely to keep monitoring until user stops the script | |
while ($true) { | |
Start-Sleep -Seconds 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment