{"id":55733,"date":"2008-04-22T01:13:00","date_gmt":"2008-04-22T01:13:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2008\/04\/22\/hey-scripting-guy-how-can-i-monitor-a-folder-for-the-creation-of-new-subfolders\/"},"modified":"2008-04-22T01:13:00","modified_gmt":"2008-04-22T01:13:00","slug":"hey-scripting-guy-how-can-i-monitor-a-folder-for-the-creation-of-new-subfolders","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/hey-scripting-guy-how-can-i-monitor-a-folder-for-the-creation-of-new-subfolders\/","title":{"rendered":"Hey, Scripting Guy! How Can I Monitor a Folder for the Creation of New Subfolders?"},"content":{"rendered":"<p><img decoding=\"async\" class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" height=\"34\" alt=\"Hey, Scripting Guy! Question\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" align=\"left\" border=\"0\" \/> <\/p>\n<p>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&#8217;t detect new folders.<br \/>&#8212; WS<\/p>\n<p><img decoding=\"async\" height=\"5\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" border=\"0\" \/><img decoding=\"async\" class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" height=\"34\" alt=\"Hey, Scripting Guy! Answer\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" align=\"left\" border=\"0\" \/><a href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><img decoding=\"async\" class=\"farGraphic\" title=\"Script Center\" height=\"288\" alt=\"Script Center\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" width=\"120\" align=\"right\" border=\"0\" \/><\/a> <\/p>\n<p>Hey, WS. Before we get started today can we ask you a quick question: are you reading today\u2019s column? If you <i>aren\u2019t<\/i> reading today\u2019s column that means that the Scripting Guy who writes this column (or, more correctly, the Scripting Guy who <i>used<\/i> to write this column) actually carried through on his threat to quit writing this column. <\/p>\n<p>On the other hand, if you <i>are<\/i> reading this column then that means one of two things happened: 1) either the Seattle area <i>didn\u2019t<\/i> 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\u2019t be all that smart to quit his job just because it <i>did<\/i> snow in Seattle. Especially when you consider the fact that the Scripting Son starts college in August.<\/p>\n<p>What\u2019s all this about snow in Seattle, in <i>April<\/i>? 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 <a href=\"http:\/\/www.msnbc.msn.com\/id\/24200422\" target=\"_blank\"><b>MSNBC<\/b><\/a>, \u201cBy 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.\u201d <\/p>\n<p>Oh, and on top of that, \u201cThe air will have a winter-like bite to it, with lows starting out in the 30s and highs maxing out only in the 40s.\u201d<\/p>\n<p>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 18<sup>th<\/sup> (or even on April 19<sup>th)<\/sup> then he was going to immediately quit his job and move some place where it <i>doesn\u2019t <\/i>snow on April 18<sup>th<\/sup>. Where would that some place be? Well, he wasn\u2019t really sure; after all, he always thought that <i>Seattle<\/i> was some place where it doesn\u2019t snow on April 18<sup>th<\/sup>. And what would he do once he arrived in his new, presumably-warmer, home town? Well, he wasn\u2019t sure about that, either. But hey, how hard could it be to find a job writing a daily column about system administration scripting?<\/p>\n<p>At any rate, if you aren\u2019t reading today\u2019s 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.<\/p>\n<p>Like, say, Antarctica.<\/p>\n<p>On the other hand, there\u2019s always the outside chance that it didn\u2019t 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 <i>didn\u2019t<\/i> escape to warmer climes. Which can only mean one thing: you\u2019re probably <i>are<\/i> reading this column, which means he needs to give you something to actually read:<\/p>\n<pre class=\"codeSample\">strComputer = \".\"\n\nSet objWMIService = GetObject(\"winmgmts:\\\\\" &amp; strComputer &amp; \"\\root\\cimv2\")\n\nSet colMonitoredEvents = objWMIService.ExecNotificationQuery _\n    (\"SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE \" _\n        &amp; \"TargetInstance ISA 'Win32_SubDirectory' and \" _\n            &amp; \"TargetInstance.GroupComponent= \" _\n                &amp; \"'Win32_Directory.Name=\"\"C:\\\\\\\\Scripts\"\"'\")\n\nDo While True\n    Set objEventObject = colMonitoredEvents.NextEvent()\n    Wscript.Echo objEventObject.TargetInstance.PartComponent\nLoop\n<\/pre>\n<table class=\"dataTable\" id=\"EXE\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td class=\"\">\n<p class=\"lastInCell\"><b>Note<\/b>. To be fair, things are nowhere <i>near<\/i> as bad as the Scripting Guy who writes this column has made them sound. For example, here\u2019s the forecast for Sunday: \u201cSunday shouldn&#8217;t bring much more than a brief mix of a few scattered rain and snow showers.\u201d See? Just a few scattered snow showers. No big deal.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>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\u2019t use a script that <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/feb07\/hey0214.mspx\"><b>monitors file creation<\/b><\/a> to monitor folder creation. However, you <i>can<\/i> use a very similar approach; all you have to do is specify that you\u2019re looking for new folders rather than new files. Needless to say, that\u2019s exactly what we\u2019ve done here.<\/p>\n<p>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 <i>remote<\/i> computer? Let\u2019s put it this way: you\u2019d have a snowball\u2019s chance in April of using this same script to monitor folder creation on a remote computer.<\/p>\n<p>Which, sadly enough, means yes, of <i>course<\/i> 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:<\/p>\n<pre class=\"codeSample\">strComputer = \"atl-fs-001\"\n<\/pre>\n<p>Connecting to the WMI service is the easy part. The hard part \u2013 or at least the part that <i>looks<\/i> hard \u2013 is this:<\/p>\n<pre class=\"codeSample\">Set colMonitoredEvents = objWMIService.ExecNotificationQuery _\n    (\"SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE \" _\n        &amp; \"TargetInstance ISA 'Win32_Subdirectory' and \" _\n            &amp; \"TargetInstance.GroupComponent= \" _\n                &amp; \"'Win32_Directory.Name=\"\"C:\\\\\\\\Scripts\"\"'\")\n<\/pre>\n<p>This is the part of the script where we create our \u201cevent subscription;\u201d 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 <b>ExecNotificationQuery<\/b> that requests notification (within 10 seconds) any time a new instance of the <b>__InstanceCreationEvent<\/b> class is created. (New instances of this class are created each time a new WMI object is created on the computer.)<\/p>\n<p>But wait: there <i>is<\/i> a catch or two here. For one thing, we only want to be notified if this new instance is a member of the <b>Win32_Subdirectory<\/b> class; that\u2019s 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. <\/p>\n<table class=\"dataTable\" id=\"ERG\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td class=\"\">\n<p class=\"lastInCell\"><b>Note<\/b>. Why in the world did we write <i>C:\\Scripts<\/i> like this: <i>C:\\\\\\\\Scripts<\/i>? We won\u2019t bother going into all the details today; for more information, take a look at our <a href=\"http:\/\/msevents.microsoft.com\/cui\/eventdetail.aspx?EventID=1032268754&amp;culture=en-US\" target=\"_blank\"><b>webcast<\/b><\/a> on WMI events and eventing.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>Once we\u2019ve 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\u2019s 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 \u201cblock\u201d on this line of code until a new subfolder is created in C:\\Scripts:<\/p>\n<pre class=\"codeSample\">Set objEventObject = colMonitoredEvents.NextEvent()\n<\/pre>\n<p>And what happens if and when a new subfolder <i>is<\/i> created in C:\\Scripts? In that case we echo back the value of the new folder\u2019s <b>PathComponent<\/b> property; that\u2019s going to give us output similar to this:<\/p>\n<pre class=\"codeSample\">\\\\ATL-WS-001\\root\\cimv2:Win32_Directory.Name=\"c:\\\\scripts\\\\New Folder\"\n<\/pre>\n<p>If that output is a little messy for you, well, this Do loop will clean the folder path up a bit:<\/p>\n<pre class=\"codeSample\">Do While True\n    Set objEventObject = colMonitoredEvents.NextEvent()\n    strNewFolder = objEventObject.TargetInstance.PartComponent\n    arrNewFolder = Split(strNewFolder, \"=\")\n    strNewFolder = arrNewFolder(1)\n    strNewFolder = Replace(strNewFolder, \"\\\\\", \"\\\")\n    strNewFolder = Replace(strNewFolder, Chr(34), \"\")\n    Wscript.Echo strNewFolder\nLoop\n<\/pre>\n<p><i>That<\/i> loop will give you output that looks like this:<\/p>\n<pre class=\"codeSample\">c:\\\\scripts\\\\New Folder\n<\/pre>\n<p>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.<\/p>\n<p>This script works just fine, but it\u2019s 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 <i>that<\/i> 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 <i>any<\/i> new folder gets created on a computer. Unfortunately, though, that won\u2019t work; a query that monitors a computer for a new folder created anywhere on the machine is considered too \u201cexpensive,\u201d and will result in an error similar to this:<\/p>\n<pre class=\"codeSample\">SWbemServicesEx: Quota violation\n<\/pre>\n<p>In theory, there <i>might<\/i> be a way to work around this issue; for more information, see the following <a href=\"http:\/\/support.microsoft.com\/kb\/828653\" target=\"_blank\"><b>Knowledge Base article<\/b><\/a>. As a general rule, however, assume that you can only monitor a single folder at a time; that\u2019s why we had to specify a folder path in our query.<\/p>\n<p>That\u2019s 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\u2019s raining. Does that mean it really <i>will<\/i> snow on April 18<sup>th<\/sup>? To tell you the truth, that\u2019s 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.<\/p>\n<p>Oh, well: doing the <i>Hey, Scripting Guy!<\/i> column was fun while it lasted, eh?<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&#8217;t detect new folders.&#8212; WS Hey, WS. Before we get started today can we ask you a quick question: are you reading today\u2019s column? If [&hellip;]<\/p>\n","protected":false},"author":595,"featured_media":87096,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[11,3,12,5],"class_list":["post-55733","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-folders","tag-scripting-guy","tag-storage","tag-vbscript"],"acf":[],"blog_post_summary":"<p>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&#8217;t detect new folders.&#8212; WS Hey, WS. Before we get started today can we ask you a quick question: are you reading today\u2019s column? If [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/55733","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/users\/595"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/comments?post=55733"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/55733\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media\/87096"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media?parent=55733"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=55733"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=55733"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}