{"id":71253,"date":"2004-10-11T11:11:00","date_gmt":"2004-10-11T11:11:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2004\/10\/11\/how-can-i-automatically-run-a-script-any-time-a-file-is-added-to-a-folder\/"},"modified":"2004-10-11T11:11:00","modified_gmt":"2004-10-11T11:11:00","slug":"how-can-i-automatically-run-a-script-any-time-a-file-is-added-to-a-folder","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-automatically-run-a-script-any-time-a-file-is-added-to-a-folder\/","title":{"rendered":"How Can I Automatically Run a Script Any Time a File is Added to a Folder?"},"content":{"rendered":"<p><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" border=\"0\" alt=\"Hey, Scripting Guy! Question\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" height=\"34\"> \n<P>Hey, Scripting Guy! Is it possible to have a script automatically run any time a file is added to a specific folder?<BR><BR>&#8212; MB<\/P><IMG border=\"0\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" height=\"5\"><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" border=\"0\" alt=\"Hey, Scripting Guy! Answer\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" height=\"34\"><A href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><IMG class=\"farGraphic\" title=\"Script Center\" border=\"0\" alt=\"Script Center\" align=\"right\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" width=\"120\" height=\"288\"><\/A> \n<P>Hey, WM. Yes, this <I>is<\/I> possible, thanks to the magic of WMI events, which allow you to write a script to monitor for something of interest (like a file being added to a folder) and then take some action any time an event like that occurs. We don\u2019t have time to discuss WMI events in any detail in this column, but they can be incredibly useful to script writers. Consequently, it might be worth your while to check out this <A href=\"http:\/\/null\/technet\/scriptcenter\/resources\/tales\/sg0103.mspx\"><B><I>Tales from the Script<\/I><\/B><\/A> column.<\/P>\n<P>In the meantime, here\u2019s a script that monitors the C:\\Scripts folder. Any time a file is added to this folder, the script responds by echoing the name of that new file:<\/P><PRE class=\"codeSample\">strComputer = &#8220;.&#8221;\nSet objWMIService = GetObject(&#8220;winmgmts:&#8221; _\n    &amp; &#8220;{impersonationLevel=impersonate}!\\\\&#8221; &amp; _\n        strComputer &amp; &#8220;\\root\\cimv2&#8221;)\nSet colMonitoredEvents = objWMIService.ExecNotificationQuery _\n    (&#8220;SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE &#8221; _\n        &amp; &#8220;Targetinstance ISA &#8216;CIM_DirectoryContainsFile&#8217; and &#8221; _\n            &amp; &#8220;TargetInstance.GroupComponent= &#8221; _\n                &amp; &#8220;&#8216;Win32_Directory.Name=&#8221;&#8221;c:\\\\\\\\scripts&#8221;&#8221;&#8216;&#8221;)\nDo\n    Set objLatestEvent = colMonitoredEvents.NextEvent\n    Wscript.Echo objLatestEvent.TargetInstance.PartComponent\nLoop\n<\/PRE>\n<P>Again, there\u2019s too much going on here to go through the script step-by-step, but what we are looking for are instances of the <B>__InstanceCreationEvent<\/B> class; instances of this class are automatically created any time a new managed object (that is, something WMI knows about) is created on a computer. Although the query is a little complicated, it boils down to this: we want to be alerted to any new items that show up in C:\\Scripts. (Note that <B>C:\\\\\\\\Scripts<\/B> is not a misprint; you really need all four slashes here.) <\/P>\n<P>We also need to mention that a WMI script like this works by \u201cpolling;\u201d it periodically goes out and checks to see if any new files have been added to the folder. For this sample, we\u2019re checking every 10 seconds (that\u2019s what the <B>WITHIN 10<\/B> represents) to see if there are any new files in the folder. If that\u2019s too fast or too slow, you can change that value to anything you want. Keep in mind two things, however. For one, if you poll too often (say, every second), you\u2019ll have a script that is constantly running, and could theoretically put a drain on your system resources. <\/P>\n<P>Conversely, if you make the value too long, you might miss new files, assuming they get added and then deleted before the polling time expires. For example, say your script checks every 5 minutes for new files. If you add 100 new files and then delete all those files 3 minutes later, the script will never know that those files were added to the folder. That\u2019s because scripts like this work by comparing the files that currently in the folder with the files that were in the folder the last time the script checked. Play around with the polling interval and see what works best for you.<\/P>\n<P>As we noted, this script simply echoes the name of any new file added to C:\\Scripts. What if you wanted to do something a little fancier any time a file is added to the folder? No problem; just replace this line of code with the code you want executed any time a new file is detected:<\/P><PRE class=\"codeSample\">Wscript.Echo objLatestEvent.TargetInstance.PartComponent\n<\/PRE>\n<P>By the way, would you prefer to be notified any time a file is <I>deleted<\/I> from C:\\Scripts? That\u2019s easy enough; just monitor C:\\Scripts for new instances of the __InstanceDeletionEvent class:<\/P><PRE class=\"codeSample\">strComputer = &#8220;.&#8221;\nSet objWMIService = GetObject(&#8220;winmgmts:&#8221; _\n    &amp; &#8220;{impersonationLevel=impersonate}!\\\\&#8221; &amp; _\n        strComputer &amp; &#8220;\\root\\cimv2&#8221;)\nSet colMonitoredEvents = objWMIService.ExecNotificationQuery _\n    (&#8220;SELECT * FROM __InstanceDeletionEvent WITHIN 10 WHERE &#8221; _\n        &amp; &#8220;Targetinstance ISA &#8216;CIM_DirectoryContainsFile&#8217; and &#8221; _\n            &amp; &#8220;TargetInstance.GroupComponent= &#8221; _\n                &amp; &#8220;&#8216;Win32_Directory.Name=&#8221;&#8221;c:\\\\\\\\scripts&#8221;&#8221;&#8216;&#8221;)\nDo\n    Set objLatestEvent = colMonitoredEvents.NextEvent\n    Wscript.Echo objLatestEvent.TargetInstance.PartComponent\nLoop\n<\/PRE>\n<P>Hey, we <I>told<\/I> you WMI events were worth knowing about!<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! Is it possible to have a script automatically run any time a file is added to a specific folder?&#8212; MB Hey, WM. Yes, this is possible, thanks to the magic of WMI events, which allow you to write a script to monitor for something of interest (like a file being added to [&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":[42,3,4,5],"class_list":["post-71253","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-events-and-monitoring","tag-scripting-guy","tag-scripting-techniques","tag-vbscript"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! Is it possible to have a script automatically run any time a file is added to a specific folder?&#8212; MB Hey, WM. Yes, this is possible, thanks to the magic of WMI events, which allow you to write a script to monitor for something of interest (like a file being added to [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/71253","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=71253"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/71253\/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=71253"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=71253"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=71253"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}