永久WMI事件消费者没有被触发,临时确实

时间:2014-11-24 15:06:26

标签: windows events powershell wmi

我正在尝试创建永久WMI事件订阅,以便在USB驱动器连接时运行脚本。

以下是我创建Filter,Consumer和绑定的方法:

$computer = "xxx"
$filterNS = "root\cimv2"
$wmiNS = "root\subscription"
$query = "Select * from __InstanceCreationEvent within 5 where targetinstance isa 'win32_logicaldisk'"

$filterName = "TestFilter"

$filterPath = Set-WmiInstance -Class __EventFilter `
 -ComputerName $computer -Namespace $wmiNS -Arguments `
  @{name=$filterName; EventNameSpace=$filterNS; QueryLanguage="WQL";
    Query=$query}

$consumerPath = Set-WmiInstance -Class CommandLineEventConsumer `
 -ComputerName $computer -Namespace $wmiNS `
 -Arguments @{
 name="TestConsumer"; 
 ExecutablePath= "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
 CommandLineTemplate = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -executionpolicy bypass -file D:\\reassignDriveletter.ps1"
 }

Set-WmiInstance -Class __FilterToConsumerBinding -ComputerName $computer `
  -Namespace $wmiNS -arguments @{Filter=$filterPath; Consumer=$consumerPath} |
  out-null

创建的所有内容都没有错误,我可以在WMI事件查看器中看到过滤器,使用者和绑定,但如果我连接USB驱动器没有任何反应(脚本的第一行写入日志条目,这就是我所知道的。)

出于测试目的,我创建了一个正常的事件订阅:

$job = Register-WmiEvent -Query "Select * from __InstanceCreationEvent within 5 where targetinstance isa 'win32_logicaldisk'" -SourceIdentifier usb -Timeout 1000 -Action $scriptblock

绝对正常。

我错过了一些明显的东西吗?我将不胜感激任何帮助。

此致

更新:刚刚在非域名加入的Win7计算机上测试,相同的代码工作正常。 (我的工作站是Win8.1域加入记录)。我将测试目标系统并报告回来。

1 个答案:

答案 0 :(得分:1)

好的,经过几天的反复试验,我最终调整/使用了here找到的其他方法。

每次USB连接时,这将启动存储在D:\ scripts中的脚本,并且它是永久性的。

$filter = ([wmiclass]"\\.\root\subscription:__EventFilter").CreateInstance()

$filter.QueryLanguage = "WQL"
$filter.Query = "Select * from __InstanceCreationEvent within 5 where targetinstance isa 'win32_logicaldisk'"
$filter.Name = "USBFilter"
$filter.EventNamespace = 'root\cimv2'

$result = $filter.Put()
$filterPath = $result.Path

$consumer = ([wmiclass]"\\.\root\subscription:CommandLineEventConsumer").CreateInstance()
$consumer.Name = 'USBConsumer'
$consumer.CommandLineTemplate = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe –ExecutionPolicy Bypass -file D:\scripts\reassignDriveletter.ps1"
$consumer.ExecutablePath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
$consumer.WorkingDirectory = "D:\scripts"
$result = $consumer.Put()
$consumerPath = $result.Path

$bind = ([wmiclass]"\\.\root\subscription:__FilterToConsumerBinding").CreateInstance()

$bind.Filter = $filterPath
$bind.Consumer = $consumerPath
$result = $bind.Put()
$bindPath = $result.Path

要删除这些Perma事件,请执行以下操作:

([wmi]$filterPath).Delete()
([wmi]$consumerPath).Delete()
([wmi]$bindPath).Delete()

我的测试脚本每次插入USB驱动器时都会创建一个文件夹,所以我可以对它进行测试并且有效。

我正在运行Windows 8.1顺便说一句。