【发布时间】:2020-01-10 23:51:39
【问题描述】:
我想在插入特定 USB 设备时触发脚本,我研究了 Register-WmiEvent,但我真的很困惑如何正确处理它。
到目前为止,我已经成功地隔离了设备:
Get-WmiObject win32_PNPEntity | where {$_.Caption -eq "Lexar USB Flash Drive USB Device"}
这是返回的 WMI 对象:
_GENUS : 2
__CLASS : Win32_PnPEntity
__SUPERCLASS : CIM_LogicalDevice
__DYNASTY : CIM_ManagedSystemElement
__RELPATH : Win32_PnPEntity.DeviceID="USBSTOR\\DISK&VEN_LEXAR&PROD_USB_FLASH_DRIVE&REV_1100\\AAEDZZ5RVJ47QS4K&0"
__PROPERTY_COUNT : 26
__DERIVATION : {CIM_LogicalDevice, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER : P7409
__NAMESPACE : root\cimv2
__PATH : \\P7409\root\cimv2:Win32_PnPEntity.DeviceID="USBSTOR\\DISK&VEN_LEXAR&PROD_USB_FLASH_DRIVE&REV_1100\\AAEDZZ5RVJ47QS4K&0"
Availability :
Caption : Lexar USB Flash Drive USB Device
ClassGuid : {4d36e967-e325-11ce-bfc1-08002be10318}
CompatibleID : {USBSTOR\Disk, USBSTOR\RAW, GenDisk}
ConfigManagerErrorCode : 0
ConfigManagerUserConfig : False
CreationClassName : Win32_PnPEntity
Description : Lecteur de disque
DeviceID : USBSTOR\DISK&VEN_LEXAR&PROD_USB_FLASH_DRIVE&REV_1100\AAEDZZ5RVJ47QS4K&0
ErrorCleared :
ErrorDescription :
HardwareID : {USBSTOR\DiskLexar___USB_Flash_Drive_1100, USBSTOR\DiskLexar___USB_Flash_Drive_, USBSTOR\DiskLexar___, USBSTOR\Lexar___USB_Flash_Drive_1...}
InstallDate :
LastErrorCode :
Manufacturer : (Lecteurs de disque standard)
Name : Lexar USB Flash Drive USB Device
PNPClass : DiskDrive
PNPDeviceID : USBSTOR\DISK&VEN_LEXAR&PROD_USB_FLASH_DRIVE&REV_1100\AAEDZZ5RVJ47QS4K&0
PowerManagementCapabilities :
PowerManagementSupported :
Present : True
Service : disk
Status : OK
StatusInfo :
SystemCreationClassName : Win32_ComputerSystem
SystemName : P7409
PSComputerName : P7409
我应该如何处理事件部分?
有没有办法编写它,使其像 “当包含该 Caption 的实例存在时......这样做”?
我正在尝试:
$query = "Select * FROM __InstanceModificationEvent WITHIN 1 WHERE TargetInstance ISA 'win32_PNPEntity' and TargetInstance.Caption = 'Lexar USB Flash Drive USB Device'"
Register-WMIEvent -Query $query -Action { Write-Host "LEXAR FLASH DRIVE CONNECTED"} -SourceIdentifier TEST
但是当我插入/拔出它时没有任何反应。
我尝试过:
$query = "SELECT * FROM win32_DeviceChangeEvent"
Register-WMIEvent -Query $query -Action {Write-Host "ALERT"}
这项工作,但它会在任何设备连接/断开时触发。我希望能够仅使用 Lexar 标题隔离该设备。
非常感谢。
【问题讨论】:
-
关于这个主题的信息足够多。在 Google 上搜索“Powershell WMI 事件”会得到 345K 的结果。请进行更多研究,并尝试在查看文档后根据遇到的问题编辑您的问题
-
我添加了更多信息,你是对的。
标签: powershell wmi