Hey, Scripting Guy! How Can I Monitor a Folder for the Creation of New Subfolders?

Hey, Scripting Guy! How Can I Monitor a Folder for the Creation of New Subfolders?

  • Comments 1
  • Likes
Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I monitor a folder for the creation of new subfolders? I know that new files can be detected (via WMI events) but the same syntax doesn't detect new folders.
-- WS

SpacerHey, Scripting Guy! AnswerScript Center

Hey, WS. Before we get started today can we ask you a quick question: are you reading today’s column? If you aren’t reading today’s column that means that the Scripting Guy who writes this column (or, more correctly, the Scripting Guy who used to write this column) actually carried through on his threat to quit writing this column.

On the other hand, if you are reading this column then that means one of two things happened: 1) either the Seattle area didn’t get the snow it was predicted to get this past weekend; or, 2) someone managed to convince the Scripting Guy who writes this column that it wouldn’t be all that smart to quit his job just because it did snow in Seattle. Especially when you consider the fact that the Scripting Son starts college in August.

What’s all this about snow in Seattle, in April? Well, on Friday morning, as the Scripting Guy who writes this column wrote this column (which you may or may not be reading at the moment) snow was being predicted for the Seattle area. According to MSNBC, “By late Friday, the snow level could drop to near 500 feet and lower. Areas north of Seattle could see wet, slushy snow Friday evening into early Saturday. Areas north of Snohomish and Skagit counties could see a couple of inches of snow.”

Oh, and on top of that, “The air will have a winter-like bite to it, with lows starting out in the 30s and highs maxing out only in the 40s.”

To be honest, the moment the Scripting Guy who writes this column read that forecast he decided that enough was enough: if it actually snowed in Seattle on April 18th (or even on April 19th) then he was going to immediately quit his job and move some place where it doesn’t snow on April 18th. Where would that some place be? Well, he wasn’t really sure; after all, he always thought that Seattle was some place where it doesn’t snow on April 18th. And what would he do once he arrived in his new, presumably-warmer, home town? Well, he wasn’t sure about that, either. But hey, how hard could it be to find a job writing a daily column about system administration scripting?

At any rate, if you aren’t reading today’s column, well, now you know why: the Scripting Guy who writes this column has escaped to some place a bit warmer and a bit more hospitable than Seattle.

Like, say, Antarctica.

On the other hand, there’s always the outside chance that it didn’t actually snow, that the Seattle area was just treated to rain and 30-degree temperatures. In that case, the Scripting Guy who writes this column probably didn’t escape to warmer climes. Which can only mean one thing: you’re probably are reading this column, which means he needs to give you something to actually read:

strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
    ("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _
        & "TargetInstance ISA 'Win32_SubDirectory' and " _
            & "TargetInstance.GroupComponent= " _
                & "'Win32_Directory.Name=""C:\\\\Scripts""'")

Do While True
    Set objEventObject = colMonitoredEvents.NextEvent()
    Wscript.Echo objEventObject.TargetInstance.PartComponent
Loop

Note. To be fair, things are nowhere near as bad as the Scripting Guy who writes this column has made them sound. For example, here’s the forecast for Sunday: “Sunday shouldn't bring much more than a brief mix of a few scattered rain and snow showers.” See? Just a few scattered snow showers. No big deal.

OK; what do you say we toss another log onto the fire and see if we can figure out how this script works? As WS noted, you can’t use a script that monitors file creation to monitor folder creation. However, you can use a very similar approach; all you have to do is specify that you’re looking for new folders rather than new files. Needless to say, that’s exactly what we’ve done here.

As you can see, we start out by connecting to the WMI service on the local computer. Could we use this same script to monitor folder creation on a remote computer? Let’s put it this way: you’d have a snowball’s chance in April of using this same script to monitor folder creation on a remote computer.

Which, sadly enough, means yes, of course you can use this same script to monitor folder creation on a remote computer: all you have to do is assign the name of that remote computer to the variable strComputer. For example:

strComputer = "atl-fs-001"

Connecting to the WMI service is the easy part. The hard part – or at least the part that looks hard – is this:

Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
    ("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _
        & "TargetInstance ISA 'Win32_Subdirectory' and " _
            & "TargetInstance.GroupComponent= " _
                & "'Win32_Directory.Name=""C:\\\\Scripts""'")

This is the part of the script where we create our “event subscription;” that is, this is the query we use to specify that we want notification any time a new subfolder is created in the folder C:\Scripts. To do that we create an ExecNotificationQuery that requests notification (within 10 seconds) any time a new instance of the __InstanceCreationEvent class is created. (New instances of this class are created each time a new WMI object is created on the computer.)

But wait: there is a catch or two here. For one thing, we only want to be notified if this new instance is a member of the Win32_Subdirectory class; that’s how we can limit notification to the creation of new folders. In addition to that, we also want to be notified only if this new subfolder is created in the C:\Scripts folder.

Note. Why in the world did we write C:\Scripts like this: C:\\\\Scripts? We won’t bother going into all the details today; for more information, take a look at our webcast on WMI events and eventing.

Once we’ve configured our event subscription the rest is easy. For starters, we set up a Do loop designed to run forever and ever; in fact, the only way to stop monitoring the C:\Scripts folder is to terminate the script itself. (Which makes this a good time to mention that today’s script should be run in a command window, and run under the CScript script host to boot.) Inside this endless loop we use the following line of code to tell the script that we want it to just sit there and wait until it receives an event notification; in other words, we want the script to “block” on this line of code until a new subfolder is created in C:\Scripts:

Set objEventObject = colMonitoredEvents.NextEvent()

And what happens if and when a new subfolder is created in C:\Scripts? In that case we echo back the value of the new folder’s PathComponent property; that’s going to give us output similar to this:

\\ATL-WS-001\root\cimv2:Win32_Directory.Name="c:\\scripts\\New Folder"

If that output is a little messy for you, well, this Do loop will clean the folder path up a bit:

Do While True
    Set objEventObject = colMonitoredEvents.NextEvent()
    strNewFolder = objEventObject.TargetInstance.PartComponent
    arrNewFolder = Split(strNewFolder, "=")
    strNewFolder = arrNewFolder(1)
    strNewFolder = Replace(strNewFolder, "\\", "\")
    strNewFolder = Replace(strNewFolder, Chr(34), "")
    Wscript.Echo strNewFolder
Loop

That loop will give you output that looks like this:

c:\\scripts\\New Folder

Either way, once the notification has been received and echoed to the screen, the script will then loop around and waits for the next event to occur.

This script works just fine, but it’s important to note that it only alerts you when subfolders are created within the C:\Scripts folder itself. What if you create a new folder in C:\Scripts\Test; will the script notify you of the existence of that new folder? Sadly, no; we can only monitor one folder level at a time. Granted, you might think that we could monitor for the creation of any new instance of the Win32_Directory class; after all, that would tell us when any new folder gets created on a computer. Unfortunately, though, that won’t work; a query that monitors a computer for a new folder created anywhere on the machine is considered too “expensive,” and will result in an error similar to this:

SWbemServicesEx: Quota violation

In theory, there might be a way to work around this issue; for more information, see the following Knowledge Base article. As a general rule, however, assume that you can only monitor a single folder at a time; that’s why we had to specify a folder path in our query.

That’s all we have time for today, and maybe all we have time for forever. As the Scripting Guy who writes this column is putting the finishing touches on the column, the temperature outside is 36 degrees Fahrenheit and it’s raining. Does that mean it really will snow on April 18th? To tell you the truth, that’s a pretty sure bet: after all, the Scripting Son has a baseball scheduled from 6:30 PM on Friday, and what would baseball in Seattle be without a little snow and icy-cold temperatures.

Oh, well: doing the Hey, Scripting Guy! column was fun while it lasted, eh?

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • I dont know if I read ur column or not, sooo confuuuuseed :|