Created
May 24, 2023 18:19
-
-
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
$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 "`nNew devices detected:" -ForegroundColor Green | |
Write-Output $("=" * 50) | |
$Additions | |
Write-Output $("=" * 50) | |
} | |
if ($Removals) { | |
Write-Host "`nDevices removed since last check:" - -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