Devin W.C. Ryan

Rename Files with PowerShell

While on holidays I started scanning in a bunch of pictures for a family project and since this was being done in batches each batch of scanned images would be named childhoodXXXXX.jpg where XXXXX is the number of the current image in sequence.  This would be the same for each batch.  Since wanted a means of knowing which images were part of which batch (and thus the corresponding package they came from) I wrote a little script to rename files in a folder with the following requirements:

  • Prepend batch number to beginning of file name
  • Prepend to files that did not currently start with a digit (since we know all names start with childhood)
  • Script is being run from the directory containing the files
  • I didn’t include a recursive folder structure so all files are in the same directory

The script is as follows:

$num = "3 - "

dir | 
%{ 
    $name = $_.Name;
    $c = $name.SubString(0,1);
    
    if(-not [char]::IsNumber($c))
    {
        Rename-Item $_ ($num + $name)
    }; 
}

The script works by getting a list of all files in the current directory, dir, and piping it to a loop which iterates over every file in the folder.  The % is a shorthand/alias for the cmdlet Foreach-Object.  For every file the first character of the name is retrieved and then is tested to see if it is a number, if it is not a number then the Rename-Item cmdlet is used to return the current object/file represented by $_ in the loop to the concatenation of $num and $name, i.e.

childhood0001.jpg would become 3 – childhood0001.jpg

You can make your prefix anything as it is just a string by setting the $num variable.  This means you could automate this further by dynamically changing the prefix within a separate loop or passing it as a parameter to your script.

This post came out of me wanting to play with PowerShell over the holidays and as it worked out this will be my last post of 2014.

1 thought on “Rename Files with PowerShell”

Leave a Comment

Your email address will not be published. Required fields are marked *