如何将 "new pnp devices" 事件记录到 Windows 上的控制台?

How to log "new pnp devices" events to console on Windows?

我想写一些类似 nestat 的东西(将新的 tcp 连接记录到控制台)但是对于带有 powershell 的 pnp 设备。

是否有特定于 PnP 的 API 方法“订阅某种事件总线”并获取“连接”和“断开”事件?

或者实现此目的的唯一方法是使用 Get-PnpDevice 循环并“手动”搜索差异?

您可以使用 WMI 事件来执行此操作。例如,这是一种方法(似乎过于复杂,所以也许有人可以改进它):

$addIdentifier = "WMI.PnpAddEvent"
$removeIdentifier = "WMI.PnpRemoveEvent"

$addAction = { $pnpEntity = $EventArgs.NewEvent.TargetInstance; Write-Host "`nPNPEvent: Plugged In`nCaption: $($pnpEntity.Caption)`nPNPDeviceID: $($pnpEntity.PNPDeviceID)`n" }
$addQuery = "SELECT * FROM __instancecreationevent WITHIN 5 WHERE targetinstance isa 'Win32_PnPEntity'"

$removeAction = { $pnpEntity = $EventArgs.NewEvent.TargetInstance; Write-Host "`nPNPEvent: Unplugged`nCaption: $($pnpEntity.Caption)`nPNPDeviceID: $($pnpEntity.PNPDeviceID)`n" }
$removeQuery = "SELECT * FROM __instancedeletionevent WITHIN 5 WHERE targetinstance isa 'Win32_PnPEntity'"

$addEventArgs = @{
    Query            = $addQuery
    SourceIdentifier = $addIdentifier
    SupportEvent     = $true
    Action           = $addAction
}

$removeEventArgs = @{
    Query            = $removeQuery
    SourceIdentifier = $removeIdentifier
    SupportEvent     = $true
    Action           = $removeAction
}

Register-WmiEvent @addEventArgs
Register-WmiEvent @removeEventArgs

现在,当您 add/remove 一个设备时,您将在控制台中得到如下输出:

PNPEvent: Unplugged
Caption: Apple iPhone
PNPDeviceID: USB\VID_05AC&PID_12A8&MI_00\E&2491F388&0&0000    

PNPEvent: Plugged In
Caption: Apple iPhone
PNPDeviceID: USB\VID_05AC&PID_12A8&MI_00\E&2491F388&0&0000

有几件事要记住:

  • 本届活动报名截止
  • 您需要从提升的提示
  • 运行

如前所述,会话结束时应取消注册,但如果您想手动取消,可以这样做:

$addIdentifier, $removeIdentifier | ForEach-Object { Unregister-Event -Force -SourceIdentifier $_ }