{"id":70843,"date":"2004-12-09T19:07:00","date_gmt":"2004-12-09T19:07:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2004\/12\/09\/how-can-i-rename-files-based-on-the-files-creation-date\/"},"modified":"2004-12-09T19:07:00","modified_gmt":"2004-12-09T19:07:00","slug":"how-can-i-rename-files-based-on-the-files-creation-date","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-rename-files-based-on-the-files-creation-date\/","title":{"rendered":"How Can I Rename Files Based on the File\u2019s Creation Date?"},"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! I have a folder that contains a bunch of log files. I would like to rename each file based on the date the file was created; for example, if a file was created on December 1, 2004, I\u2019d like to rename it 20041201.log. Is that possible?<BR><BR>&#8212; CK<\/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, CK. Listen, when it comes to scripting, anything is possible. (Well, except for the things that aren\u2019t possible, of course.) And while dates can often times be tricky to work with in your WMI scripts, this is one time when WMI\u2019s date format actually makes it <I>easy<\/I> to carry out a task.<\/P>\n<P>To help explain how to do this, let\u2019s break the task into two pieces. First, how do we list all the files in a folder, as well as their creation dates? Well, one way is to use a script similar to this:<\/P><PRE class=\"codeSample\">strComputer = &#8220;.&#8221;\nSet objWMIService = GetObject(&#8220;winmgmts\\\\&#8221; &amp; strComputer &amp; &#8220;\\root\\cimv2&#8221;)<\/p>\n<p>Set FileList = 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>For Each objFile In FileList\n    Wscript.Echo objFile.CreationDate\nNext\n<\/PRE>\n<P>In this script, we bind to the WMI service and then use an association query to return a collection of all the files in the folder C:\\Logs. If you aren\u2019t familiar with association queries, they do pretty much what the name implies: they provide a way to associate two separate WMI classes, in this case, Win32_Directory and CIM_DataFile. The net effect is that this enables us to get back a collection of all the files in the associated folder.<\/P>\n<P>After we have all the files, we simply create a For-Each loop, and then echo the value of the <B>CreationDate<\/B> property for each of these files. Because WMI uses the UTC (Universal Time Coordinate) format, we\u2019ll get back values that look like this:<\/P><PRE class=\"codeSample\">20041201202723.695209-480\n<\/PRE>\n<P>Sure, that\u2019s weird-looking, but guess what: the first eight characters happen to correspond to the year, month, and day, the very values you want to use as file names. You want a file name like 20041201? Take a look at the first eight characters in our UTC date: <B>20041201<\/B>202723.695209-480. Just what the doctor ordered.<\/P>\n<P>In fact, to get the file name, all we need to do is use VBScript\u2019s Left function to grab those first eight characters in our UTC date. This modified script takes those first eight characters, stores them in a variable named strDate, and then echoes <I>that<\/I> value:<\/P><PRE class=\"codeSample\">strComputer = &#8220;.&#8221;\nSet objWMIService = GetObject(&#8220;winmgmts:\\\\&#8221; &amp; strComputer &amp; &#8220;\\root\\cimv2&#8221;)<\/p>\n<p>Set FileList = 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>For Each objFile In FileList\n    strDate = Left(objFile.CreationDate, 8)\n    Wscript.Echo strDate\nNext\n<\/PRE>\n<P>So much for step 1. Now it\u2019s time for the second &#8211; and final &#8211; step: renaming each of the files. Let\u2019s show you the script, and then explain how it works:<\/P><PRE class=\"codeSample\">strComputer = &#8220;.&#8221;\nSet objWMIService = GetObject(&#8220;winmgmts:\\\\&#8221; &amp; strComputer &amp; &#8220;\\root\\cimv2&#8221;)<\/p>\n<p>Set FileList = 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>For Each objFile In FileList\n    strDate = Left(objFile.CreationDate, 8)\n    strNewName = objFile.Drive &amp; objFile.Path &amp; strDate &amp; &#8220;.&#8221; &amp; &#8220;log&#8221;\n    errResult = objFile.Rename(strNewName)\nNext\n<\/PRE>\n<P>The tricky part here lies in constructing the new file name. When you rename a file using WMI, you can\u2019t just specify a new name; for example, we can\u2019t simply rename the file <B>Wednesday.log<\/B> to <B>20041201.log<\/B>. Instead, we have to specify the entire path, and rename the file <B>C:\\Logs\\20041201.log<\/B>. That\u2019s what this line of code does:<\/P><PRE class=\"codeSample\">strNewName = objFile.Drive &amp; objFile.Path &amp; strDate &amp; &#8220;.log&#8221;\n<\/PRE>\n<P>What we\u2019re doing here is combining the drive where the file resides (<B>C:<\/B>), the folder path on that drive (<B>\\Logs\\<\/B>), the new name for the file (<B>20041201<\/B>, the value of our variable strDate), and the new file extension (<B>.log<\/B>). Put those all together, and you end up with <B>C:\\Logs\\20041201.log<\/B>, which just happens to be the complete path we want to assign the file. All we have to do now is call the Rename method and we\u2019ll change the file name.<\/P>\n<P>Incidentally, we know it seems a bit odd to have to supply the entire path just to rename a file. If there\u2019s a bright side to this, however, it\u2019s the fact that you can use this same approach to move files to another folder. For example, suppose you not only wanted to rename the files, but you also wanted to move them to a folder name C:\\Backups. In that case, you could use a script similar to this, which replaces the current file path (<B>\\Logs\\<\/B>) with the new path (<B>\\Backups\\<\/B>). Run this script, and the files will not only be renamed, they will also be moved to C:\\Backups:<\/P><PRE class=\"codeSample\">strComputer = &#8220;.&#8221;\nSet objWMIService = GetObject(&#8220;winmgmts:\\\\&#8221; &amp; strComputer &amp; &#8220;\\root\\cimv2&#8221;)<\/p>\n<p>Set FileList = 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>For Each objFile In FileList\n    strDate = Left(objFile.CreationDate, 8)\n    strNewName = objFile.Drive &amp; &#8220;\\Backups\\&#8221; &amp;  strDate &amp; &#8220;.log&#8221;\n    errResult = objFile.Rename(strNewName)\nNext\n<\/PRE>\n<P>The only problem with the script we\u2019ve shown you is that it will blow up if you have files with the same creation date; after all, the script will try to create two files named, say, 20041201.log, and the file system just doesn\u2019t like to have identically-named files in the same folder. If that\u2019s an issue, here\u2019s a sample script that checks to see if a file name is unique before it actually renames the file. For example, suppose the folder already has a file named 20041201.log. If that happens, this script (which we won\u2019t explain in detail today) will create a new file name: 20041201_2.log and check to see if <I>that<\/I> file exists. If it does, it will try 20041201_3.vbs, and continue trying until it creates a unique name. At that point it renames the file:<\/P><PRE class=\"codeSample\">strComputer = &#8220;.&#8221;\nSet objWMIService = GetObject(&#8220;winmgmts:\\\\&#8221; &amp; strComputer &amp; &#8220;\\root\\cimv2&#8221;)<\/p>\n<p>Set FileList = 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>For Each objFile In FileList\n    strDate = Left(objFile.CreationDate, 8)\n    strNewName = objFile.Drive &amp; objFile.Path &amp; _\n       strDate &amp; &#8220;.&#8221; &amp; &#8220;log&#8221;\n    strNameCheck = Replace(strNewName, &#8220;\\&#8221;, &#8220;\\\\&#8221;)<\/p>\n<p>    i = 1\n    Do While True\n        Set colFiles = objWMIService.ExecQuery _\n            (&#8220;Select * from Cim_Datafile Where Name = &#8216;&#8221; &amp; strNameCheck &amp; &#8220;&#8216;&#8221;)\n        If colFiles.Count = 0 Then\n            errResult = objFile.Rename(strNewName)\n            Exit Do\n        Else\n            i = i + 1\n            strNewName = objFile.Drive &amp; objFile.Path &amp; _\n                strDate &amp; &#8220;_&#8221; &amp; i &amp; &#8220;.&#8221; &amp; &#8220;log&#8221;\n            strNameCheck = Replace(strNewName, &#8220;\\&#8221;, &#8220;\\\\&#8221;)\n        End If\n    Loop\nNext\n<\/PRE>\n<P>Yes, it\u2019s a little complicated, which is why we\u2019re saving the explanation for another day. Hey, you don\u2019t really expect to put in any overtime on this column, do you?<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! I have a folder that contains a bunch of log files. I would like to rename each file based on the date the file was created; for example, if a file was created on December 1, 2004, I\u2019d like to rename it 20041201.log. Is that possible?&#8212; CK Hey, CK. Listen, when it [&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,3,12,5],"class_list":["post-70843","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-files","tag-scripting-guy","tag-storage","tag-vbscript"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! I have a folder that contains a bunch of log files. I would like to rename each file based on the date the file was created; for example, if a file was created on December 1, 2004, I\u2019d like to rename it 20041201.log. Is that possible?&#8212; CK Hey, CK. Listen, when it [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/70843","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=70843"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/70843\/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=70843"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=70843"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=70843"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}