{"id":66793,"date":"2006-07-31T10:18:00","date_gmt":"2006-07-31T10:18:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2006\/07\/31\/how-can-i-incrementally-rename-all-the-files-in-a-folder\/"},"modified":"2006-07-31T10:18:00","modified_gmt":"2006-07-31T10:18:00","slug":"how-can-i-incrementally-rename-all-the-files-in-a-folder","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-incrementally-rename-all-the-files-in-a-folder\/","title":{"rendered":"How Can I Incrementally Rename All the Files in a Folder?"},"content":{"rendered":"<p><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\"> \n<P>Hey, Scripting Guy! I have an unknown number of files in a folder. I need to rename them using this format: ABC_f<I>x<\/I>.inv, where <I>x<\/I> is an incremental number. How can I do that?<BR><BR>&#8212; RN<\/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, RN. You know, one of the Scripting Guys once had an idea for a very different kind of restaurant. Would you walk into this restaurant, sit down at a table, and then order from the menu? No way! Instead, you\u2019d walk in and pay a set price (say, $10) and you would <I>never<\/I> order from the menu. Instead, you\u2019d spin a wheel, and whatever item the wheel landed on is what you\u2019d get. <\/P>\n<P>Now, admittedly, that could be bad: if the wheel lands on a grilled-cheese sandwich, well, then you just spent $10 on a grilled-cheese sandwich. But suppose the wheel lands on steak-and-lobster? Now you\u2019ve gotten steak-and-lobster for just $10; that\u2019s not a bad deal at all. Looking for a unique dining experience? Look no further.<\/P>\n<P>So what does that have to do with incrementally renaming all the files in a folder? Nothing; we just wanted to mention the restaurant idea in case any venture capitalists happen to be reading this column. Guys, you know how to reach us.<\/P>\n<P>You know, that\u2019s a good idea: while we sit here and wait for the venture capital to start rolling in we might as well kill some time by answering RN\u2019s question. OK, RN, here\u2019s a script that will incrementally rename all the files in the folder C:\\Data:<\/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:\\Data&#8217;} Where &#8221; _\n        &amp; &#8220;ResultClass = CIM_DataFile&#8221;)<\/p>\n<p>i = 1<\/p>\n<p>For Each objFile in colFiles\n    strNewName = &#8220;C:\\Data\\ABC_f&#8221; &amp; i &amp; &#8220;.inv&#8221;\n    errResult = objFile.Rename(strNewName)\n    i = i + 1\nNext\n<\/PRE>\n<P>And yes, we\u2019d be happy to explain how this script works. (Note to potential investors: when\u2019s the last time you heard about <A href=\"http:\/\/www.foodnetwork.com\/food\/emeril_lagasse\/0,1974,FOOD_9823,00.html\" target=\"_blank\"><B>Emeril<\/B><\/A> or <A href=\"http:\/\/www.foodnetwork.com\/food\/mario_batali\/0,1974,FOOD_9906,00.html\" target=\"_blank\"><B>Mario Batali<\/B><\/A> taking the time to explain how a system administration script works?) As you can see, we start off by connecting to the WMI service on the local computer. Could we use this same script to rename files on a <I>remote<\/I> computer? Of course we could; all we have to do is assign the name of the remote computer to the variable strComputer. For example, this line of code causes the script to rename files on the remote computer atl-fs-01:<\/P><PRE class=\"codeSample\">strComputer = &#8220;atl-fs-01&#8221;\n<\/PRE>\n<P>Fine dining, scripts that connect to remote computers, and plenty of free parking. What more could you ask for?<\/P>\n<P>After connecting to the WMI service we then use this line of code to retrieve a collection of all the files in the folder C:\\Data:<\/P><PRE class=\"codeSample\">Set colFiles = objWMIService.ExecQuery _\n    (&#8220;ASSOCIATORS OF {Win32_Directory.Name=&#8217;C:\\Data&#8217;} Where &#8221; _\n        &amp; &#8220;ResultClass = CIM_DataFile&#8221;)\n<\/PRE>\n<P>We agree: it <I>is<\/I> a weird-looking line of code. But don\u2019t worry too much about that. If you\u2019d like to better understand how Associators Of queries work, then take a look at the <A href=\"http:\/\/msdn.microsoft.com\/library\/en-us\/wmisdk\/wmi\/swbemservices_associatorsof.asp\" target=\"_blank\"><B>WMI SDK<\/B><\/A>. Otherwise, just be content with the knowledge that if you\u2019d like to work with a different folder all you have to do here is replace C:\\Data with the path to that folder. Want to work with D:\\Accounting\\Invoices? OK:<\/P><PRE class=\"codeSample\">Set colFiles = objWMIService.ExecQuery _\n    (&#8220;ASSOCIATORS OF {Win32_Directory.Name=&#8217;D:\\Accounting\\Invoices&#8217;} Where &#8221; _\n        &amp; &#8220;ResultClass = CIM_DataFile&#8221;)\n<\/PRE>\n<P>As soon as we have a collection of all the files in the folder (and it doesn\u2019t matter how many files there are, this query grabs each and every one) we\u2019re ready to start renaming these babies. To do that, we first assign the value 1 to a counter variable named i:<\/P><PRE class=\"codeSample\">i = 1\n<\/PRE>\n<P>Why do we give this variable the value 1? Well, we want to incrementally name all the files in the folder, with the first file being file 1 (ABC_f<B>1<\/B>.inv), the second file being file 2, etc. Because we\u2019re using i as a way keep track of which number needs to be assigned to which file we logically need to start off with i being equal to 1.<\/P>\n<TABLE id=\"ERE\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD>\n<P><B>Note<\/B>. Would <A href=\"http:\/\/www.foodnetwork.com\/food\/rachael_ray\/0,1974,FOOD_9928,00.html\" target=\"_blank\"><B>Rachael Ray<\/B><\/A> know that we should set up a counter variable named i, and that we should set the value of i to 1? Well, we\u2019re not saying that she <I>wouldn\u2019t<\/I> know to do that; we\u2019re just pointing out that she doesn\u2019t talk much about counter variables on her cooking show.<\/P>\n<P>Seems kind of strange to us, too.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>Our next step is to set up a For Each loop to loop through all the files in the collection (which, of course, corresponds quite nicely to all the files in the folder C:\\Data). Inside that loop we execute these three lines of code:<\/P><PRE class=\"codeSample\">strNewName = &#8220;C:\\Data\\ABC_f&#8221; &amp; i &amp; &#8220;.inv&#8221;\nerrResult = objFile.Rename(strNewName)\ni = i + 1\n<\/PRE>\n<P>In line 1 we\u2019re constructing a new file name (or, to be a bit more accurate, a new file path). To do that we simply combine the following items:<\/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>C:\\Data\\ABC_f<\/B><\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P>The counter variable i (which, the first time through the loop, is equal to <B>1<\/B>)<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P><B>.inv<\/B><\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<P>Add them altogether and you get this:<\/P>\n<P>C:\\Data\\ABC_f + 1 + .inv = <B>C:\\Data\\ABC_f1.inv<\/B><\/P>\n<P>As it turns out, C:\\Data\\ABC_f1.inv is exactly the file path we need to use for the first file in the collection. And note that we <I>do<\/I> need to use the complete path when using WMI to rename files; the file name alone won\u2019t do us any good.<\/P>\n<P>Once we have the complete path renaming the file is as easy as calling the <B>Rename<\/B> method and passing this method the file path we just constructed:<\/P><PRE class=\"codeSample\">errResult = objFile.Rename(strNewName)\n<\/PRE>\n<P>So much for file 1. In order to rename file 2 in the collection we increment the value of i by 1 (meaning i is now equal to 2), then loop around and repeat this process with file 2. This continues until we have incrementally renamed each and every file in the folder.<\/P>\n<P>A few quick notes here. First, by default files returned using a WMI query come back in alphabetical order. That means that the file that comes first alphabetically \u2013 for example, AAAA.txt \u2013 is going to be the first file to be renamed (and thus get the name ABC_f1.inv). Would it be possible to use a different order when it comes to renaming files, such as making the oldest file in the folder ABC_f1.inv? Yes, but not without adding additional code throughout the script. If that\u2019s something someone out there needs to do, let us know.<\/P>\n<P>Second, this script does what it\u2019s supposed to do: it renames all the files in the folder. But suppose you already have a file named ABC_f1.inv. In a case like that, you might want to leave that file alone, and thus give the first file you <I>do<\/I> rename the moniker ABC_f<B>2<\/B>.inv. Will this script help you out in that situation? No. But, again, if a script like that would be useful to you just let us know. <\/P>\n<P>Finally, you\u2019re right: it\u2019s highly unlikely that <A href=\"http:\/\/www.marthastewart.com\/\" target=\"_blank\"><B>Martha Stewart<\/B><\/A> would ever explain how you could write a script to handle any of these scenarios. But, in all fairness, that might not be Martha\u2019s fault. One of the Scripting Guys actually wanted to ask Martha Stewart to make a guest appearance during the <A href=\"http:\/\/null\/technet\/scriptcenter\/webcasts\/archive.mspx\"><B>Scripting Week 2<\/B><\/A> webcasts, but he was told he couldn\u2019t bring in outside guests. For all we know Martha Stewart <I>could<\/I> explain how to write a script; after all, she seems to know how to do pretty much everything else. She just never got the chance. Like we were told: no \u201cguest stars\u201d on TechNet webcasts.<\/P>\n<TABLE id=\"EDH\" 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>. Of course, this Scripting Guy was also told that no one would go to a restaurant where they spun a wheel and then had to order whatever item the wheel pointed to. We\u2019ll see, both about the new restaurant <I>and<\/I> about Martha Stewart.<\/P><\/TD><\/TR><\/TBODY><\/TABLE><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! I have an unknown number of files in a folder. I need to rename them using this format: ABC_fx.inv, where x is an incremental number. How can I do that?&#8212; RN Hey, RN. You know, one of the Scripting Guys once had an idea for a very different kind of restaurant. Would [&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,38,11,3,12,5],"class_list":["post-66793","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-associators-of","tag-files","tag-folders","tag-scripting-guy","tag-storage","tag-vbscript"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! I have an unknown number of files in a folder. I need to rename them using this format: ABC_fx.inv, where x is an incremental number. How can I do that?&#8212; RN Hey, RN. You know, one of the Scripting Guys once had an idea for a very different kind of restaurant. Would [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/66793","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=66793"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/66793\/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=66793"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=66793"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=66793"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}