Last active
April 15, 2026 03:36
-
-
Save ericchansen/68485e96f8c17abf388cb4a58ebe5ef3 to your computer and use it in GitHub Desktop.
PowerShell script to monitor device connects and disconnects on Windows.
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
| <# | |
| .SYNOPSIS | |
| Monitor PnP device connects and disconnects in real time. | |
| .DESCRIPTION | |
| Polls Get-PnpDevice every 5 seconds and reports any devices that appeared | |
| or disappeared since the last check. Useful for debugging USB, Bluetooth, | |
| and other hot-pluggable peripherals. | |
| .EXAMPLE | |
| .\monitor_usb.ps1 | |
| #> | |
| $CurrentState = $null | |
| $NewState = $null | |
| Write-Host "Monitoring device changes..." -ForegroundColor Green | |
| while ($true) { | |
| if (-not($CurrentState)) { | |
| $CurrentState = Get-PnpDevice -Status OK | |
| } | |
| else { | |
| $NewState = Get-PnpDevice -Status OK | |
| $Changes = $null | |
| $Changes = Compare-Object -ReferenceObject $CurrentState -DifferenceObject $NewState | |
| if ($Changes) { | |
| $Additions = @() | |
| $Removals = @() | |
| foreach ($Change in $Changes) { | |
| if ($Change.SideIndicator -eq "=>") { | |
| $Additions += @($Change.InputObject) | |
| } | |
| elseif ($Change.SideIndicator -eq "<=") { | |
| $Removals += @($Change.InputObject) | |
| } | |
| } | |
| if ($Additions) { | |
| Write-Host "`n[$(Get-Date -Format 'HH:mm:ss')] New devices detected:" -ForegroundColor Green | |
| Write-Output $("=" * 50) | |
| $Additions | |
| Write-Output $("=" * 50) | |
| } | |
| if ($Removals) { | |
| Write-Host "`n[$(Get-Date -Format 'HH:mm:ss')] Devices removed:" -ForegroundColor Red | |
| Write-Output $("=" * 50) | |
| $Removals | |
| Write-Output $("=" * 50) | |
| } | |
| } | |
| $CurrentState = $NewState | |
| } | |
| Start-Sleep -Seconds 5 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment