{"id":70103,"date":"2005-04-04T19:12:00","date_gmt":"2005-04-04T19:12:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2005\/04\/04\/how-can-i-monitor-for-different-types-of-events-with-just-one-script\/"},"modified":"2005-04-04T19:12:00","modified_gmt":"2005-04-04T19:12:00","slug":"how-can-i-monitor-for-different-types-of-events-with-just-one-script","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-monitor-for-different-types-of-events-with-just-one-script\/","title":{"rendered":"How Can I Monitor for Different Types of Events With Just One Script?"},"content":{"rendered":"<p><P>&nbsp;<\/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 there any way to monitor a folder for file creations and deletions, all with just one script?<\/P>\n<P>&#8212; HA<\/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, HA. By the way, thanks for the question: you temporarily saved us from answering a different question, one that was proving a bit difficult thanks to some surprising differences between Windows XP Service Pack 1 and Windows XP Service Pack 2. (We\u2019ll tackle that question in tomorrow\u2019s column.) Your question, by contrast, is an easy one to answer, even if most people aren\u2019t aware of that.<\/P>\n<P>Most people <I>are<\/I> aware that you can monitor for file creations, deletions, <I>or<\/I> modifications by using one of these three event classes (note the two underscores at the beginning of all three class names):<\/P>\n<TABLE border=\"0\" cellSpacing=\"0\" cellPadding=\"0\">\n<TBODY>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P><B>__InstanceCreationEvent<\/B>. This is used for monitoring creation events; that is, you can be notified any time a new instance of something gets created. In our case, notification will occur any time a new file is created in the folder C:\\Scripts.<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P><B>__InstanceDeletionEvent<\/B>. You\u2019re way ahead of us: this class is used for monitoring deletion events; we\u2019ll be notified any time a file is deleted from C:\\Scripts.<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P><B>__InstanceModificationEvent<\/B>. Finally, we can be notified any time a file in C:\\Scripts is modified in some way (you change the file name, you add or delete something from the file, etc.).<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<TABLE id=\"END\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD>\n<P class=\"lastInCell\"><B>Note<\/B>. If none of this makes sense to you, don\u2019t worry; instead, check out this <A href=\"http:\/\/msevents.microsoft.com\/cui\/eventdetail.aspx?EventID=1032268754&amp;culture=en-US\" target=\"_blank\"><B>WMI Events webcast<\/B><\/A> from Scripting Week 2. In that webcast we discuss WMI events in detail, and we explain things like ExecNotificationQuery and WITHIN 10.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV><PRE class=\"codeSample\">Set 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;)\n<\/PRE>\n<P>However, this next query \u2013 which tries to monitor instances of both the __InstanceCreationEvent and __InstanceDeletionEvent classes \u2013 is doomed to fail:<\/P><PRE class=\"codeSample\">Set colMonitoredEvents = objWMIService.ExecNotificationQuery _\n    (&#8220;SELECT * FROM __InstanceCreationEvent OR __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;)\n<\/PRE>\n<P>You just can\u2019t do it; instead, you get the terse error message: \u201cUnparsable query.\u201d Yikes.<\/P>\n<P>Is this a problem? Of course it is. Although there are exceptions, you\u2019ll often want to know about <I>any<\/I> activity that goes on in C:\\Scripts, not just file creations or file deletions. Because of that people often resort to writing \u2013 and running \u2013 separate scripts to monitor and report on each of the WMI event classes.<\/P>\n<P>But guess what: there\u2019s a better way. Turns out there\u2019s actually a <I>fourth<\/I> WMI event class: <B>__InstanceOperationEvent<\/B>. Best of all, our other three event classes are all subsumed under __InstanceOperationEvent; you can use __InstanceOperationEvent to monitor for event creations, event deletions, <I>and<\/I> event modifications. We\u2019ll use it today to monitor for both file creations and deletions.<\/P>\n<P>What we do is monitor for instances of the __InstanceOperationEvent class; new instances of this class are created pretty much any time <I>anything<\/I> occurs on a computer. We then check the value of the <B>Path_.Class<\/B> property to determine whether the new instance was created in response to a file creation or file deletion. That\u2019s how we can monitor for file creations and deletions in a single script.<\/P>\n<P>Let\u2019s take a look at the code:<\/P><PRE class=\"codeSample\">strComputer = &#8220;.&#8221;\nSet objWMIService = GetObject(&#8220;winmgmts:\\\\&#8221; &amp; strComputer &amp; &#8220;\\root\\cimv2&#8221;)<\/p>\n<p>Set colMonitoredEvents = objWMIService.ExecNotificationQuery _\n    (&#8220;SELECT * FROM __InstanceOperationEvent 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;)<\/p>\n<p>Do While TRUE\n    Set objEventObject = colMonitoredEvents.NextEvent()<\/p>\n<p>    Select Case objEventObject.Path_.Class\n        Case &#8220;__InstanceCreationEvent&#8221;\n            Wscript.Echo &#8220;A new file was just created: &#8221; &amp; _\n                objEventObject.TargetInstance.PartComponent\n        Case &#8220;__InstanceDeletionEvent&#8221;\n            Wscript.Echo &#8220;A file was just deleted: &#8221; &amp; _\n                objEventObject.TargetInstance.PartComponent\n    End Select\nLoop\n<\/PRE>\n<P>Keep in mind that looks can be deceiving here; the script isn\u2019t quite as complicated as it might first appear. All we\u2019re really doing here is using a basic <B>ExecNotificationQuery<\/B> to check every 10 seconds (<B>WITHIN 10<\/B>) for new instances of the __InstanceOperationEvent class; in particular, we\u2019re looking for instances involving the folder C:\\Scripts. That\u2019s what this crazy piece of code does:<\/P><PRE class=\"codeSample\">Set colMonitoredEvents = objWMIService.ExecNotificationQuery _\n    (&#8220;SELECT * FROM __InstanceOperationEvent 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;)\n<\/PRE>\n<P><B>Note<\/B>. If none of this makes sense to you, don\u2019t worry; instead, check out this <B>WMI Events webcast<\/B> from Scripting Week 2. In that webcast we discuss WMI events in detail, and we explain things like ExecNotificationQuery and WITHIN 10.<\/P>\n<P>After issuing the query we simply create a Do Loop and wait for the next event to occur. When it does we use the Path_.Class property to determine the event type; we then echo a message that an event just took place. This message also includes the WMI object path for the new instance (information which happens to be stored in the <B>PartComponent<\/B> property). The object path for a file looks something like this:<\/P><PRE class=\"codeSample\">\\\\ATL-WS-01\\root\\cimv2:CIM_DataFile.Name=&#8221;c:\\\\scripts\\\\New Text Document.txt&#8221;\n<\/PRE>\n<P>We didn\u2019t bother doing so here, but you could add a few lines of code to the script to pull out just the file path (in this case, <B>C:\\Scripts\\New Text Document.txt<\/B>). Otherwise, you\u2019ll just have to make do with the WMI object path.<\/P>\n<P>Here\u2019s where all that excitement takes place:<\/P><PRE class=\"codeSample\">Select Case objEventObject.Path_.Class\n    Case &#8220;__InstanceCreationEvent&#8221;\n        Wscript.Echo &#8220;A new file was just created: &#8221; &amp; _\n            objEventObject.TargetInstance.PartComponent\n    Case &#8220;__InstanceDeletionEvent&#8221;\n        Wscript.Echo &#8220;A file was just deleted: &#8221; &amp; _\n            objEventObject.TargetInstance.PartComponent\nEnd Select\n<\/PRE>\n<P>That\u2019s basically it; we then loop around and wait for the next event. And while we\u2019re waiting, we\u2019ll get back to work on that other question, the one that inspired us to take the easy way out and answer this question instead.<\/P><BR>\n<DIV>\n<TABLE border=\"0\" cellSpacing=\"0\" cellPadding=\"0\" width=\"100%\">\n<TBODY>\n<TR>\n<TD><A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/apr05\/hey0404.mspx#top\"><IMG border=\"0\" alt=\"Top of page\" src=\"http:\/\/www.microsoft.com\/technet\/mnplibrary\/templates\/MNP2.Common\/images\/arrow_px_up.gif\" width=\"7\" height=\"9\"><\/A><A class=\"topOfPage\" href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/apr05\/hey0404.mspx#top\">Top of page<\/A><\/TD><\/TR><\/TBODY><\/TABLE><\/DIV><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&nbsp; Hey, Scripting Guy! Is there any way to monitor a folder for file creations and deletions, all with just one script? &#8212; HA Hey, HA. By the way, thanks for the question: you temporarily saved us from answering a different question, one that was proving a bit difficult thanks to some surprising differences between [&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,6],"class_list":["post-70103","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","tag-wmi"],"acf":[],"blog_post_summary":"<p>&nbsp; Hey, Scripting Guy! Is there any way to monitor a folder for file creations and deletions, all with just one script? &#8212; HA Hey, HA. By the way, thanks for the question: you temporarily saved us from answering a different question, one that was proving a bit difficult thanks to some surprising differences between [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/70103","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=70103"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/70103\/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=70103"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=70103"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=70103"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}