Writing a Powershell Script: Rename Files

Goal: Rename a set of files using a powershell script.

Example

start: alpha bravo charlie delta.png
change: Remove “charlie .*”
end: alpha bravo.png
  • Learn powershell and it’s syntax.
  • Execute a powershell script by double clicking.
  • Show executed code for bug checking.
  • Functions used: rename-item, replace()

Solution

Script Code:

get-childitem *.png | foreach { rename-item -LiteralPath $_ ($_.Name -replace “( charlie .+)”, “$1.png”) }

Edit (5/14/2024): -LiteralPath is a flag for rename-item which takes the second argument, $_ (the path of the current file), exactly as it is. This flag is necessary because filenames could contain special characters like “[” which are treated differently if left un-escaped or not taken into account.

This script loops through all png files and renames them sometimes with the same file name.

An issue with the script is that renames all png files instead of png files that match the condition. It seems probable that this code can be updated to be as selective.

For the shortcut:
Target:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command “& ‘[path to ps1 file]\script-name.ps1’
Start in: was left blank.

Steps to find this solution

First googled for an answer, initially looked at doing this via a command line batch script but did not find a similar solution doing this.

Found these answers which I combined and ran until it worked correctly.
(Super User: How do I remove the same part of a file name for many files in Windows 8?)
(Stack Overflow: how do I rename files in Powershell with regex?)

Reference on commands I used.
(SS64: Rename-Item)
(SS64: Replace())
(SS64: Regular Expressions)

Usage of the “-replace” option (regular expressions)
(Microsoft | Powershell: About Comparison Operators)

Running the script by double clicking a copy of a shortcut.
(Stack Overflow: Is there a way to make a PowerShell script work by double clicking a .ps1 file?)

Keeping the window open and showing execution/errors.
(Microsoft | PowerShell: Write-Output)
(Stack Overflow: How to keep the shell window open after running a PowerShell script?)
(Microsoft: Set-PSDebug)
(Server Fault: PowerShell script, showing commands run)

Filtering a collection.
(Concurrency: PowerShell Basics – Filtering and Selecting by Mitchell Grande)