{"id":66013,"date":"2006-11-17T16:46:00","date_gmt":"2006-11-17T16:46:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2006\/11\/17\/how-can-i-delete-all-the-bak-files-in-a-folder-that-are-more-than-7-days-old\/"},"modified":"2006-11-17T16:46:00","modified_gmt":"2006-11-17T16:46:00","slug":"how-can-i-delete-all-the-bak-files-in-a-folder-that-are-more-than-7-days-old","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-delete-all-the-bak-files-in-a-folder-that-are-more-than-7-days-old\/","title":{"rendered":"How Can I Delete All the .BAK Files in a Folder That Are More Than 7 Days Old?"},"content":{"rendered":"<p><img decoding=\"async\" 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\"><\/p>\n<p>Hey, Scripting Guy! How can I delete all the .BAK files in a folder that are more than 7 days old?<\/p>\n<p>&#8212; KT<\/p>\n<p><img decoding=\"async\" height=\"5\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" border=\"0\"><img decoding=\"async\" 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 decoding=\"async\" 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><\/p>\n<p>Hey, KT. You know, on his way to work this morning the Scripting Guy who writes this column heard an advertisement for a local seafood restaurant. Now, this Scripting Guy doesn\u2019t like seafood, so he normally wouldn\u2019t pay any attention to an ad for a restaurant like this. However, his interest was piqued when the ad pointed out that this was the only restaurant in the Seattle area that served crab ice cream. As you might expect, the Scripting Guy who writes this column was shocked: Seattle considers itself a world-class city, yet it only has one restaurant that serves crab ice cream?!? That\u2019s an outrage, pure and simple.<\/p>\n<p>And we agree with you: someone <i>should<\/i> be fired over that. Those of you who live in other cities have no idea how good you have it. After all, any time you get a craving for crab ice cream you can probably just walk outside your front door and see half-a-dozen places where you can satisfy that craving. Sadly, that\u2019s not true for those of us stuck in the Seattle area.<\/p>\n<table class=\"dataTable\" id=\"EAD\" 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>. If you\u2019ve ever eaten crab ice cream, drop us a line and let us know; we\u2019d love to hear about it. We\u2019d also be interested in knowing how big the guy was who forced you to eat the stuff.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>Admittedly we\u2019re still a little shaken by all this, but we\u2019ll try to answer your question anyway, KT. Not that this doesn\u2019t represent something of an outrage itself: after all, deleting a specific type of file based on the file creation date is harder than it really should be. OK, we should qualify that a bit: doing this on the local computer isn\u2019t <i>too<\/i> bad. But in this day and age, who wants to do everything on the local computer? If you want to perform this kind of task remotely \u2013 and we know that many of you do \u2013 things can get a little tricky. But that\u2019s all right. Here\u2019s a reasonably straightforward way to delete all the .BAK files in a folder that are more than 7 days old, and on either the local machine or a remote machine to boot:<\/p>\n<pre class=\"codeSample\">dtmDate = Date - 7\nstrDay = Day(dtmDate)\nIf Len(strDay) &lt; 2 Then\n    strDay = \"0\" &amp; strDay\nEnd If\nstrMonth = Month(dtmDate)\nIf Len(strMonth) &lt; 2 Then\n    strMonth = \"0\" &amp; strMonth\nEnd If\nstrYear = Year(dtmDate)\nstrTargetDate = strYear &amp; strMonth &amp; strDay\nstrComputer = \".\"\nSet objWMIService = GetObject(\"winmgmts:\\\\\" &amp; strComputer &amp; \"\\root\\cimv2\")\nSet FileList = objWMIService.ExecQuery _\n    (\"ASSOCIATORS OF {Win32_Directory.Name='C:\\Scripts'} Where \" _\n        &amp; \"ResultClass = CIM_DataFile\")\nFor Each objFile In FileList\n    strDate = Left(objFile.CreationDate, 8)\n    If strDate &lt; strTargetDate Then\n        If objFile.Extension = \"bak\" Then\n            objFile.Delete\n        End If\n    End If\nNext\n<\/pre>\n<p>And don\u2019t worry; as soon as we finish this dish of crab ice cream we\u2019ll explain how this all works.<\/p>\n<p>OK. The first thing we need to do is calculate our target date: in this case, that\u2019s the current date minus 7 days. That\u2019s what we do in this first line of code:<\/p>\n<pre class=\"codeSample\">dtmDate = Date - 7\n<\/pre>\n<p>Because we\u2019re going to use WMI we next need to convert dtmDate to a UTC-like date time value. We won\u2019t discuss the UTC date-time format today; for more information see the <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/guide\/sas_wmi_fvwp.mspx\"><b>Microsoft Windows 2000 Scripting Guide<\/b><\/a>. For now all we need to know is that we must convert a date like 11\/16\/2006 to this, with the first four digits representing the year, the next two digits representing the month, and the last two digits representing the day:<\/p>\n<pre class=\"codeSample\">20061116\n<\/pre>\n<p>It\u2019s pretty easy to extract the individual pieces of a date-time value; we can do that using the <b>Day<\/b>, <b>Month<\/b>, and <b>Year<\/b> functions. The one tricky part occurs when we have a date like 6\/5\/2006. In that case both the month (6) and the day (5) have only one digit. Why is that a problem? That\u2019s a problem because, in the UTC format, the month and the day <i>must<\/i> be two digits longs. To deal with that problem we\u2019ve included code like this for both the day and the month:<\/p>\n<pre class=\"codeSample\">strDay = Day(dtmDate)\nIf Len(strDay) &lt; 2 Then\n    strDay = \"0\" &amp; strDay\nEnd If\n<\/pre>\n<p>What are we doing here? Well, we\u2019re first using the Day function to grab the day portion of the target date and store it in a variable named strDay. We then use the <b>Len<\/b> function to check the number of characters in strDay. If strDay has less than 2 characters we use this line of code to tack a leading zero onto the value:<\/p>\n<pre class=\"codeSample\">strDay = \"0\" &amp; strDay\n<\/pre>\n<p>In other words, if strDay equals 5, the preceding block of code will add a leading zero, making strDay equal to this:<\/p>\n<pre class=\"codeSample\">05\n<\/pre>\n<p>Sometimes we Scripting Guys are so clever it\u2019s scary, isn\u2019t it? <i>(Editor\u2019s Note: Never as scary as crab ice cream though.)<\/i><\/p>\n<p>After assuring ourselves that both the day and month have two digits, we then use this line of code to combine the year, month, and day into a UTC-like value:<\/p>\n<pre class=\"codeSample\">strTargetDate = strYear &amp; strMonth &amp; strDay\n<\/pre>\n<p>Our next step is to connect to the WMI service on the local computer (although, again, we could just as easily run this script against a remote machine). We then use this crazy-looking query to return a collection of all the files found in the folder C:\\Scripts:<\/p>\n<pre class=\"codeSample\">Set FileList = objWMIService.ExecQuery _\n    (\"ASSOCIATORS OF {Win32_Directory.Name='C:\\Scripts'} Where \" _\n        &amp; \"ResultClass = CIM_DataFile\")\n<\/pre>\n<p>Good point: we aren\u2019t interested in <i>all<\/i> the files in C:\\Scripts, are we? Instead, we\u2019re interested only in .BAK files older than our target date. Don\u2019t worry; we haven\u2019t forgotten that. However, while it\u2019s theoretically possible to write a WMI query that returns just those files, writing a query like that is probably more trouble that it\u2019s worth. (Just like going all the way to the ice cream shop and finding out that all they have is crab ice cream.) We found it easier to instead return <i>all<\/i> the files, then simply going through the collection one-by-one , deleting those files that meet our criteria.<\/p>\n<p>So how do we do that? Well, to begin with, we set up a For Each loop to loop through all the files in the collection. Inside that loop we use the <b>Left<\/b> function to grab the first 8 characters of the <b>CreationDate<\/b> property (a value that will be in UTC format) and store those characters in a variable named strDate:<\/p>\n<pre class=\"codeSample\">strDate = Left(objFile.CreationDate, 8)\n<\/pre>\n<p>Why do we do that? Well, let\u2019s say that this particular file was created on 10\/30\/2006. If that\u2019s the case, that makes strDate equal to 20061030, a UTC-like value if we ever saw one. That also means that we can compare strDate to our target date by using code like this:<\/p>\n<pre class=\"codeSample\">If strDate &lt; strTargetDate Then\n<\/pre>\n<p>What if strDate <i>is<\/i> less than our target date? That means that this file is <i>potentially<\/i> a candidate for deletion. Why \u201cpotentially?\u201d Well, remember, we want to delete only files that have a .BAK file extension. Therefore, we need to make a second check, one that looks at the file extension to see if it is equal to <i>bak<\/i> (note that, in WMI, you don\u2019t include the period in the file extension):<\/p>\n<pre class=\"codeSample\">If objFile.Extension = \"bak\" Then\n<\/pre>\n<p>If we do have a .BAK file older than the target date we then use this line of code to delete the file:<\/p>\n<pre class=\"codeSample\">objFile.Delete\n<\/pre>\n<p>Otherwise we simply loop around and repeat the process with the next file in the collection. When we\u2019re all done each and every .BAK file in the C:\\Scripts folder (or at least those .BAK files older than our target date) will be gone.<\/p>\n<p>Interestingly enough, in the course of researching this column we not only figured out how to delete old .BAK files, but we also discovered a way to enjoy crab ice cream. Here\u2019s the secret: get a big glob of chocolate syrup. (Hot fudge is best, but any chocolate syrup will do.) Next, get a can of whipped cream and some chopped nuts (we\u2019d recommend walnuts). Pour the syrup into a bowl, then top with the nuts and whipped cream. Finally, throw the crab ice cream away and just eat the syrup, nuts, and whipped cream. Delicious!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! How can I delete all the .BAK files in a folder that are more than 7 days old? &#8212; KT Hey, KT. You know, on his way to work this morning the Scripting Guy who writes this column heard an advertisement for a local seafood restaurant. Now, this Scripting Guy doesn\u2019t like [&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-66013","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 delete all the .BAK files in a folder that are more than 7 days old? &#8212; KT Hey, KT. You know, on his way to work this morning the Scripting Guy who writes this column heard an advertisement for a local seafood restaurant. Now, this Scripting Guy doesn\u2019t like [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/66013","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=66013"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/66013\/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=66013"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=66013"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=66013"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}