A colleague of mine asked me if I could make a PowerShell script which would rename all of his jpg photos on his NAS. All photos need to be renamed to the (parent) folder they are in.

I decided to write it in a function with multiple for loops (for readability) and to put in a jpg filter. If you want different files to be renamed, just change that filter (or extend it).

The script can be used by putting it in the root of the folder where all the different photo folders are present and run it.
For example if you have a folder called HolidayPhotos and in that folder multiple folders like Ibiza_2010, Florida_2012, etc. just put the script in the HolidayPhotos folder. Now run the script and all jpg files will be renamed to Ibiza_2010_1, Ibiza_2010_2, etc. and Flordia_2012_1, Florida_2012_2, etc.

rename_photos.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#######################################################
# AUTHOR  : http://www.hican.net - @hicannet
# DATE    : 12-03-2012
# COMMENT : This script renames all .jpg files to the
#           name of the .jpg parent folder recursively,
#           extended with an increasing number.
#           Put the script in the root of the folders'
#           parent folder.
#######################################################
$path = Split-Path -parent $MyInvocation.MyCommand.Definition
 
Function renamePhotos
{
  # Loop through all directories
  $dirs = dir $path -Recurse | Where { $_.psIsContainer -eq $true }
  Foreach ($dir In $dirs)
  {
    $i = 1
    $newdir = $dir.name + "_"
    $images = Get-ChildItem -Path $dir.fullname -Filter *.jpg -Recurse
    Foreach ($image In $images)
    {
      $split    = $image.name.split(".jpg")
      $replace  = $split[0] -Replace $split[0],($newdir + $i + ".jpg")
 
      $image_string = $image.fullname.ToString().Trim()
      Rename-Item "$image_string" "$replace"
      $i++
    }
  }
}
# RUN SCRIPT
renamePhotos
"SCRIPT FINISHED"