{"id":63413,"date":"2007-12-12T01:14:00","date_gmt":"2007-12-12T01:14:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2007\/12\/12\/hey-scripting-guy-how-can-i-delete-files-that-are-a-specified-number-of-hours-old\/"},"modified":"2007-12-12T01:14:00","modified_gmt":"2007-12-12T01:14:00","slug":"hey-scripting-guy-how-can-i-delete-files-that-are-a-specified-number-of-hours-old","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/hey-scripting-guy-how-can-i-delete-files-that-are-a-specified-number-of-hours-old\/","title":{"rendered":"Hey, Scripting Guy! How Can I Delete Files That Are a Specified Number of Hours Old?"},"content":{"rendered":"<p><H2><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\"> <\/H2>\n<P>Hey, Scripting Guy! I\u2019ve seen scripts that let you delete all the files in a folder that are X number of days old. I have a different problem: I\u2019d like to delete files that are X number of hours, or even X number of <I>minutes<\/I>, old. How can I do that?<BR><BR>&#8212; DF<\/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, DF. Did you see where some researchers are predicting that, by the year 2050, humans and robots might actually marry one another? In fact, outside of possible ethical concerns, these researchers see absolutely no reason why such marriages won\u2019t take place by the year 2050, at the latest.<\/P>\n<P>Although he\u2019s hardly an expert in robotics or artificial intelligence, the Scripting Guy who writes this column is a bit more skeptical. After all, look at the state of robotics today. For example, robots might be good at doing one thing (spot-welding an automobile on the assembly line; vacuuming a living room) but they\u2019re still more idiot savant than jack-of-all-trades. Robots aren\u2019t very good at conversation; robots pay no attention to <I>your<\/I> feelings; robots are highly unlikely to give you a little something \u2013 not even a card \u2013 on your birthday. Robots can\u2019t fend for themselves; you have to do pretty much everything for them. Robots \u2013 <\/P>\n<P>You know, come to think of it, for the typical female, transitioning from the typical male to a robot probably won\u2019t be that big of a deal, will it?<\/P>\n<P>Interestingly enough, researchers are <I>not<\/I> predicting that, by the year 2050, robots will be writing the <I>Hey, Scripting Guy!<\/I> column. Many would say that\u2019s because some tasks are too trivial and too mindless even for robots. However, we like to believe that\u2019s because that no robot could ever write a script that, like this one, deletes all the files in the folder C:\\Scripts that are more than 8 hours old:<\/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>Set colFiles = objWMIService.ExecQuery _\n    (&#8220;ASSOCIATORS OF {Win32_Directory.Name=&#8217;C:\\Scripts&#8217;} Where &#8221; _\n        &amp; &#8220;ResultClass = CIM_DataFile&#8221;)<\/p>\n<p>strCurrentDate = Now<\/p>\n<p>For Each objFile In colFiles\n    strFileDate = WMIDateStringToDate(objFile.CreationDate)\n    intHours = DateDiff(&#8220;h&#8221;, strFileDate, strCurrentDate)\n    If intHours &gt;= 8 Then\n        Wscript.Echo objFile.Delete\n    End If\nNext<\/p>\n<p>Function WMIDateStringToDate(dtmInstallDate)\n    WMIDateStringToDate = CDate(Mid(dtmInstallDate, 5, 2) &amp; &#8220;\/&#8221; &amp; _\n        Mid(dtmInstallDate, 7, 2) &amp; &#8220;\/&#8221; &amp; Left(dtmInstallDate, 4) _\n            &amp; &#8221; &#8221; &amp; Mid (dtmInstallDate, 9, 2) &amp; &#8220;:&#8221; &amp; _\n                Mid(dtmInstallDate, 11, 2) &amp; &#8220;:&#8221; &amp; Mid(dtmInstallDate, _\n                    13, 2))\nEnd Function\n<\/PRE>\n<P>OK, let\u2019s see if we can figure out how this baby works. (And no, we don\u2019t need any help from any of the robots reading this column. Although we apparently need help <A href=\"http:\/\/www.motoman.com\/products\/nonindustrial\/robobar.htm\" target=\"_blank\"><B>mixing a Tequila Sunrise<\/B><\/A>, we humans can still explain our own scripts, thank you very much.)<\/P>\n<P>As you can see (unless you\u2019re a robot, in which case your laser vision probably caught the computer screen on fire), we start out by connecting to the WMI service on the local computer. Just a moment; it looks like we question. You in the back, the one with the metallic voice. Can you run this script against a remote computer? You bet you can; all you have to do is assign the name of that remote computer to the variable strComputer, like so:<\/P><PRE class=\"codeSample\">strComputer = &#8220;.&#8221;\n<\/PRE>\n<TABLE id=\"EXD\" 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>. No, we don\u2019t have the remote computer\u2019s IP address. You\u2019ll have to ask her for that yourself.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>After connecting to the WMI service we then use this line of code, and an <B>Associators Of<\/B> query, to retrieve a collection of all the files (instances of the <B>CIM_DataFile<\/B> class) found in the folder C:\\Scripts. Once we have the collection in hand, we then assign the current date and time to a variable named strCurrentDate. That\u2019s what this line of code is for:<\/P><PRE class=\"codeSample\">strCurrentDate = Now\n<\/PRE>\n<P>At this point, we\u2019re ready to go and delete some files.<\/P>\n<P>To do that, our first step is to set up a For Each loop that loops through all the files in the folder C:\\Scripts. Inside that loop, the first thing we do is execute this line of code:<\/P><PRE class=\"codeSample\">strFileDate = WMIDateStringToDate(objFile.CreationDate)\n<\/PRE>\n<P>What\u2019s going on here? Well, what going on here is that we\u2019recalling a function named WMIDateStringToDate, passing the file\u2019s <B>CreationDate<\/B> property as the function parameter. WMIDateStringToDate is going to take the CreationDate, perform a little formatting magi on that date, then store the reformatted value in a variable named strFileDate.<\/P>\n<P>Why do we go through all those gyrations? Well, as you know (and as even most robots know) WMI stores date-time values in the UTC (Universal Time Coordinate) format. Is that a problem? You bet it is; that means dates and times look like this:<\/P><PRE class=\"codeSample\">20071211094327.000000+420\n<\/PRE>\n<P>As you might expect, date arithmetic is none-too-easy when you have dates and times that look like that. Our function is designed to do something about that.<\/P>\n<P>We aren\u2019t going to talk about UTC dates and times today, nor are we going to explain the function WMIDateStringToDate function in any detail; if you\u2019d like more information on either of those topics, see the <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/guide\/sas_wmi_fvwp.mspx\" target=\"_blank\"><B>Microsoft Windows 200 Scripting Guide<\/B><\/A>. Instead, we\u2019ll simply note that the individual pieces of a typical date are actually stored at predefined locations within a UTC value; for example, the first four digits (2007) represent the year, the two digits after that represent the month; and so on. What our function is doing is simply taking a UTC value (the CreationDate property) and constructing a more readable (OK, OK: more <I>human<\/I> readable) date from those various pieces. The net result? The variable strFileDate gets assigned a value like this:<\/P><PRE class=\"codeSample\">12\/11\/2007 09:43.27\n<\/PRE>\n<P>That\u2019s a value that humans find much easier to deal with. More importantly, it\u2019s also a value that VBScript finds easier to deal with.<\/P>\n<P>Speaking of which, as soon as we get the reformatted date-time value back from the function we hand that value off to VBScript and its <B>DateDiff<\/B> function:<\/P><PRE class=\"codeSample\">intHours = DateDiff(&#8220;h&#8221;, strFileDate, strCurrentDate) \n<\/PRE>\n<P>What DateDiff does is determine the amount of time that has (or that will) elapse between two dates. As you can see, we pass three parameters when we call DateDiff:<\/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>&#8220;h&#8221;<\/B>. This represents the time interval we want to get back. We want to determine the age of a file in hours; hence we pass the value &#8220;h&#8221;. To get the age in minutes we\u2019d use this value: <B>&#8220;n&#8221;<\/B>. For a complete list of parameters available to the DateDiff function see \u2013 you guessed it: see the <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/guide\/sas_vbs_ufbq.mspx\" target=\"_blank\"><B>Microsoft Windows 2000 Scripting Guide<\/B><\/A>.<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P><B>strFileDate<\/B>. The date and time that the file was created.<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P><B>strCurrentDate<\/B>. The current date and time. (Or at least the current date and time when the script first started.)<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<P>As we noted, DateDiff will calculate the age of the file in hours, then store that value in the variable intHours. We then use this line of code to determine if the file is more than 8 hours old:<\/P><PRE class=\"codeSample\">If intHours &gt;= 8 Then\n<\/PRE>\n<TABLE id=\"EGG\" 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>. OK, technically we check to see if each file is greater than or equal to 8. Why? Because the DateDiff function returns integer values only, and constructs those integers by removing any decimal points (not by rounding up or down). For example, suppose a file is 8.5 hours (8 hours and 30 minutes old). In that case, DateDiff will report that the file is 8 hours old; because 8 isn\u2019t greater than 8, this file wouldn\u2019t be deleted. Using the greater than or equal to operator takes care of that problem.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>If the file <I>is<\/I> older than 8 hours we then call the <B>Delete<\/B> method and delete the file. If it isn\u2019t, then we simply zip back to the top of the loop and repeat the process with the next file in the collection. By the time we\u2019re done the only files left in C:\\Scripts will be those files less than 8 hours old. That\u2019s all we have to do.<\/P>\n<P>In case you\u2019re wondering, as part of his research the Scripting Guy who writes this column took a quick tour around the Internet looking for information about robots. When he did so, he stumbled upon <A href=\"http:\/\/www.geckosystems.com\/products\/carebot3.php\" target=\"_blank\"><B>Carebot 3.4<\/B><\/A>. One of Carebot\u2019s primary purposes in life is to follow you around everywhere you go, verbally reminding you of all the things you\u2019re supposed to be doing but apparently aren\u2019t doing at that very moment. <\/P>\n<P>You know, come to think of it, for the typical male, transitioning from the typical female to a robot probably won\u2019t be that big of a deal, will it?<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! I\u2019ve seen scripts that let you delete all the files in a folder that are X number of days old. I have a different problem: I\u2019d like to delete files that are X number of hours, or even X number of minutes, old. How can I do that?&#8212; DF Hey, DF. Did [&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":[715,13,38,3,4,12,5],"class_list":["post-63413","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-associators-of","tag-dates-and-times","tag-files","tag-scripting-guy","tag-scripting-techniques","tag-storage","tag-vbscript"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! I\u2019ve seen scripts that let you delete all the files in a folder that are X number of days old. I have a different problem: I\u2019d like to delete files that are X number of hours, or even X number of minutes, old. How can I do that?&#8212; DF Hey, DF. Did [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/63413","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=63413"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/63413\/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=63413"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=63413"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=63413"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}