10 December 2012

How to monitor a folder and trigger an action for incoming files, in Windows 7


Step 1:

Copy a file into a folder and look for the details of this event in windows event viewer. For example, if  copy a file named test - Copy.txt in C:\_QVW\PDFfolder\WatchThis folder, I found the following entry in the windows event viewer:


Make note of the event id (4656) and keyword (Audit Success) and that we are looking at security windows logs.


Step 2:
Go to the windows task scheduler and click on create task.

Step 2.1:
In general tab, name your trigger as My Folder Monitor as follows:

Step 2.2:
In triggers tab, click on New. In New Trigger window, set begin the task to On an event and select custom in settings, then click on New Event Filter button. In New Event Filter window, set the options as follows:
Note that we set the options according to what we have found in step 1.
Click OK and OK to finish this step.

Step 2.3:
In the action tabs, click on New. In the New Action window, set the options as follows:
Click OK and OK to finish this step.

Step 3:
Now, we need to tell the task which folder to monitor. 

Step 3.1:
Go back to the windows event that we looked at in step 1. Open the event details by double clicking the event and take note of the details of the event. We can use ObjectName and ProcessName details which are under the EventData node to fine tune our scheduled task.

Step 3.2:
Go to triggers tab of the scheduled task and click on Edit and then edit event filter. Note that, it is opened in XML tab and one cannot go back to Filter tab. From now on, the event filter can only be modified in XML. 
Modify the XML expression to restrict the scheduled task to trigger the action only for the files in C:\_QVW\PDFfolder\WatchThis folder, as follows:
Please note that > means > (i.e greater than).


Now if you copy & paste or create a file in C:\_QVW\PDFfolder\WatchThis folder, a pop-up message should appear in the screen.


Hope it works on your side as well.

19 comments:

  1. I am stumped on step 1!

    I found that no matter where I copied a file there were no new Events logged.
    I am looking in Windows Logs > Security
    I tried running Computer Management as Administrator. No Change.

    Please let me know if I need to enable some other service or something as well.
    Win 7 Pro

    Thanks

    ReplyDelete
    Replies
    1. still interested but found a .vbs way around this

      Delete
  2. Yes it looks like, you need to enable/setup some options, please see the following:
    http://technet.microsoft.com/en-us/library/cc727935%28v=ws.10%29.aspx

    What is your .vbs workaround?

    ReplyDelete
    Replies
    1. Thanks for the link!
      That led me to Applying Audit Policy (Advanced Section of the Security tab on the folder's properties) and also Defining Audit Policy. It is Audit object access which is required.
      This allowed me to complete this exercise, but, presents another problem

      Scheduled tasks has limited options for action types: Start a Program, Send an Email, or Display a Message.
      So I am left writing a different script to accomplish the file copy which was my original intent.
      I'm not sure if you can pass variables from the event through as arguments.
      I will have to look into that later.

      For now the .vbs is tested and seems to be working OK.

      ' FOLDER TO MONITOR
      strWFolder = "X:\SomeFolder\ToWatch"
      strCFolder = "Y:\SomeFolder\ToCopy\FileTo"

      ' FREQUENCY TO CHECK IT, IN SECONDS
      nFrequency = 900

      strComputer = "."
      strQueryFolder = Replace(strWFolder, "\", "\\\\")
      Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
      Set colMonitoredEvents = objWMIService.ExecNotificationQuery ("SELECT * FROM __InstanceCreationEvent WITHIN " & nFrequency & " WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent='Win32_Directory.Name=""" & strQueryFolder & """'")

      Do
      Set objLatestEvent = colMonitoredEvents.NextEvent
      strNewFile = objLatestEvent.TargetInstance.PartComponent
      arrNewFile = Split(strNewFile, "=")
      strFilePath = arrNewFile(1)
      strFilePath = Replace(strFilePath, "\\", "\")
      strFilePath = Replace(strFilePath, Chr(34), "")
      strFileName = Replace(strFilePath, strFolder, "")
      strTempFilePath = WScript.CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "\TEMP.M4A"

      ' DO THE OPERATION STUFF
      arrFileName = Split(strFileName, "\")
      strlastOne = arrFileName(3) ' sloppily grab last element of known array length
      strDestFile = strCFolder & "\" & strlastOne
      Call CopyFile(strFileName, strDestFile)

      ' ...
      Loop

      Sub CopyFile(SourceFile, DestinationFile)

      Set fso = CreateObject("Scripting.FileSystemObject")

      'Wait approximate time - 15 minutes - before copy
      WScript.Sleep(900000)

      'Copy the file
      fso.CopyFile SourceFile, DestinationFile, True

      If wasReadOnly Then
      'Reapply the read-only attribute
      fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
      End If

      Set fso = Nothing

      End Sub

      Delete
  3. Your scheduler trick works great for me except that the lines that you hilighted in your last pic seem to be ignored. I'm running on a Windows server 2012.

    These are the lines that I added but they don't seem to have any effect.

    and *[EventData[Data[@Name='ObjectName'] and (Data>='E:\Auditing')]]
    and *[EventData[Data[@Name='ProcessName'] and (Data='C:\Windows\explorer.exe')]]
    and *[EventData[Data[@Name='SubjectUserName'] and (Data!='BATEST01$')]]


    Any ideas?

    Jeff

    ReplyDelete
    Replies
    1. Unfortunately I do not have access to any windows server 2012 environment to try it out.
      Have you tried it without the last line, i.e. "and *[EventData[Data[@Name='SubjectUserName'] and (Data!='BATEST01$')]]
      "?

      Delete
  4. Thank you for the quick reply. Yes, I tried it with only the *[EventData[Data[@Name='ObjectName'] and (Data>='E:\Auditing')] line and it is also ignored. The code is accepted, no error message but not executed. Seem that all the EventData lines are being ignored. (BTW, this site is changing my '>' to '>')

    When I got auditing to work, set Audit Object Access to success in the local policy and turned on auditing for create files/write data on one folder and subfolders, there was a lot of 4656 codes in the log that were unrelated to writing files to this folder. So, the code in the Task Scheduler script had to do the filtering for me. Unfortunately, it didn't.

    I'm really beginning to hate computers. Just when you think you have them figured out, they do what they want.

    ReplyDelete
  5. I am using Window 7 Enterprise and I don't see 'Object Details' in Event Viewer when I select any event, I don't see Object Name with folder path and file I copied. Please let me know if something is wrong on my side. I can see new event when I copy file but information in your screenshot is not relevant with what I see.

    I am seeing below details.

    Subject:
    Security ID: domain name\username
    Account Name: username
    Account Domain: domain name
    Logon ID: 0x5df92

    Process Information:
    New Process ID: 0x1c8c
    New Process Name: C:\Windows\explorer.exe
    Token Elevation Type: TokenElevationTypeDefault (1)
    Creator Process ID: 0x1278

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. This comment has been removed by the author.

      Delete
  6. Previously vbs script was working but suddenly stopped so what can be the reason behind stopping..any help would be appreciated..thanks.

    ReplyDelete
  7. Thanks for this! I used this on Win7 Pro to monitor a folder change on my NAS and upon trigger (file write) schedule a task to run Synctoy to sync the folder contents with my dropbox folder. :)

    ReplyDelete
  8. This comment has been removed by a blog administrator.

    ReplyDelete
  9. Hi I have problem on Win 10 Pro. I cannot type 'Security' in a step 2.2.
    Roll is not working, field is white (not grey) and if I try to write sth in the field, it is still empty :/

    ReplyDelete
    Replies
    1. In task scheduler I dont have event connected with copy, modify or create new file :/
      In 'security tab' I see only:
      Logon
      special logon
      User account anagment

      Delete
  10. Works like a charm. Thx a lot

    I was just looking for the proper xml event translation to audit a folder where a specific-named file is being created to write an event log

    ReplyDelete
  11. This comment has been removed by a blog administrator.

    ReplyDelete