{"id":65513,"date":"2007-02-15T00:50:00","date_gmt":"2007-02-15T00:50:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2007\/02\/15\/how-can-i-automatically-open-new-files-added-to-a-folder\/"},"modified":"2007-02-15T00:50:00","modified_gmt":"2007-02-15T00:50:00","slug":"how-can-i-automatically-open-new-files-added-to-a-folder","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-automatically-open-new-files-added-to-a-folder\/","title":{"rendered":"How Can I Automatically Open New Files Added to a Folder?"},"content":{"rendered":"<p><H2><IMG 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\"> <\/H2>\n<P>Hey, Scripting Guy! How can I monitor a folder for new files and then automatically open each new file that gets added to that folder?<BR><BR>&#8212; CA<\/P><IMG height=\"5\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" border=\"0\"><IMG 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 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> \n<P>Hey, CA. You know, today is Valentine\u2019s Day in the US, which means that right now most American men are saying to themselves, \u201cWhat? Today is Valentine\u2019s Day? Uh-oh \u2026.\u201d We\u2019re not sure how many other countries around the world celebrate Valentine\u2019s Day, but in the US today is the day when you\u2019re supposed to lavish your significant other with jewelry, flowers, chocolates, heartfelt cards and other expensive gifts, all as a way to say thank you for the \u2026 wonderful \u2026 things they do for you.<\/P>\n<TABLE class=\"dataTable\" id=\"E2C\" 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>. In case you\u2019re wondering, the answer is no; instead, the Scripting Guy who writes this column and his son are going to a college basketball game tonight. On the other hand, what greater gift could this Scripting Guy give someone than to <I>not<\/I> hang around with them?<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>If you\u2019re not familiar with the occasion, Valentine\u2019s Day is named after St. Valentine, although <I>which<\/I> St. Valentine remains a matter of debate. (Apparently, in the early days of Christianity there were at least three St. Valentines.) According to legend, sometime in the third century a Roman emperor barred young men from getting married; he believed that unmarried men would make better soldiers. (Today most scholars disagree with that, pointing out that no one has more fighting experience than a <I>married<\/I> man.) As the story goes, St. Valentine was a priest who elected to defy the emperor, continuing to perform marriages in secret. When he was caught, he was martyred for his faith, although not before sending a note to a young lady signed, \u201cFrom your Valentine.\u201d The rest is history. <\/P>\n<P>Or legend. Take your pick.<\/P>\n<P>At any rate, if you\u2019re like most American men you haven\u2019t gotten that certain special someone anything for Valentine\u2019s Day. Might we suggest a script that monitors a folder for new files and then automatically opens each new file that gets added to that folder:<\/P><PRE class=\"codeSample\">Set objShell = CreateObject(&#8220;Wscript.Shell&#8221;)<\/p>\n<p>strComputer = &#8220;.&#8221;<\/p>\n<p>Set objWMIService = GetObject(&#8220;winmgmts:\\\\&#8221; &amp; strComputer &amp; &#8220;\\root\\cimv2&#8221;)<\/p>\n<p>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;)<\/p>\n<p>Do\n    Set objLatestEvent = colMonitoredEvents.NextEvent\n    strNewFile = objLatestEvent.TargetInstance.PartComponent\n    arrNewFile = Split(strNewFile, &#8220;=&#8221;)\n    strFileName = arrNewFile(1)\n    strFileName = Replace(strFileName, &#8220;\\\\&#8221;, &#8220;\\&#8221;)\n    strFileName = Replace(strFileName, Chr(34), &#8220;&#8221;)\n    objShell.Run(&#8220;notepad.exe &#8221; &amp; strFileName)\nLoop\n<\/PRE>\n<P>And no, you don\u2019t need glasses: the script really <I>does<\/I> look like that. But maybe it will help if we explain <I>why<\/I> it looks like that.<\/P>\n<P>We start out simple enough, creating an instance of the <B>Wscript.Shell<\/B> object, the object we\u2019ll use to open a file. We then do something equally straightforward, connecting to the WMI service on the local computer. (Although, as usual, this script works equally well against a remote machine.)<\/P>\n<P>We then encounter this line of code:<\/P><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>We won\u2019t explain this monstrosity in minute detail today; for that you might take a peek at the Scripting Guys webcast <A href=\"http:\/\/msevents.microsoft.com\/cui\/eventdetail.aspx?EventID=1032268754&amp;culture=en-US\" target=\"_blank\"><B>An Ounce of Preventio<\/B><B>n<\/B><\/A>. In brief, this query is designed to check the folder C:\\Scripts every 10 seconds and see if any new files have been added to that folder. How do we know that this query checks for new files? Well, we know that it\u2019s looking for new items because it\u2019s querying for instances of the <B>__InstanceCreationEvent<\/B> class. And we know that we\u2019re looking for files because we\u2019re specifying that we\u2019re only interested in new members of the __InstanceCreationEvent class if they happen to also be members of the <B>CIMDirectoryContainsFile<\/B> class. <\/P>\n<P>And that\u2019s not all. The 10 second interval between checks is what the <B>WITHIN 10<\/B> is all about; if that value is too long or too short then just adjust the time accordingly. Last but surely not least, we know that we\u2019re looking at the C:\\Scripts folder because of this:<\/P><PRE class=\"codeSample\">&#8216;Win32_Directory.Name=&#8221;&#8221;c:\\\\\\\\scripts&#8221;&#8221;&#8216;\n<\/PRE>\n<P>For better or worse, all those \\\u2019s and all those single and double quote marks are required.<\/P>\n<P>Got all that? Well, to be honest, we don\u2019t, either. But if you use the preceding example as a template and change only those items (such as the folder name) that you need to change you should be fine.<\/P>\n<P>We\u2019d like to tell you that all the craziness is over, but we can\u2019t do that; there\u2019s still a bit more craziness to come. Our next step is to set up a Do loop that\u2019s designed to run forever; you might note that there\u2019s no exit criteria like \u201cDo Until x = 1\u201d or \u201cDo While x &lt; 10\u201d:<\/P><PRE class=\"codeSample\">Do\n<\/PRE>\n<P>Inside that loop the first thing we do is issue a command that causes the script to \u201cblock.\u201d That simply means that the script will sit on this line of code until our query notifies us that an event of interest has occurred:<\/P><PRE class=\"codeSample\">Set objLatestEvent = colMonitoredEvents.NextEvent\n<\/PRE>\n<P>Needless to say, thanks to the criteria specified in our query, such notification can only mean one thing: a new file has been added to C:\\Scripts.<\/P>\n<P>Now the craziness returns. Each time a new file is added to the folder we get notified; in addition, we can take a peek at the <B>PartComponent<\/B> property to determine the file path:<\/P><PRE class=\"codeSample\">strNewFile = objLatestEvent.TargetInstance.PartComponent\n<\/PRE>\n<P>That\u2019s the good news. The bad news is that the PartComponent 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>Yuck. But don\u2019t despair; we can extract the path from that. Guaranteed.<\/P>\n<P>To do that, we first use the <B>Split<\/B> function to split the PartComponent on the equals sign. That\u2019s going to give us an array consisting of two items:<\/P>\n<TABLE class=\"\" cellSpacing=\"0\" cellPadding=\"0\" border=\"0\">\n<TBODY>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P>\\\\ATL-WS-01\\root\\cimv2:CIM_DataFile.Name<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P>&#8220;c:\\\\scripts\\\\New Text Document.txt&#8221;<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<P>As you can see, the path we need is \u2013 more or less \u2013 contained in the second item in the array. (Which, arrays being what they are, the second item in the array is assigned the index number 1.) With that in mind, we use this line of code to put this item into a variable named strFileName:<\/P><PRE class=\"codeSample\">strFileName = arrNewFile(1)\n<\/PRE>\n<P>Now we just need to clean things up a bit. First, we use the <B>Replace<\/B> function to replace any double \\ characters with a single \\, like so:<\/P><PRE class=\"codeSample\">strFileName = Replace(strFileName, &#8220;\\\\&#8221;, &#8220;\\&#8221;)\n<\/PRE>\n<P>That\u2019s leaves strNewFile equal to this: &#8220;<B>c:\\scripts\\New Text Document.txt<\/B>&#8220;. That right there is our file path. Or at least it will be after we use the Replace function to remove the double quote marks (which have an ASCII value of 34):<\/P><PRE class=\"codeSample\">strFileName = Replace(strFileName, Chr(34), &#8220;&#8221;)\n<\/PRE>\n<P>And now that strFileName contains the <I>real<\/I> path to the new file we can use the <B>Run<\/B> method and open the new file in Notepad:<\/P><PRE class=\"codeSample\">objShell.Run(&#8220;notepad.exe &#8221; &amp; strFileName)\n<\/PRE>\n<P>Good question: do you <I>have<\/I> to open new files in Notepad? No. However, you do need to specify an executable file; we can\u2019t just ask the Run method to directly open the file C:\\Scripts\\New Text Document.txt. We took the easy way out here and assumed that all the new files that might be added to C:\\Scripts can be opened with Notepad. If that\u2019s not the case then you\u2019ll need to add some additional code to the script, code that checks the file extension and then runs the appropriate application (e.g., it calls Excel if we happen to be dealing with a .xls file). Most likely you can figure that part out on your own. If not, we\u2019ll cover it in a future column.<\/P>\n<P>With any luck that will not only answer your question, CA, but also take care of your Valentine\u2019s Day shopping. If not, maybe we could be so presumptuous as to suggest a <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/funzone\/games\/games07\/bobble.mspx\"><B>Dr. Scripto Bobblehead doll<\/B><\/A> for that certain special someone. Granted, you can\u2019t actually <I>buy<\/I> a Dr. Scripto Bobblehead doll, but there\u2019s still time to win one as part of the <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/funzone\/games\/default.mspx\"><B>2007 Winter Scripting Games<\/B><\/A>. All you have to do is enter an event and you\u2019re automatically entered in a drawing to win one of 250 Dr. Scripto bobbleheads.<\/P>\n<P>Sure, it doesn\u2019t <I>sound<\/I> like much. But what man or woman could say no to a face like this:<\/P><IMG height=\"300\" alt=\"Dr. Scripto\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/games\/bobble\/bh_color_1.gif\" width=\"176\" border=\"0\"><BR><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! How can I monitor a folder for new files and then automatically open each new file that gets added to that folder?&#8212; CA Hey, CA. You know, today is Valentine\u2019s Day in the US, which means that right now most American men are saying to themselves, \u201cWhat? Today is Valentine\u2019s Day? Uh-oh [&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":[38,11,3,12,5],"class_list":["post-65513","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-files","tag-folders","tag-scripting-guy","tag-storage","tag-vbscript"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! How can I monitor a folder for new files and then automatically open each new file that gets added to that folder?&#8212; CA Hey, CA. You know, today is Valentine\u2019s Day in the US, which means that right now most American men are saying to themselves, \u201cWhat? Today is Valentine\u2019s Day? Uh-oh [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/65513","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=65513"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/65513\/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=65513"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=65513"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=65513"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}