Skip to content

Instantly share code, notes, and snippets.

@arenagroove
Created April 22, 2025 03:29
Show Gist options
  • Select an option

  • Save arenagroove/51312369ef31a6d6d4536f10f4dbd65b to your computer and use it in GitHub Desktop.

Select an option

Save arenagroove/51312369ef31a6d6d4536f10f4dbd65b to your computer and use it in GitHub Desktop.
PowerShell script to sequentially rename image files (.jpg, .png, .webp) in the current directory using a configurable prefix and index format. The script ensures all file extensions are lowercase and prevents filename collisions by checking for existing files before renaming.

Sequential Image Renamer (PowerShell)

Rename image files in the current directory with a sequential, zero-padded index and a customizable prefix. It supports .jpg, .png, and .webp formats, ensures lowercase file extensions, and prevents overwriting existing files by checking for filename collisions.

Features

  • Sequential renaming with two-digit zero-padding (e.g., lr-demo-img-01.jpg)
  • Supports .jpg, .png, .webp file types
  • Automatically converts extensions to lowercase
  • Avoids overwriting by skipping used filenames
  • Simple and efficient—no dependencies required

Usage

  1. Place the script in the folder containing the images.
  2. Open PowerShell and navigate to the folder.
  3. Run the script:
.\sequential-image-renamer.ps1
# Set starting index and naming pattern
$index = 1
$prefix = "lr-demo-img-"
# Get all .jpg, .png, and .webp files in the current folder (no subfolders)
Get-ChildItem -Path . -File | Where-Object { $_.Extension -match "\.jpg|\.png|\.webp" } | Sort-Object Name | ForEach-Object {
# Get lowercase extension
$extension = $_.Extension.ToLower()
# Loop to find the next available filename
do {
# Format the index with leading zeros
$formattedIndex = "{0:D2}" -f $index
# Create the new filename
$newName = "$prefix$formattedIndex$extension"
# Check if the file already exists
$exists = Test-Path -Path (Join-Path -Path $_.DirectoryName -ChildPath $newName)
# Increment index if name exists
if ($exists) {
$index++
}
} while ($exists)
# Perform the renaming
Rename-Item -Path $_.FullName -NewName $newName -ErrorAction Stop
# Increment index for next file
$index++
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment