【问题标题】:Monitor Drive. Using VB Script监控驱动器。使用 VB 脚本
【发布时间】:2013-04-13 16:06:36
【问题描述】:

我想使用 VBScript 监视驱动器的文件更改。我有下面的代码。它适用于InstanceCreationEventInstanceDeletionEvent。但是InstanceModificationEvent 没有发生。通过谷歌搜索,我知道我们需要使用CIM_DataFile 而不是CIM_DirectoryContainsFile 来监控InstanceModificationEvent。我不确定如何修改代码。谁能帮忙。

仅供参考:一个脚本应该监控驱动器中的所有文件夹和子文件夹。

PS:任何改进代码和性能的建议或其他想法也欢迎。

我的代码:

Dim arrFolders 
Dim strComputer 
Dim objWMIService 
Dim strFolder 
Dim strCommand 
Dim i 
Dim strQuery 

strChangeFile = "MonitorFolder_Log.txt"
strMailIDFile = "MonitorFolder_MailIDs.txt"

'Check if the log file exists, if not ceate a new file and exit the script. Restart the script again.
Set oFSO = CreateObject("Scripting.FileSystemObject")     
If not oFSO.FileExists(strChangeFile)  then
    'WScript.Echo "Change Log File Not Found. Creating new file..."
    Set oTxtFile = oFSO.CreateTextFile(strChangeFile)  
    WScript.Echo strChangeFile & " File Created." & vbCrLf & "Please restart the script." & vbCrLf
    WScript.Quit
End If

'Prompt for which drive should be monitored. If not a valid drive, then exit the script.
strDrive = InputBox("Enter the drive to monitor: " & vbCrLf & "E.g.: Input C to monitor C:\ drive.", "Monitor Folder - Oracle", "E")
If strDrive = "" then
    WScript.Echo "Not a valid drive. Terminating the script."
    WScript.Quit
End If

'Append ":" with the drive name.
strDrive = strDrive & ":"

'Read the mail IDs.
Set objFSOMailID = CreateObject("Scripting.FileSystemObject")
Set oTSMailID = objFSOMailID.OpenTextFile(strMailIDFile)
strMailIDsList = oTSMailID.ReadAll
oTSMailID.close
'WScript.Echo strMailIDsList

'Array to store the existing folder paths that should be monitored.
arrFolders = Array()
i = 0

Set FSO = CreateObject("Scripting.FileSystemObject")
ShowSubfolders FSO.GetFolder(strDrive)

Sub ShowSubFolders(Folder)
    For Each Subfolder in Folder.SubFolders
    i = i + 1
        folderPath = "" & Subfolder.Path & ""
    folderPath = Replace(folderPath ,"\","\\\\")
    ReDim Preserve arrFolders(i)
    arrFolders(i) = folderPath
    'Wscript.Echo i & " " & arrFolders(i)
        ShowSubFolders Subfolder
    Next
End Sub 

'Set the first path to be the drive.
arrFolders(0) = strDrive & "\\\\"

'Use WMI query to get the file changes.
strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 
'Loop throught the array of folders setting up the monitor for Each 
i = 0 
For Each strFolder In arrFolders 
   'Create the event sink 
   'WScript.Echo "setup for folder: " & strFolder & vbLf
   strCommand = "Set EventSink" & i & " = WScript.CreateObject" & "(""WbemScripting.SWbemSink"", ""SINK" & i & "_"")" 
   ExecuteGlobal strCommand
   'Setup Notification 
   strQuery = "SELECT * " _
           & "FROM __InstanceOperationEvent " _
           & "WITHIN 1 " _
           & "WHERE Targetinstance ISA 'CIM_DirectoryContainsFile'" _
           & "  AND TargetInstance.GroupComponent = " & "'Win32_Directory.Name=""" & strFolder & """'"
   strCommand = "objWMIservice.ExecNotificationQueryAsync EventSink" & i & ", strQuery"
   ExecuteGlobal strCommand 
   'Create the OnObjectReady Sub 
   strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " &  "objAsyncContext)" & vbLf _
             & "  'Wscript.Echo objObject.TargetInstance.PartComponent" & vbLf _
             & "  SendNotification(objObject)" & vbLf _
             & "End Sub"
   'WScript.Echo strCommand 
   ExecuteGlobal strCommand 
   i = i + 1 
Next 

'Wait for events.
WScript.Echo "Waiting for events..." 
i = 0 
While (True) 
   Wscript.Sleep(1000) 
Wend


Function SendNotification(objObject)

    strEventType = objObject.Path_.Class
    strPartComp = Split(objObject.TargetInstance.PartComponent, "=")
    strFileName = Replace(strPartComp(1), "\\", "\")

    WScript.Echo strEventType
    WScript.Echo strFileName

    'Some more code to send mail and logs...

End Function

【问题讨论】:

  • 不要使用“C”盘。由于有很多文件夹,你会得到 Index Out Of Bounds 和其他异常。在 USB 设备中尝试。
  • 监控驱动器中的所有文件夹和子文件夹以了解什么
  • 如果有人创建了新的文档/文件,应该向用户列表发送通知邮件。

标签: scripting vbscript wmi wmi-query wmi-service


【解决方案1】:

监视整个文件系统以创建文件是不可行的。它会占用系统资源并可能严重影响系统运行。只监视选定的文件夹。以下应该有效:

Const Interval = 1

Set monitor = CreateMonitor("C:\foo")
Do
  Set evt = monitor.NextEvent()
  Select Case evt.Path_.Class
    Case "__InstanceCreationEvent"     : SendNotification evt.TargetInstance
    Case "__InstanceModificationEvent" : ...
    Case "__InstanceDeletionEvent"     : ...
  End Select
Loop

Function CreateMonitor(path)
  Set wmi = GetObject("winmgmts://./root/cimv2")
  Set fso = CreateObject("Scripting.FileSystemObject")

  path = Split(fso.GetAbsolutePathName(path), ":")
  drv  = path(0) & ":"
  dir  = Replace(path(1), "\", "\\")
  If Right(dir, 2) <> "\\" Then dir = dir & "\\"

  query = "SELECT * FROM __InstanceOperationEvent" & _
          " WITHIN " & Interval & _
          " WHERE Targetinstance ISA 'CIM_DataFile'" & _
          " AND TargetInstance.Drive='" & drv & "'" & _
          " AND TargetInstance.Path='" & dir & "'"
  Set CreateMonitor = wmi.ExecNotificationQuery(query)
End Function

Sub SendNotification(tgtInst)
  'send notification
End Sub

您应该将不同文件夹的监视器作为单独的进程运行,因为NextEvent() 是一个阻塞操作。

【讨论】:

  • 我同意。但这是我的要求。你能帮我解决实际问题吗?如何监控文件中的内容变化,即:如果文本文件被修改,则必须引发修改事件。
  • 查看更新的答案。上面的代码在我测试时运行良好。如果它没有捕捉到__InstanceModificationEvent,你必须找出为什么没有引发事件。请注意,该脚本仅检查给定文件夹的事件。它不会检测子文件夹中的更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-16
相关资源
最近更新 更多