Bulk File Renaming

by Jun 11, 2014

Let’s assume you have a bunch of scripts (or pictures or log files or whatever) in a folder, and you’d like to rename all files. The new file name should, for example, have a prefix, then an incrementing number.

Here’s how you could do that.

This example would rename all PowerShell scripts with the extension .ps1 inside the folder you specified. The new name would be powershellscriptX.ps1 where “X” is an incrementing number.

Note that the actual rename is disabled in this script. Remove the -WhatIf parameter to actually rename the files, but be extremely careful. If you mistype a variable or use the wrong folder path, then your script might happily rename thousands of wrong files that you did not intend to rename.

$Path = 'c:\temp'
$Filter = '*.ps1'
$Prefix = 'powershellscript'
$Counter = 1

Get-ChildItem -Path $Path -Filter $Filter -Recurse |
  Rename-Item -NewName {
    $extension = [System.IO.Path]::GetExtension($_.Name)
    '{0}{1}.{2}' -f $Prefix, $script:Counter, $extension
   } -WhatIf

Twitter This Tip! ReTweet this Tip!