Pipe the files into Rename-Item with a script block: Rename-Item -NewName { $_.Name -replace 'old', 'new' }. Add -WhatIf first.
This comes up constantly: a folder of exports with the wrong prefix, backup files with a space in the name, screenshots that need a date on the front. The pattern is always the same.
Find and Replace in Filenames
# ALWAYS look first
Get-ChildItem -Path "D:\Exports" -Filter *.log |
Rename-Item -NewName { $_.Name -replace '^file', 'server' } -WhatIf
-WhatIf prints exactly what would happen and changes nothing:
What if: Performing the operation "Rename File" on target "Item: D:\Exports\file1.log
Destination: D:\Exports\server1.log".
What if: Performing the operation "Rename File" on target "Item: D:\Exports\file2.log
Destination: D:\Exports\server2.log".
Happy with it? Run the same line without -WhatIf.
Other Patterns You Will Want
# strip spaces out of filenames
Get-ChildItem -File | Rename-Item -NewName { $_.Name -replace ' ', '_' } -WhatIf
# add today's date to the front
$stamp = Get-Date -Format 'yyyy-MM-dd'
Get-ChildItem -Filter *.bak | Rename-Item -NewName { "$stamp-$($_.Name)" } -WhatIf
# change the extension only
Get-ChildItem -Filter *.txt | Rename-Item -NewName { $_.Name -replace '\.txt$', '.log' } -WhatIf
The Trap: Regex, Not Text
-replace takes a regular expression, so characters like ., ( and [ do not mean what they look like. To replace a literal dot, escape it as \. as in the extension example above. If you would rather avoid regex entirely, use the string method instead:
Get-ChildItem -Filter *.txt | Rename-Item -NewName { $_.Name.Replace('.txt', '.log') } -WhatIf
One more thing: if two files would end up with the same name, the second rename fails and the rest carry on. That is why the dry run matters on a folder you cannot easily rebuild.
Related
- Advanced File and Folder Creation
- Delete Files in PowerShell
- List Files with Sizes and Dates
- PowerShell Complete Guide
If SQL Server is part of your day job, my current work lives over at sqldba.blog: production DBA scripts, an error library and the SSMS guide.
Leave a Reply