在单引号WMI查询中插入VBS变量

时间:2010-06-15 06:32:53

标签: vbscript

我对以下片段感到非常沮丧:

Dim objFSO, varSrc, varDest, varExt

Set objFSO = CreateObject("Scripting.FileSystemObject")

varSrc = WScript.Arguments(0)
varDest = WScript.Arguments(1)
varExt = WScript.Arguments(2)

If objFSO.FolderExists(varSrc) Then
    WScript.Echo varSrc
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
        ("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _
            & "Targetinstance ISA 'CIM_DirectoryContainsFile' AND " _
                & "TargetInstance.GroupComponent= " _
                    & "'Win32_Directory.Name=""c:\\\\kk ""'")
    Do
        Set objLatestEvent = colMonitoredEvents.NextEvent
        WScript.Echo objLatestEvent.TargetInstance.PartComponent
    Loop
Else
    WScript.Echo "Bazinga"
End If

我尝试用varSrc替换c:\\ kk但是WSH似乎无法在WMI查询中识别它 - 更不用说它在单引号内了!

我尝试过chr(34)并且没有用。请尽可能帮助。非常感谢!

更新

非常感谢你的回答和道歉的道歉。

varSrc应该是“C:\\\\kk”。并且WMI查询无法识别它。让我举例说明:

应该解析查询:

SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' AND TargetInstance.GroupComponent= 'Win32_Directory.Name= ""c:\\\\KK""'

我已经测试了上面的查询,但它确实有效!但是我需要的是用来自用户输入的参数替换c:\\\\kk,在这种情况下,参数是varSrc。我遇到的问题是语法是正确的,但WMI查询将varSrc字面上称为“Directory.Name”;或者另一种方式 - 语法错误或不可解析的查询。

如果查询是:

("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _
            & "Targetinstance ISA 'CIM_DirectoryContainsFile' AND " _
                & "TargetInstance.GroupComponent= " _
                    & "'Win32_Directory.Name=""varSrc""'")

脚本将在没有任何错误的情况下运行,但是它不会监视新创建的文件。因为它将'Directory.Name'解析为文字'varSrc'而不是用户输入参数。

如果查询是:

Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
    ("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _
        & "Targetinstance ISA 'CIM_DirectoryContainsFile' AND " _
            & "TargetInstance.GroupComponent= " _
                & "'Win32_Directory.Name="""""&varSrc&"""""'")

会产生错误:

vmove.vbs(15, 2) SWbemServicesEx: Invalid query

2 个答案:

答案 0 :(得分:1)

最有可能的是,varSrc包含带有单个反斜杠的文件夹路径,而您的WMI查询需要四个反斜杠作为路径分隔符。在将\插入查询之前尝试将\\\\替换为varSrc,如下所示:

varSrc = Replace(varSrc, "\", "\\")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
    ("SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE " _
        & "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _
            & "TargetInstance.GroupComponent= " _
                & "'Win32_Directory.Name=""" & varSrc & """'")

答案 1 :(得分:1)

PLS。 chk下面的脚本,

varSrc = Replace(varSrc, "\", "\\")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE " _
    & "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _
        & "TargetInstance.GroupComponent= " _
            & "Win32_Directory.Name=" & "'" & varSrc & "'")