Skip to content

Instantly share code, notes, and snippets.

@ericchansen
Created May 24, 2023 18:19
Show Gist options
  • Save ericchansen/68485e96f8c17abf388cb4a58ebe5ef3 to your computer and use it in GitHub Desktop.
Save ericchansen/68485e96f8c17abf388cb4a58ebe5ef3 to your computer and use it in GitHub Desktop.
PowerShell script to monitor device connects and disconnects on Windows.
$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