{"id":64813,"date":"2007-05-22T23:10:00","date_gmt":"2007-05-22T23:10:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2007\/05\/22\/how-can-i-monitor-the-number-of-files-in-a-folder\/"},"modified":"2007-05-22T23:10:00","modified_gmt":"2007-05-22T23:10:00","slug":"how-can-i-monitor-the-number-of-files-in-a-folder","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-monitor-the-number-of-files-in-a-folder\/","title":{"rendered":"How Can I Monitor the Number of Files in a Folder?"},"content":{"rendered":"<p><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\"> \n<P>Hey, Scripting Guy! We have a third-party application that rarely crashes; however, when it <I>does<\/I> crash it seriously disrupts our business. We can always tell when the application is getting ready to crash; at that point, one of its directories starts filling up with log files. How can we be notified any time the number of log files in this folder exceeds a specified value?<BR><BR>&#8212; AE<\/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, AE. You know, before we tackle this question there\u2019s something we feel just has to be said: there are people in this world who are the embodiment of pure evil. <\/P>\n<P>And no, Peter, for once we\u2019re <I>not<\/I> thinking of you.<\/P>\n<P>Although now that you mention it \u2026.<\/P>\n<P>The other night the Scripting Guy who writes this column stopped at the store on his way home and picked up a carton of milk. At that time the store was jam-packed, with 9 or 10 people standing in line at each checkstand \u2026 each checkstand, that is, except the express lane (15 items or less). With his single item safely in hand, the Scripting Guy who writes this column headed towards the express lane, only to be clipped from behind by a woman who shoved her shopping cart directly in his path, in order to get to the checkstand before he could.<\/P>\n<P>Now, that was a bit rude (not to mention painful) but the Scripting Guy who writes this column was consoled by the fact that the lady was about to get her comeuppance. After all, she had <I>way<\/I> more than 15 items in the cart; there was absolutely no way the clerk would let her in line with that many items. But the Scripting Guy who writes this column didn\u2019t count on the resourcefulness of the truly evil.<\/P>\n<P>Before the clerk could say anything the woman spoke up. \u201cI actually have two separate purchases here, \u201cshe said. \u201cI need to pay for half of these items and get a receipt, then pay for the other half and get a separate receipt.\u201d The implication, of course, is that she was buying food for two local orphanages, and needed separate receipts for tax purposes. (Although the Scripting Guy who writes this column couldn\u2019t help but wonder, \u201cWhat? Satan can\u2019t do his own grocery shopping, you have to do it for him?\u201d) As she explained the reason why she had barged into the express lane despite having way more than 15 items, she took all the groceries out of the shopping cart and piled them on the checkstand. <\/P>\n<TABLE class=\"dataTable\" id=\"ELD\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD class=\"\">\n<P><B>Note<\/B>. In case you\u2019re wondering, she had 15 items in pile 1 and 17 items in pile 2. Even her second pile <I>by itself<\/I> was over the 15-item limit!<\/P>\n<P>Not that the Scripting Guy who writes this column was counting or anything.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>To tell you the truth, the store clerk didn\u2019t seem entirely comfortable with this. However, perhaps sensing the presence of pure evil, he decided to let it go. And what do you think happened? You got it: after he finished ringing up the last item in pile 1 the lady said, \u201cYou know, in order to make things <I>easier for you<\/I>, why don\u2019t you just put everything on one order and I\u2019ll pay for it all together.\u201d (And yes, she actually did speak in italics. That\u2019s what evil people do.) The clerk did what he was told, and a few minutes later the woman sashayed out of the store, having successfully purchased 32 items in the express lane (15 items or less).<\/P>\n<P>Pure evil. And did we mention that she also drove an SUV and took up two parking spots in the parking lot? Even <I>Dracula<\/I> would only take one parking space, especially when the store was crowded.<\/P>\n<P>But, then again, Dracula was at least part human.<\/P>\n<P>Oh, well. Fortunately the Scripting Guys would never stoop that low. (Actually they <I>would<\/I> stoop that low, except the Scripting Guys would get beat up by angry patrons if <I>they<\/I> tried to sneak 32 items through the express lane.) For example, if you want to know how to monitor the number of files found in a particular folder, well, the Scripting Guys are only too happy to oblige:<\/P><PRE class=\"codeSample\">strComputer = &#8220;.&#8221;<\/p>\n<p>Set objWMIService = GetObject(&#8220;winmgmts:\\\\&#8221; &amp; strComputer &amp; &#8220;\\root\\cimv2&#8221;)<\/p>\n<p>Do While True\n    Set colFileList = objWMIService.ExecQuery _\n        (&#8220;ASSOCIATORS OF {Win32_Directory.Name=&#8217;C:\\Logs&#8217;} Where &#8221; _\n            &amp; &#8220;ResultClass = CIM_DataFile&#8221;)<\/p>\n<p>    If colFileList.Count &gt;= 100 Then\n        Exit Do\n    End If<\/p>\n<p>    Wscript.Sleep 60000\nLoop<\/p>\n<p>Wscript.Echo &#8220;There are at least 100 log files in the target folder.&#8221;\n<\/PRE>\n<P>There are actually several different ways we could approach this problem; we ended up picking one that seemed pretty easy to script and pretty easy to understand. We begin by connecting to the WMI service on the local computer, although we could just as easily use this same script to monitor a folder on a remote computer; in that case all we have to do is assign the name of that computer (e.g., atl-fs-01) to the variable strComputer:<\/P><PRE class=\"codeSample\">strComputer = &#8220;atl-fs-01&#8221;\n<\/PRE>\n<P>We next set up a Do While loop, a loop seemingly designed to run forever and ever (or, at the very least, to continue running as long as True is equal to True):<\/P><PRE class=\"codeSample\">Do While True\n<\/PRE>\n<P>But don\u2019t worry; that only <I>sounds<\/I> like a mistake on our part. As you\u2019re about to see, our loop includes a loophole that enables us bring this seemingly-endless loop to an end.<\/P>\n<P>For our sample script we\u2019ve decided that 100 is the trigger value: if we ever get to 100 or more files in our target folder (C:\\Logs) we want to be notified. And that\u2019s a good question: how do we know how many files are in C:\\Logs in the first place? Well, a very simple way to determine that is to use the following WMI query, a query that returns a collection consisting of all the files in C:\\Logs:<\/P><PRE class=\"codeSample\">Set colFileList = objWMIService.ExecQuery _\n    (&#8220;ASSOCIATORS OF {Win32_Directory.Name=&#8217;C:\\Logs&#8217;} Where &#8221; _\n        &amp; &#8220;ResultClass = CIM_DataFile&#8221;)\n<\/PRE>\n<P>Admittedly, the syntax is a little weird here. However, all we\u2019re really doing is looking for items that are associated with a particular instance of the <B>Win32_Directory<\/B> class. (Which instance? The one with a <B>Name<\/B> of <I>C:\\Logs<\/I>.) Of course, we\u2019re only interested in these associated items if they, in turn, happen to be instances of the <B>CIM_DataFile<\/B> class; as you can probably guess, if something is an instance of the CIM_DataFile class then that something must be a file. This is kind of a roundabout way of doing things, but it\u2019s also WMI\u2019s way of returning a collection of all the files found in a given folder. If your files are stored in a different folder, well, then just replace the path <B>C:\\Logs<\/B> with the path to your folder.<\/P>\n<P>As it turns out, one of the nifty things about WMI collections is that each collection has a property named <B>Count<\/B>; this property tells us how many items (in this case, how many files) can be found in the collection. Hence our next line of code, which checks to see if the value of the Count property is greater than or equal to 100:<\/P><PRE class=\"codeSample\">If colFileList.Count &gt;= 100 Then\n<\/PRE>\n<TABLE class=\"dataTable\" id=\"EQF\" 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>. What if your target value is actually 10 files or 10,000 files or whatever number of files? No problem; just change 100 to the desired value.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>Let\u2019s assume that the Count <I>isn\u2019t<\/I> greater than or equal to 100; what happens then? Well, in that case we pause the script for 60 seconds (60,000 milliseconds):<\/P><PRE class=\"codeSample\">Wscript.Sleep 60000\n<\/PRE>\n<P>When one minute is up we then loop around and requery the folder C:\\Logs, once again checking to see how many files are in the folder. And yes, we do need to requery each time around; that\u2019s the only way to know the current number of files in the folder.<\/P>\n<P>This also means that we\u2019re checking every minute to see if the number of files in C:\\Logs has exceeded the target value of 100. However, you can also change this value to anything you desire. For example, maybe 60 seconds is too long; maybe the folder can fill up with files and bring the application to a crashing halt faster than that. OK; here\u2019s a minor modification that causes the script to pause for just 15 seconds (15,000 milliseconds) between checks:<\/P><PRE class=\"codeSample\">Wscript.Sleep 15000\n<\/PRE>\n<P>Alternatively, maybe you don\u2019t need to check every minute; maybe every 10 minutes is good enough. Fine. If there are 60,000 milliseconds in a minute (and there are), then there must be 600,000 milliseconds in 10 minutes. Thus this line of code, which pauses the script for 10 minutes between checks:<\/P><PRE class=\"codeSample\">Wscript.Sleep 600000\n<\/PRE>\n<P>Etc.<\/P>\n<P>Now, what if the Count <I>is<\/I> greater than or equal to 100? In that case we simply exit our \u201cendless\u201d loop:<\/P><PRE class=\"codeSample\">Exit Do\n<\/PRE>\n<P>And once we exit the loop we echo back a message informing us that the target value has been exceeded:<\/P><PRE class=\"codeSample\">Wscript.Echo &#8220;There are at least 100 log files in the target folder.&#8221;\n<\/PRE>\n<P>Now, admittedly, we don\u2019t <I>have<\/I> to exit the loop; we did that simply so we wouldn\u2019t get notified every minute that we had exceeded the target value. That\u2019s the advantage to exiting the loop: fewer nags. The disadvantage? After we restart the application (or whatever we need to do to head off trouble) we\u2019ll need to restart the monitoring script as well. If you don\u2019t mind repeated notifications then you could rewrite the script so that it keeps running (and notifying you) even after the target value has been reached:<\/P><PRE class=\"codeSample\">strComputer = &#8220;.&#8221;<\/p>\n<p>Set objWMIService = GetObject(&#8220;winmgmts:\\\\&#8221; &amp; strComputer &amp; &#8220;\\root\\cimv2&#8221;)<\/p>\n<p>Do While True\n    Set colFileList = objWMIService.ExecQuery _\n        (&#8220;ASSOCIATORS OF {Win32_Directory.Name=&#8217;C:\\Logs&#8217;} Where &#8221; _\n            &amp; &#8220;ResultClass = CIM_DataFile&#8221;)<\/p>\n<p>    If colFileList.Count &gt;= 100 Then\n        Wscript.Echo &#8220;There are at least 100 log files in the target folder.&#8221;\n    End If<\/p>\n<p>    Wscript.Sleep 60000\nLoop\n<\/PRE>\n<P>We should also mention that you aren\u2019t limited to using Wscript.Echo as a way to issue a notification. For example, you might want to <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/guide\/sas_log_akqy.mspx\" target=\"_blank\"><B>write an event to the Application event log<\/B><\/A>, or maybe <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/guide\/sas_ent_cueg.mspx\" target=\"_blank\"><B>send an email<\/B><\/A> using the SMTP service. That\u2019s entirely up to you.<\/P>\n<P>Of course, what would <I>really<\/I> be cool is if the script could fix the application for you. We can\u2019t provide any sample code because we don\u2019t know anything about the application. But it\u2019s possible that the script could stop and then restart the application; that depends entirely on the application. (At the very least, you could no doubt terminate the application process and then restart it. But, depending on the application, that might create more problems than it solves.)<\/P>\n<P>We hope that helps, AE, and we hope that, unlike the Scripting Guy who writes this column, you haven\u2019t lost your faith in humanity. As it is, and to add insult to injury, when he came to work this morning he stopped by the kitchen and grabbed a plastic spoon out of the big bin labeled <I>Plastic Spoons<\/I>. As he sat down in his office and prepared to eat his daily raspberry yogurt he suddenly realized that he was holding a plastic fork: someone had put a plastic fork in the bin labeled <I>Plastic Spoons<\/I>!<\/P>\n<P>Evil, pure evil.<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! We have a third-party application that rarely crashes; however, when it does crash it seriously disrupts our business. We can always tell when the application is getting ready to crash; at that point, one of its directories starts filling up with log files. How can we be notified any time the number [&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-64813","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! We have a third-party application that rarely crashes; however, when it does crash it seriously disrupts our business. We can always tell when the application is getting ready to crash; at that point, one of its directories starts filling up with log files. How can we be notified any time the number [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/64813","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=64813"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/64813\/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=64813"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=64813"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=64813"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}