Renaming Files Containing a Particular Pattern Using PowerShell

PowerShell 5.0 icon

I had mistakenly allowed a string to be appended multiple times on the names of files in a folder on my Windows server by a Python script on which I was working. It was a date string that was applied several times: “_2015-11-04_2015-11-04_2015-11-04_2015-11-04_2015-11-04”

I wanted to remove this string from multiple files that were named MailXXXXXXXXX_2015-11-04_2015-11-04_2015-11-04_2015-11-04_2015-11-04.cfmail (the Xs represent numbers).

I tried using the old RENAME command like this: rename “_2015-11-04_2015-11-04_2015-11-04_2015-11-04_2015-11-04.cfmail” “/…(53 slashes here)…/.cfmail”, but I kept getting errors saying the file was in use.

I turned to PowerShell and found a good script for this purpose on TechNet.

After making the necessary changes, I logged onto the server, opened a Command Prompt with admin privileges, and started PS. I navigated to the folder that contained the files to be renamed and created a script I called rename.ps1 here.

Get-ChildItem -Filter "*_2015-11-04_2015-11-04_2015-11-04_2015-11-04_2015-11-04*" -Recurse | Rename-Item -NewName {$_.name -replace '_2015-11-04_2015-11-04_2015-11-04_2015-11-04_2015-11-04','' }

At the PS prompt, I had to run the command “Set-ExecutionPolicy RemoteSigned” to run the script, and then ran the script: “./rename.ps1”. All the files were renamed as I had hoped.