当某个事件发生时,我需要启动PowerShell脚本,并且我正在使用WMI类来获取持久性。我只能部分工作,并且需要一些帮助才能使其充分发挥作用。所以,这里是什么工作,什么不...WMI事件订阅和PowerShell执行
下面的代码工作,并将启动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](https://msdn.microsoft.com/en-us/library/aa389231(v = vs.85).aspx)类的CommandLineTemplate属性。您可以指定命令行的内容。 –