I need to find a way to automatically rename all files that are created within a specific directory on a Windows 2008r2 file server. This needs to be done more or less instantanously, so I can't have a scheduled job run every 5 minutes or so.
I've done some research and figured out that I may be able to do this by scheduling a task to trigger on WMI events signalling file creation, but I really don't know how to get started so I need some pointers.
To create a PS script that locates the file and renames it would be easy enough, but I really don't know how to trigger the script on the correct event.
First of all, enable File Auditing in Administrative Tools -> Local Security Policy -> Local Policies -> Audit Policy -> Audit Object Access.
Here, you want to enable both
Failure
&Success
After that, right-click the folder where the folders will be created and go to Advanced in the Properties. There you'll have a tab
Auditing
. Add it for all users and check all the options (Success)Then, create a folder in the folder and open up the
eventvwr
. Here you will see an entry in the Audit-logs for the creation of the folder. Right-click on it and add an action on it.As task you could launch
PowerShell.exe
and as argument you could provide your script:(You do not need to pass the arguments if you won't be doing anything with them)
I've never tried it, but the PowerShell Pack includes a FileSystemWatcher which can trigger your alert monitor. See this thread for an example usage.
Your powershell script obviously needs to be continually running.
However, one of your biggest problems with any trigger system is that you will usually get notified of when the file creation starts and not when it has finished, so your file may still be in use when you try to rename it. To get around this, your trigger code may have to check if the rename succeeds and keeping trying every so often until it does.
You also need to be careful of how the files are created. For example, I have seen programs which first of all create files such as filename.ext.temp and when completed they rename the file to the proper name ie filename.ext. In this case you don't really want to monitor the file creation, but rather the rename.
I had one considered it, but I like TiZon's better. This was the code I found a while back, but the need for it went away so I never really put it to much use.
From CodeProject.