【发布时间】:2017-11-03 22:12:46
【问题描述】:
当某个事件发生时,我需要启动一个 PowerShell 脚本,并且我正在使用 WMI 类来获得持久性。我只能让它部分工作,需要一些帮助才能使其完全工作。所以,这里是什么有效,什么不...
以下代码有效,并且会在启动 calc.exe 时在后台启动 PowerShell(为了简单起见,我选择此事件只是为了测试目的)。
$fname = "testFilter"
$cname="testConsumer"
$exePath="C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
$query="SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name='calc.exe'"
$WMIEventFilter=Set-WmiInstance -Class __EventFilter -Namespace "root\subscription" -Arguments @{Name=$fname;EventNameSpace="root\cimv2";QueryLanguage="WQL";Query=$query}
$WMIEventConsumer=Set-WmiInstance -Class CommandLineEventConsumer -Namespace "root\subscription" -Arguments @{Name=$cname;ExecutablePath=$exePath}
Set-WmiInstance -Class __FilterToConsumerBinding -Namespace "root\subscription" -Arguments @{Filter=$WMIEventFilter;Consumer=$WMIEventConsumer} | out-null
但是,如果我修改 $exePath 变量以将参数传递给 powershell.exe,那么它就不再起作用(不会创建任何 powershell 进程)。
我还尝试将CommandLineEventConsumer 替换为ActiveScriptEventConsumer,并使用VBScript 启动powershell。这是修改后的代码(只有第 3 行和第 5 行不同):
$fname = "testFilter"
$cname="testConsumer"
$scriptPath="D:\Work\LaunchPowerShell.vbs"
$query="SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name='calc.exe'"
$WMIEventFilter=Set-WmiInstance -Class __EventFilter -Namespace "root\subscription" -Arguments @{Name=$fname;EventNameSpace="root\cimv2";QueryLanguage="WQL";Query=$query}
$WMIEventConsumer=Set-WmiInstance -Class ActiveScriptEventConsumer -Namespace "root\subscription" -Arguments @{Name=$cname;ScriptFileName=$scriptPath;ScriptingEngine="VBScript"}
Set-WmiInstance -Class __FilterToConsumerBinding -Namespace "root\subscription" -Arguments @{Filter=$WMIEventFilter;Consumer=$WMIEventConsumer} | out-null
还有 LaunchPowerShell.vbs:
Dim objShell : Set objShell = WScript.CreateObject("WScript.shell")
objShell.run("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe D:\Work\MyScript.ps1")
VB 脚本在从命令提示符 (cmd.exe) 启动时会按预期工作,但在触发事件时(即启动 calc.exe 时)运行 powershell 就没有运气了。即使我从 powershell 参数中删除我的脚本,它也不会运行,所以不确定是什么问题。
如果有人可以提供帮助,将不胜感激。谢谢!!!
【问题讨论】:
-
我想你想看看 CommandLineEventConsumer 类的 CommandLineTemplate 属性。您指定命令行是什么。
标签: powershell vbscript wmi