2015-11-01 66 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

相關問題