如何通过vbs监控文件夹中的文件

3

有人能帮我看看我的错误吗? 这个脚本是用于监视文件夹创建、删除或修改文本文件的。

sPath = "C:\scripts\test"
sComputer = "."
sDrive = split(sPath,":")(0)
sFolders1 = split(sPath,":")(1)
sFolders = REPLACE(sFolders1, "\", "\\") & "\\"

Set objWMIService = GetObject("winmgmts:\\" & sComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceOperationEvent WITHIN 1 WHERE " _
& "TargetInstance ISA 'CIM_DataFile' AND " _
& "TargetInstance.Drive='" & sDrive & "' AND " _
& "TargetInstance.Path='" & sFolders & "' AND " _
& "TargetInstance.Extension = 'txt' ")

Wscript.Echo vbCrlf & Now & vbTab & _
"Begin Monitoring for a Folder " & sDrive & ":" & sFolders1 & " Change Event..." & vbCrlf

Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
    Select Case objLatestEvent.Path_.Class

    Case "__InstanceCreationEvent"
    WScript.Echo Now & vbTab & objLatestEvent.TargetInstance.FileName & "." & objLatestEvent.TargetInstance.Extension _
    & " was created" & vbCrlf

    Case "__InstanceDeletionEvent"
    WScript.Echo Now & vbTab & objLatestEvent.TargetInstance.FileName & "." & objLatestEvent.TargetInstance.Extension _
    & " was deleted" & vbCrlf

    Case "__InstanceModificationEvent"
    If objLatestEvent.TargetInstance.LastModified <> _
    objLatestEvent.PreviousInstance.LastModified then
    WScript.Echo Now & vbTab & objLatestEvent.TargetInstance.FileName & "." & objLatestEvent.TargetInstance.Extension _
    & " was modified" & vbCrlf
    End If
    End Select
Loop

Set objWMIService = nothing
Set colMonitoredEvents = nothing
Set objLatestEvent = nothing

当我写下这段代码时,它可以完美运行。

sPath = "\\ComputerName\C$\scripts\test"

代替

sPath = "C:\scripts\test"

Thank you....


我没有看到任何问题。你用的是哪个版本的Windows?你是否以管理员身份运行此程序? - Nilpo
1个回答

4
如果您在谷歌上搜索 "WMI TargetInstance.Drive",会发现驱动器字母需要带冒号。查询语句如下:
SELECT * FROM __InstanceOperationEvent WITHIN 1 WHERE TargetInstance ISA 'CIM_DataFile' AND TargetInstance.Drive='E:' AND TargetInstance.Path='\\trials\\SoTrials\\answers\\10041057\\data\\' AND TargetInstance.Extension = 'txt'

正常工作。

哇,太棒了。我没看到那个。 - Nilpo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接