Powershell 檢測設備管理器


Get-WmiObject -Class Win32_PNPEntity 獲取設備信息

下圖為其中一個設備的詳細信息

Name存在且 PNPClass 為 $Null 的設備為其他設備(Other Devices)

Status 為 "Error" 的設備為未正常工作設備(Yellow Bang)

PNPClass 表示設備所屬類

通過比較數據的改變來檢測設備的變化

function CatchChange {
    Write-Host("Listening Device Change")
    $device=Get-WmiObject -Class Win32_PNPEntity
    $device_num=$device.Length
    while ($device_num -eq((Get-WmiObject -Class Win32_PNPEntity).Length)){

    }
    $device_Change=Get-WmiObject -Class Win32_PNPEntity
    $device_Compare=Compare-Object $device $device_Change
    Write-Host($device_Compare.InputObject.Name) 
}

檢測設備管理器,監聽設備變化

# 檢測Device Manager 
# 0     Other Devices
# 1     Error Devices (Yellow Bang)
# 2     Camera Number

function GetDevStatus {
    $Device_other = @()
    $Device_yellowbang = @()
    $CameraNum=0
    $All_List = Get-WmiObject -Class Win32_PNPEntity
    foreach ($i in $All_List) {
        if ($Null -ne $i.Name  -and $Null -eq $i.PNPClass) {
            $Device_other += ($i.Name)
        }
        if ($i.Status -eq "Error") {
            $Device_yellowbang += ($i.Name)
        }
        if ($i.PNPClass -eq "Camera"){
            $CameraNum+=1
        }
    }
    return $Device_other, $Device_yellowbang,$CameraNum
}

function CatchChange {
    Write-Host("************Listening Device Change************")
    $device=Get-WmiObject -Class Win32_PNPEntity
    $device_num=$device.Length
    while ($device_num -eq((Get-WmiObject -Class Win32_PNPEntity).Length)){

    }
    if ($device_num -gt((Get-WmiObject -Class Win32_PNPEntity).Length)){
        Write-Host("Remove Device")
    }
    else{
        Write-Host("Add Device")
    }
    $device_Change=Get-WmiObject -Class Win32_PNPEntity
    $device_Compare=Compare-Object $device $device_Change
    Write-Host($device_Compare.InputObject.Name) 
}

# CatchChange
$a = GetDevStatus
 
if ($Null -eq $a) {
    Write-Host("No Error")
}
else {
    Write-Host("************Other Devices************")
    $a[0]
    Write-Host("")
    Write-Host("************YellowBang Devices************")
    $a[1]
    Write-Host("")
    Write-Host("************Camera Num************")
    $a[2]
}
while ($True){
    CatchChange
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM