If you’re used to renaming files at the command prompt you might be surprised to discover that to rename files with PowerShell requires a few more keystrokes.

To rename files with PowerShell we need to use a scriptblock to construct the new filename:

# Change the extensions from .bak to .backup
Get-Item '*.bak' |
    Rename-Item -Newname { $_.name -replace '.bak','.backup' }

This will change each file with the extension bak to the extension backup.

And if you’re a regular expressions junkie then -replace supports regular expressions inside the scriptblock too! You can have any valid PowerShell code inside the scriptblock as long as the output is a string for the new filename.

Paul Broadwith avatar
Paul Broadwith

Paul is a Senior Technology Engineer with 25 years experience in finance, government, manufacturing and services industries. He is a father, Cloud and Datacenter MVP, coder and loves to automate everything.

comments powered by Disqus