windows – How can I bulk rename files in PowerShell?

windows – How can I bulk rename files in PowerShell?

From example 4 in the help documentation of Rename-Item retrieved with the command:

get-help Rename-Item -examples

Example:

Get-ChildItem *.txt| Rename-Item -NewName { $_.Name -replace .txt,.log }

Note the explanation in the help documentation for the escaping backslash in the replace command due to it using regular expressions to find the text to replace.

To ensure the regex -replace operator matches only an extension at the end of the string, include the regex end-of-string character $.

Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace .txt$,.log }

This takes care of the case mentioned by @OhadSchneider in the comments, where we might have a file named lorem.txt.txt and we want to end up with lorem.txt.log rather than lorem.log.log.

Now that the regex is sufficiently tightly targeted, and inspired by @etoxins answer, we could make the command more usable as follows:

Get-ChildItem | Rename-Item -NewName { $_.Name -replace .txt$,.log }

That is, there is no need to filter before the pipe if our regex sufficiently filters after the pipe. And altering the command string (e.g. if you copy the above command and now want to use it to change the extension of .xml files) is no longer required in two places.

This works well too when youre in the desired directory.

Dir | Rename-Item –NewName { $_.name –replace old,new }

windows – How can I bulk rename files in PowerShell?

The existing answers suggest the -replace operator, but what if the file is called a.xml.xml? Both .xml substrings will be replaced and the end result would be a.tmp.tmp. Fortunately, theres a .NET method for this:

Dir *.xml | rename-item -newname { [io.path]::ChangeExtension($_.name, .tmp) } 

(Manish Kumar was close with GetFileNameWithoutExtension but this is more elegant and probably a bit more efficient, not that it overly matters in this case)

Leave a Reply

Your email address will not be published.