Monitor Drive. Using VB Script

前端 未结 1 1147
清酒与你
清酒与你 2020-12-04 02:53

I want to monitor a drive for file changes, using VBScript. I have the below code. It works fine for InstanceCreationEvent and InstanceDeletionEvent

相关标签:
1条回答
  • 2020-12-04 03:32

    Monitoring the entire filesystem for file creation is not feasible. It will eat up system resources and might severly affect system operation. Only ever monitor selected folders. The following should work:

    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
    

    You should run monitors for different folders as separate processes, because NextEvent() is a blocking operation.

    0 讨论(0)
提交回复
热议问题