如何调试/注册在文件创建时运行脚本的永久性WMI事件 [英] How to Debug/Register a Permanent WMI Event Which Runs a Script on File Creation

查看:56
本文介绍了如何调试/注册在文件创建时运行脚本的永久性WMI事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在机器上注册一个永久性的WMI事件,如果在文件夹 C:\ test 中创建了文件,则应运行一个脚本.

I am trying to register a permanent WMI event on my machine, where if a file is created in the folder C:\test, a script should run.

我已经成功地注册了类似的事件,其中的动作是将一行记录到文件中,但是由于某些原因,当尝试执行脚本时,我没有任何反应.

I have successfully managed to register similar events where the action is to log a line to a file, but for some reason when trying to execute a script I just get no response.

这是我正在使用的查询:

Here is the query I am using:

$query=@"
Select * from __InstanceCreationEvent within 10
where targetInstance isa 'Cim_DirectoryContainsFile'
and targetInstance.GroupComponent='Win32_Directory.Name="C:\\\\test"'
"@

我尝试以几种不同的方式注册该活动,但均未成功,并希望有人可以帮助我了解我要去哪里.

I have tried registering the event in a few different ways with no success, and was hoping someone could help me understand where I am going wrong.

以下面的脚本为例:

$computer = $env:COMPUTERNAME
$filterNS = "root\cimv2"
$wmiNS = "root\subscription"
$query = @"
Select * from __InstanceCreationEvent within 1
where targetInstance isa 'Cim_DirectoryContainsFile' 
and targetInstance.GroupComponent = 'Win32_Directory.Name="c:\\\\test"'
"@
$filterName = "NewFileFilter"
$scriptFileName = "C:\test\test.vbs"

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

$consumerPath = Set-WmiInstance -Class ActiveScriptEventConsumer `
    -ComputerName $computer -Namespace $wmiNS `
    -Arguments @{name="MyConsumer"; ScriptFileName=$scriptFileName;
    ScriptingEngine="VBScript"}

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

其中 test.vbs 是单行代码: MsgBox("Hello!")

运行此命令后,我可以调用以下命令:

After running this, I can call the following:

Get-WmiObject -Namespace root\Subscription -Class __Eventfilter

Get-WMIObject -Namespace root\Subscription -Class __EventConsumer

Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding

并获得以下输出,向我显示该事件确实已经注册:

And get the below output, which shows me that the event has indeed been registered:

__GENUS          : 2
__CLASS          : __EventFilter
__SUPERCLASS     : __IndicationRelated
__DYNASTY        : __SystemClass
__RELPATH        : __EventFilter.Name="NewFileFilter"
__PROPERTY_COUNT : 6
__DERIVATION     : {__IndicationRelated, __SystemClass}
__SERVER         : WIN7-IT3
__NAMESPACE      : ROOT\Subscription
__PATH           : \\WIN7-IT3\ROOT\Subscription:__EventFilter.Name="NewFileFilter"
CreatorSID       : {1, 5, 0, 0...}
EventAccess      : 
EventNamespace   : root\cimv2
Name             : NewFileFilter
Query            : Select * from __InstanceCreationEvent within 1
                   where targetInstance isa 'Cim_DirectoryContainsFile' 
                   and targetInstance.GroupComponent = 
                   'Win32_Directory.Name="c:\\\\test"'
QueryLanguage    : WQL
PSComputerName   : WIN7-IT3

__GENUS          : 2
__CLASS          : ActiveScriptEventConsumer
__SUPERCLASS     : __EventConsumer
__DYNASTY        : __SystemClass
__RELPATH        : ActiveScriptEventConsumer.Name="MyConsumer"
__PROPERTY_COUNT : 8
__DERIVATION     : {__EventConsumer, __IndicationRelated, __SystemClass}
__SERVER         : WIN7-IT3
__NAMESPACE      : ROOT\Subscription
__PATH           : \\WIN7-IT3\ROOT\Subscription:ActiveScriptEventConsumer.Name="MyCon
                   sumer"
CreatorSID       : {1, 5, 0, 0...}
KillTimeout      : 0
MachineName      : 
MaximumQueueSize : 
Name             : MyConsumer
ScriptFilename   : C:\test\test.vbs
ScriptingEngine  : VBScript
ScriptText       : 
PSComputerName   : WIN7-IT3

__GENUS                 : 2
__CLASS                 : __FilterToConsumerBinding
__SUPERCLASS            : __IndicationRelated
__DYNASTY               : __SystemClass
__RELPATH               : __FilterToConsumerBinding.Consumer="ActiveScriptEventConsum
                          er.Name=\"MyConsumer\"",Filter="__EventFilter.Name=\"NewFil
                          eFilter\""
__PROPERTY_COUNT        : 7
__DERIVATION            : {__IndicationRelated, __SystemClass}
__SERVER                : WIN7-IT3
__NAMESPACE             : ROOT\Subscription
__PATH                  : \\WIN7-IT3\ROOT\Subscription:__FilterToConsumerBinding.Cons
                          umer="ActiveScriptEventConsumer.Name=\"MyConsumer\"",Filter
                          ="__EventFilter.Name=\"NewFileFilter\""
Consumer                : ActiveScriptEventConsumer.Name="MyConsumer"
CreatorSID              : {1, 5, 0, 0...}
DeliverSynchronously    : False
DeliveryQoS             : 
Filter                  : __EventFilter.Name="NewFileFilter"
MaintainSecurityContext : False
SlowDownProviders       : False
PSComputerName          : WIN7-IT3

但是,当我在 C:\ test 中创建文件时,没有任何反应.关于此问题,最令人沮丧的是,我可以创建一个使用 LogFileEventConsumer 的类似事件,并且可以正常运行(将新文件添加到 C时,会将行记录到指定文件中:\ test ).

However, when I create a file in C:\test, nothing happens. The most frustrating this about this, is that I can create a similar event which uses the LogFileEventConsumer and this works perfectly (a line is logged to the specified file when a new file is added to C:\test).

有人知道这里发生了什么吗,或者我怎样才能有效地调试它?我还没有找到任何方式来绑定到某种程度上的输出错误或记录任何有关正在发生的事情的详细信息,并且还无法弄清CIM WMI Studio的意图(它似乎不起作用)完全对我来说).

Does anyone know what is going on here, or how I can debug this effectively? I have not found any way to get the binding to somehow output errors or log any kind of details about what is going on, and have not been able to work out what CIM WMI Studio is meant to do (it doesn't seem to work at all for me).

我们非常感谢您的帮助,请让我知道是否可以发布更多详细信息,例如我尝试过的其他任何代码或任何日志-谢谢.

Any help is much appreciated, and please let me know if I can post any more details like any other code I have tried or any logs - thanks.

推荐答案

我能够使用以下脚本实现此目标:

I was able to achieve this using the following script :

$query = @"
SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA "Cim_DirectoryContainsFile" AND TargetInstance.GroupComponent="Win32_Directory.Name='C:\\test'"
"@

#Set up hash table for splatting
$wmiParams = @{
    Computername = $env:COMPUTERNAME
    ErrorAction = 'Stop'
    NameSpace = 'root\subscription'
}

# Filter
#Creating a new event filter
$wmiParams.Class = '__EventFilter'
$wmiParams.Arguments = @{
    Name = 'WatchFiles'
    EventNamespace = 'root\CIMV2'
    QueryLanguage = 'WQL'
    Query = $query 
}
$filterResult = Set-WmiInstance @wmiParams

# Consumer
$wmiParams.Class = 'ActiveScriptEventConsumer'
$wmiParams.Arguments = @{
    KillTimeout = 0
    MachineName = $env:COMPUTERNAME
    ScriptingEngine = 'VBScript'
    ScriptText = 
@"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("c:\test\Log.log", 8, True)
objFile.WriteLine "hellohellohellohellohellohello"
objFile.Close
"@
    ScriptFileName = $null
    Name = 'ActiveScriptEventConsumer'
}
$consumerResult = Set-WmiInstance @wmiParams

# Binding
$wmiParams.Class = '__FilterToConsumerBinding'
$wmiParams.Arguments = @{
    Filter = $filterResult
    Consumer = $consumerResult
}
$bindingResult = Set-WmiInstance @wmiParams

请注意我格式化 $ query 过滤器的方式,并且由于 Here-String ( @" @@ )我使用过.

Notice the way I have formatted the $query filter, and that the only character that needs escaping is the \, due to the Here-String (@""@) I used.

此处的更多注意事项:

在创建要与ActiveScriptEventCosumer一起使用的VBScript或JScript脚本时,您需要了解一些限制:

When creating VBScript or JScript scripts to use with ActiveScriptEventCosumer, you need to be aware of some limitations:

•ActiveScriptEventConsumer不使用Windows脚本宿主(WSH),该脚本宿主广泛用于系统管理脚本中.这意味着您不能使用WScript对象或其任何属性和方法(例如WScript.CreateObject,WScript.Sleep等).

•ActiveScriptEventConsumer doesn't use the Windows Script Host (WSH), which is widely used in system administration scripts. This means that you can not use the WScript object or any of its properties and methods (like WScript.CreateObject, WScript.Sleep etc.).

•该脚本无法生成任何屏幕输出,这意味着您无法使用VBScript MsgBox函数.

•The script can not generate any screen output, which means that you can not use the VBScript MsgBox function.

•该脚本没有网络访问权限.

•The script does not have network access.

•该脚本不能使用任何用户特定的数据,例如环境变量或网络共享.

•The script can't use any user specific data, such as environment variables or network shares.

这可以解释上述失败,因为我所指的脚本包含一个 MsgBox(),在这种情况下无法运行.

This could explain the above failure, as the script I was referring to contained a MsgBox(), which cannot run in these circusmtances.

这篇关于如何调试/注册在文件创建时运行脚本的永久性WMI事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆