Advertisement
Neemobeer

Detect Hardware Changes

Nov 13th, 2020 (edited)
6,687
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Detects new and removed devices
  2.  
  3. $CurrentState = $null
  4. $NewState = $null
  5.  
  6. while($true) {
  7.     if(-not($CurrentState)) {
  8.         $CurrentState = Get-PnpDevice -Status OK
  9.     } else {
  10.         $NewState = Get-PnpDevice -Status OK
  11.         $Changes = $null
  12.         $Changes = Compare-Object -ReferenceObject $CurrentState -DifferenceObject $NewState
  13.         if($Changes) {
  14.             $Additions = @()
  15.             $Removals = @()
  16.             foreach($Change in $Changes) {
  17.                 if($Change.SideIndicator -eq "=>") {
  18.                     $Additions += @($Change.InputObject)
  19.                 } elseif ($Change.SideIndicator -eq "<=") {
  20.                     $Removals += @($Change.InputObject)
  21.                 }
  22.             }
  23.             if($Additions) {
  24.                 Write-Host "`n`nNew devices detected..." -ForegroundColor Green
  25.                 Write-Output $("="*50)
  26.                 $Additions
  27.                 Write-Output $("="*50)
  28.             }
  29.            
  30.             if($Removals) {
  31.                 Write-Host "`nDevices removed since last check..." - -ForegroundColor Red
  32.                 Write-Output $("="*50)
  33.                 $Removals
  34.                 Write-Output $("="*50)
  35.             }
  36.            
  37.         }
  38.         $CurrentState = $NewState
  39.     }  
  40.     Start-Sleep -Seconds 5
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement