Use PowerShell to Rename Files in Bulk


Summary: Learn how to use Windows PowerShell to rename files in bulk.

Microsoft Scripting Guy, Ed Wilson, is here. Matt Tisdale is back today with another solution to a situation at work…

I received a call from a gentleman named Cristofer this afternoon. He had a business need and he heard from someone that Windows PowerShell could help. I told him that I am sure Windows PowerShell can help—and that was before I even heard the question.

His immediate need was to rename almost 250 files that are located in various folders on the file system. He needed to find all files with a specific character string in the name and replace this character string with a new character string. For example purposes, let’s say he needed to find all files with “current” in the name and replace “current” with “old”.

I have never attempted this specific task, but by using Get-Command and Get-Help, we were able to find exactly how to do this in a couple of minutes. Assuming we need to find all files located under C:temp (including all subfolders) with “current” in the name and rename them using “old” in place of “current”, here are the steps.

  1. Open Windows PowerShell.
  2. Navigate to C:temp.
  3. Run the following Windows PowerShell command:

Get-ChildItem -Filter “*current*” -Recurse | Rename-Item -NewName {$_.name -replace ‘current’,’old’ }

      4. Sit back and let Windows PowerShell do all of the work for you.

Anyone who has access to modify the files and is running Windows 7 can follow these steps. No special tools or elevated rights are required.

Let’s pick the command apart and explain each piece.

  • Get-ChildItem -Filter “*current*”

Finds all files with the string “current” anywhere in the name.

  • -Recurse

Instructs Get-ChildItem to search recursively through all subfolders under the start point (the current directory where the command is run from).

  • | (the pipe character)

Instructs Windows PowerShell to take each item (object) found with the first command (Get-ChildItem) and pass it to the second command (Rename-Item)

  • Rename-Item

Renames files and other objects

  • {$_.name -replace ‘current’,’old’ }

Tells Rename-Item to find the string “current” in the file name and replace it with “old”.

For an added bonus, I also recommended that Cristofer use the –WhatIf parameter with this command on his first run to get an output that shows what the command will do before he actually pulls the trigger. Using -WhatIf will tell Windows PowerShell to run the Rename-Item portion of this command in Report Only mode. It will not actually rename anything—it will simply show what files were found that match the filter criteria and what each new name would be. Here is the command with the -WhatIf parameter added.

Get-ChildItem -Filter “*current*” -Recurse | Rename-Item -NewName {$_.name -replace ‘current’,’old’ } -whatif

Unfortunately, when we use –WhatIf, we cannot send our output to a text log file. If you need a log file that shows the results of using -WhatIf, you can follow these steps:

  1. Open Windows PowerShell.
  2. Run Start-Transcript.
  3. Run your command (including the -WhatIf parameter).
  4. After the command completes, run Stop-Transcript.
  5. Note the location and file name of the transcript file, and open this file to see the results.

It is always fun to solve business challenges with Windows PowerShell commands. Cristofer said he will probably need to use these commands for renaming 1000+ files in the near future, and he will share this process with other members of his team. Imagine how much “fun” it would be to rename all of these files manually or with some clunky old batch file. No thank you. I will stick with Windows PowerShell.

Keep the requests coming in. I always enjoy helping fellow employees find ways to be more efficient and save time  and money.

~Matt

Thanks again, Matt, for sharing your time and knowledge. This is awesome.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Comments (54)

  1. Chen V says:

    Good Post and helped

  2. Anonymous says:

    Awesome!

  3. Hieronymus Fortesque Lickspittle says:

    Thanks!  You are a very talented writer.  This was very thorough and easy to follow.

  4. Stfleck says:

    Very useful tip. My problem would be a little bit different. I am sure that it still could be done. My issue would be that there are a group of files with a common string. Is there a way to rename the file based on the created date of the file. I would like the output to be something like CommonString_ddMMMYY

  5. n says:

    I used similar method but no success when "[" is part of file name. Any ideas?

  6. Stfleck says:

    I was able to figure it out . Thanks to this tip  Thank you

    This is what I came up with

    Get-ChildItem -Filter "*.csv" -Recurse | Rename-Item -NewName {$_.BaseName + $_.CreationTime.toString("ddMMMyy") + ".csv" }

  7. David Wyatt says:

    @n

    "[" is a special character in certain PowerShell commands that accept wildcards.  To use any of those special characters as literals, you have to place them inside a pair of square brackets (though this doesn't seem to apply to the -Filter parameter of Get-ChildItem, it does apply to -Path.)  For example, both of these work on my system:

    Get-ChildItem -Path '*[[]*'

    Get-ChildItem -Filter '*[*'

  8. Matt Tisdale says:

    n,

    My assumption is that what is not working for you is renaming a file containing "[" where you are trying to replace "[" with some other character.  If this is the case, "[" is a special character and must be "escaped" with a backslash character.  Here is an example… I want to find all files in a folder containing "[" and replace each "[" character with a "-" character.  Here is the command:

    Get-ChildItem -Filter "*[*" | Rename-Item -NewName {$_.name -replace "[", "-"}

    If this does not solve your issue post another questions and I will provide feedback as soon as possible.

    character and must be "escaped"

  9. n says:

    The problem is that PowerShell cannot see files with "[" in filename. In spite of that I am not able to do any rename operation – I get an error "file does not exist".

  10. Matt Tisdale says:

    PowerShell does see files with the bracket character.  I created a number of test files earlier with this character at various places in the file name and ran the command I posted earlier today.  It found and renamed the files just fine.  I am running PS 3.0.  Maybe you are running an older version and it has an issue.  I am not sure if older version have this kind of problem or not.  Feel free to post the exact command you are running and I will do some testing with it.

  11. Rifyriot says:

    n,

    Try the -literalpath parameter… it's function is descirbed in the help

    get-help Get-ChildItem -Full

  12. Parvaneh says:

    Thanks a lot!!! It worked! I have visited many websites and have tried many different Things and thgis one worked! Very well explained!

  13. Steve says:

    This just came in handy, big time. Thank you.

  14. ricardo says:

    Thanks for the post, help me a lot, but i need one more help:
    What can i do if i don´t know how character i´m seeking, because the explorer don´t show it and in the PS prompt the character only appear a question mark (i don´t know if really is)? I need to remove the character.

    Thnak you

  15. stephen says:

    Say you have a bunch of files that are numerically valued for instance: season01game01, season01game02……. season04game01. How would you change it so that it would be named Season01Game01 instead just capitalizing the beginning of every word but keeping the numeric value the same

  16. Sri says:

    instead of give “old”, i want to give the name of the parent folder where I run this command. for example if I have many subfolders (such as 2a 2b 2c), inside c:1abc where I run this command, I want the new names inside subfolders to have 2a.jpg 2b.jpg 2c.jpg

    so the final name is subfolder1.jpg subfolder2.jpg etc

    thanks

  17. KP says:

    Hi , Can i know what commend i need to use for the below operation. I have a file with name HELLO_WORLD_2012.CSV. i have to check the file if contains “HELLO_WORLD” in it, if it contains that name rename the entire file to HELLO_WORLD.CSV .The script i am going to run and the directory that files have placed are different.

  18. Kevin says:

    Thanks, this is just what i need, works like a charm..
    But is there any way i can just copy and paste the command in Powershell instead of typing it every time?
    I am a programming dummy….

  19. Ganesh says:

    Thank you so much! this saved a ton of time for me!!!!

  20. RbensM says:

    Everything is nice, but for starters, how do you navigato to C:temp?

  21. Dilshan E says:

    This is Super Useful.. Thanks a bunch

  22. tristian o'brien says:

    nice helped me on my recent project!

  23. Gijs says:

    Very nice script, of course as a scripter I coul not resist the urge to add some variables.

    For those who like toa parameterize this query:
    # ====================================
    # Date: 7 August 2014
    # Version: 1.0
    # author: Gijs Linssen
    # Simple way to rename files in bulk
    # ====================================
    # This script did not exist without the help of:
    #
    http://blogs.technet.com/b/heyscriptingguy/archive/2013/11/22/use-powershell-to-rename-files-in-bulk.aspx

    $PreFix= "*"
    $CurrentString= "StringToBeReplaced"
    $NewString= "NewString"
    $PostFix= "*"
    Get-ChildItem -Filter "$PreFix$CurrentString$PostFix" -Recurse | Rename-Item -NewName {$_.name -replace $CurrentString,$NewString }

  24. markus says:

    Unfortunately just half of the truth:
    The script fails when a file containing the "new" filestringname already exists. As far as I understand some Loop with conditional check whether filename exists or not is necessary.

  25. frred says:

    Thanks. None of the above solutions helped to bulk rename files with square brackets in powershell 2.0.

    There are bug reports on the M$ pages about square brackets. To judge by those it seems that the fix in powershell 2.0 was either not complete or the bug persists by design. All seems to go back to bad design when it comes to anticipating that users want consistent
    behaviour, which is not what they got. They got cmdlets that handle/dont handle literal paths and handle/dont handle regular expressions alongside powershell escaping, coupled with no error messages or misleading messages. After an hour of reading "path …
    does not exist" errors, now finally a solution. Hope it helps. A note of warning to copy/pasters: watch out for spaces, name collisions and mulitiples of the pattern in the filenames before running.

    get-childitem | move-item -destination {$_.name -replace ‘[(.*)] (.*)’,’$2′}

  26. pa says:

    Wildcard note for non-experts: unlike the "generic" wildcard system, where "?" means a single character, the "-replace" operator used here uses what MS calls a "regular expression" for the ‘current’ parameter. "Regular expressions" use "." as the single-character
    wildcard, not "?". So, if you had a bunch of files called "IT – 01 blah blah.txt", "IT – 02 blah blah.txt", etc, and you just wanted to cut off the "IT" and the number at the front, you would use:

    Get-ChildItem -Filter "IT*" -Recurse | Rename-Item -NewName {$_.name -replace ‘IT – …’,” } -whatif

    If you try to use "-replace ‘IT – ???’,”", you’ll get an "Invalid regular expression pattern" error.

    A good reference to go with this post is here:

    http://powershell.com/cs/blogs/ebookv2/archive/2012/03/20/chapter-13-text-and-regular-expressions.aspx

  27. sam says:

    I have two folders with different file names, I want to rename filenames of one folder with filenames of another folder. How do I do that?

  28. Dutch says:

    Very useful. Thank you!

  29. vqadmin says:

    Windows Power Shell – Rename all files under a folder
    http://www.quamvidi.com/programming.php#rename_Files_Using_PowerShell

  30. wahid haq says:

    I suggest to try KrojamSoft BatchRenameFiles program. It’s really work for me.

  31. Jose Tovar says:

    what if i nee to copy

    \server1folder1folder2folder3folder5folder667031.1.doc
    to a diferent structure folder and file name
    \server1folder7folder8this-is-the-new-naname.doc

    i have a spreadsheet with both paths and name.
    i tried one that i found but is not working
    any help will be appreciated.

    Jose

  32. Rh says:

    Hey all, I am having hard time to solve this with power shell.. Maybe you can help me.. It is simple, but I was not able to figure it out yet..
    I need to search in a particular folder (C:filesFolder fo instance) the files containing two strings inside (separate) and for these files I need to rename them using part of the original file name (6 characters in particular position of the file name) plus
    current date in YYMMDD
    I can do it using scripting but I would love to have this with powershell which I am learning and using and seams to be very good.
    your comments and suggestions are very welcome

  33. Ty says:

    This works great for files only, but what if I want to change both file and directory names? In this case, any folder name that is changed, the files and subfolders don’t get modified without running the script again for each folder level that is modified.
    Basically, it changes the folder name, then attempts to change the files inside using the old folder name, instead of the new folder name that was just created.

  34. GallEsco says:

    Great!, it was really good written, thank you!

  35. Mememe says:

    Great Article! I was hoping that someone may also be able to help with this example taking this a bit further…

    We have files generated by software such as "file.jpg", when the software finds a file already exists it doesn’t overwrite the file but makes a new file with an increment "_01" or "_02" etc so it then looks like "file_01.jpg" or "file_02.jpg" etc. When a newer
    file exists I want to find a way to rename the most current "file_01.jpg" or "file_02.jpg" etc as plain "file.jpg" and also overwrite / removing the old ones.

    Currently the files look something like this (File_02.jpg being the most current file that I want to keep / rename in this example)…

    File.jpg
    File_01.jpg
    File_02.jpg

    I want it to looks like this…

    File.jpg

    Might be trying my luck, but if anyone has any ideas that would be fantastic!
    Thanks!

  36. helep says:

    Never even heard of Powershell until I googled batch file rename! Thanks, this worked a treat.

  37. Ray S. says:

    Hello –
    I am new to the Powershell world and would appreciate some help. I want to batch rename files and folders that are located in multiple folders that have different names. For example – I have 26 folders for each letter of the alphabet. Inside each of those folders,
    I have thousands of folders based on the last name, first name and then account number. Inside each person’s folder is multiple files and folders with only a description on them, no last name, first name account number attached to them. So a folder could be
    labeled Smith, Joe 12345-AB, inside his folder would be various labeled files. I want to add the parent folder name to only the files and folders inside of that individual folder, not across the entire drive. I see where there are powershells or programs that
    will do this but I would have to individually key in each folder name in the script and then have it do the work. I do not want to do that 9,000 times. I want to run a script that will look at each parent folder, take the name and apply it to only the files
    and folders inside of it, nowhere else. Can this be done? Thank you for your help.

  38. Rodel says:

    Hello, is there also a way to rename a file using a certain string inside the file as the new name? As an example, i have hundreds of text files and i want to rename them using this string "H_KEPLERPG2-003-F-1_XLR " which is found on the first line inside
    the text file.

    here’s how the text file looks like. Thanks in adance.

    00:26:22 ***** Executing Part Number Program H_KEPLERPG2-003-F-1_XLR 2015-07-07-00.26.21.000000 8.5.1 Date: Oct 10 2014 : HPB5_01_BILC Mode*****
    00:26:23 Opening System Context for Zone 0.
    00:26:33 Vector memory already cleared…..
    00:26:42 Initializing the system.
    00:26:53 Initializing the power supplies.
    00:26:54 Reading Thermal Tray ID’s …
    00:26:54 * Powering Up Board H_Kepler_RevF_XLR_Relaxed *
    00:26:55 Loading error log file C:HPB3BI_ProgramsKeplerPG2.0H_KEPLERPG2-003-F-1PSSKepler_Mcc_A.elm. . .
    00:26:55 Loading Power up vector file C:HPB3BI_ProgramsKeplerPG2.0H_KEPLERPG2-003-F-1PSSKepler_POR_C.svm.gz. . .
    00:26:55 Loading Power up register file C:HPB3BI_ProgramsKeplerPG2.0H_KEPLERPG2-003-F-1PSSKepler_POWERUP_DutThermDiode.REG. . .

  39. Fedya says:

    PowerShell way is for my friend who showed me to this article while I am quite comfortable at using BatchRenameFiles Tool. Thanks

  40. Jim_B says:

    Ed, you saved me so much time! Thanks!

  41. Dorian Markich says:

    Thanks for the useful tip! While I was trying to find a solution, I stumbled upon KrojamSoft BatchRename and thought it was very good. It’s highly effective and lets you rename multiple files in your directory at once. I found it was super helpful, especially
    if you work with photography, screencaptures, music files… etc

  42. Jonathan says:

    So easy and so useful. This is going to save me so much time.
    I also really appreciate the WhatIf tip. I plan to use that as I explore PowerShell some more.

  43. Priya says:

    Thanks a lot, This blog helped me to solve my problem for about 1000 + files to rename them in few seconds. Thanks again!!

  44. Nicky says:

    Scenario: need to rename several text files using a substring (33,4) found in record/line 1 in each of these text files.

    Old file name = xyz.txt
    New file name = substring (33,4)_xyz.txt

    Ideas on how to go about this using powershell. Thanks

  45. Gatewood says:

    THANK YOU!!!!!!! Just renamed about 5k files using this that had a typo!

  46. Zedmag says:

    hey guys, hope someone is still reading this. Im having trouble figuring out how search subfolders to rename a batch of files, however, it needs to have some sort of IF statement. lets say i have the root folder, then 2 sub folders with the names of Style-01
    and Style-02. sitting in both of these folders are the same file labeled BlackNRed.txt. BlackNRed.txt needs to be renamed to match the folder name it is in. so it is renamed to BlackNRed-Style-01.txt if its in the Style-01 folder, and BlackNRed-Style-02.txt
    if its in the Style-02 folder and so on. Im racking my brain and may just be over thinking or over looking it. Any help would be appreciated.

  47. Zedmag says:

    in my time awaiting a response, iw as about to figure it out. now my trouble is that it seems windows 10 machines, presumably running PS 5.0 are not executing the script. win 8 and win 7 machines are with no issues. has anyone had issues with this??

  48. Chinmay says:

    I am facing problems when replacing an expression in the files with the same expression appended with a common suffix.

    For example, if I want to replace files having format "File 1 blah blah" to "File 1 – blah blah"
    and "File 2 blah blah" to "File 2 – blah blah" and so on.

    Get-ChildItem -Filter "File*" -Recurse | Rename-Item -NewName {$_.name -replace ‘File ?’,’File ? – ‘ }

    This command throws "Illegal characters in path." error.
    The wild character ‘?’ in the new name string is the character which is throwing this error.

    Could anyone suggest a possible way around this problem??

  49. Travis says:

    Worked like a charm. Excellent job and saved me having to remove the word ArchiveFile_ from over 8,000 files. Awesome job and thank you!

  50. Mel says:

    Need to rename multiple files
    ex: 12345 (AA) SHT 01(VEC).TIF
    dir|rename-item -newname { $_.name -replace “(VEC)”,””} changes file to 12345 (AA) SHT 01().TIF I need to remove the entire (VEC)

  51. ryan says:

    I have a complicated twist to this.
    I have lots of files that begin with a regular character string, but also in the file name are several strings in parenthesis separated by spaces For example:
    – “car 1 (year) (make) (model).jpg”
    – “car 2 (year) (make) (model).jpg”
    – “car 3 (year) (make) (model).jpg”

    I have tons of those, and I want to strip out everything that’s in parentheses, so I end up with:
    – “car 1.jpg”
    – “car 2.jpg”
    – “car 3.jpg”

    Is there any way to make that happen? I don’t care if it takes several steps, it will still be quicker than manually changing. Any advice is appreciated. Thanks!

  52. Rajeev says:

    Hello Sir,

    I want to rename a file when it is getting updated.is it any way to do that.

    Thanks in advance

Skip to main content