2015-11-01 38 views
0
$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 C:\test.ps1" 
$consumer.ExecutablePath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" 
$consumer.WorkingDirectory = "C:\" 
$result = $consumer.Put() 
$consumerPath = $result.Path 

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

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

上面的代码应该是当Windows检测到USB设备插入运行良好运行脚本(没有错误/警告/异常)然而在插入一个设备时,应该显示一个消息框的脚本。不。我已经测试了自己的触发脚本,对话框显示正常。PowerShell的WMI:运行没有任何错误/异常,但不执行脚本

我真的不是那么熟悉WMIS和持续性一个甚至更少,因此任何帮助都将不胜感激

回答

0

由于该事件的消费者将通过SYSTEM帐户下运行的WMI主机进程调用,你不会在自己的桌面会话中看到任何东西。

如果您改变C:\test.ps1内容写入到事件日志代替:

$LogSource = "USB Detector" 

if(-not [System.Diagnostics.EventLog]::SourceExists($LogSource)) 
{ 
    New-EventLog -LogName Application -Source $LogSource 
} 
Write-EventLog -LogName Application -Source $LogSource -EventId 100 -Message "New disk attached!" 

你会看到,它工作正常:

enter image description here

+0

这是解决方案,非常感谢:) – Deeps

相关问题