如何使用PowerShell只获取一个设备事件?

时间:2017-10-05 10:29:47

标签: powershell

我使用下面提到的代码来获取USB设备检测。但我得到三个设备检测,而不是一个。

Register-WMIEvent -Query "SELECT * FROM Win32_DeviceChangeEvent 
    WITHIN 1 WHERE EventType = 2" -Action { Write-Host "Device detected"}

意外输出 enter image description here

我想在插入USB时进行单次检测。

请指导我..

1 个答案:

答案 0 :(得分:0)

当我理解你的问题时,你的搜索是这样的:

#Get all USB Device(This is your query)
$Devices = Register-WMIEvent -Query "SELECT * FROM Win32_DeviceChangeEvent WITHIN 1 WHERE EventType = 2"
#Check if the devices variable empty or not
if(-not [String]::IsNullOrEmpty($Devices)){
    #Will be printed when one or more usb devices are connected
    Write-Host "Device detected"
}