Renaming files manually can be exhausting, but with PowerShell, you can batch rename multiple files in just one click on Windows! In this post, weβll walk you through a simple yet effective PowerShell script to rename files in sequence or based on specific conditions. Letβs break down the script and customize it for various use cases.
The Script:
Get-ChildItem *.png | ForEach-Object {
$newName = $_.BaseName.TrimStart('0') + $_.Extension
Rename-Item $_.FullName -NewName $newName
}
π Line-by-Line Breakdown:
1. Get-ChildItem *.png
-
What it does:
Retrieves all
.png
files in the current directory for processing.
Example:
Get-ChildItem *.jpg # To fetch all JPEG files
2. | ForEach-Object { ... }
-
What it does:
Loops through each file and applies the actions inside the curly braces
{ ... }
.
Example:
Get-ChildItem *.txt | ForEach-Object {
Write-Host $_.Name
}
3. $_.BaseName.TrimStart('0') + $_.Extension
- What it does: Removes leading zeroes from the file name while keeping the file extension intact.
Example:
$newName = $_.BaseName.TrimStart('A') + $_.Extension # Removes leading 'A' characters
4. Rename-Item $_.FullName -NewName $newName
- What it does: Renames the file using its new name generated in the previous step.
Example:
Rename-Item $_.FullName -NewName "newFile_" + $_.Name # Add 'newFile_' prefix
π― Different Scenarios and Examples
1. Renaming Files by Adding a Suffix
Get-ChildItem *.txt | ForEach-Object {
$newName = $_.BaseName + '_backup' + $_.Extension
Rename-Item $_.FullName -NewName $newName
}
This script renames file.txt
to file_backup.txt
.
2. Changing File Extensions
Get-ChildItem *.png | ForEach-Object {
$newName = $_.BaseName + '.jpg'
Rename-Item $_.FullName -NewName $newName
}
This renames image1.png
to image1.jpg
.
3. Adding Sequential Numbers to Files
$counter = 1
Get-ChildItem *.png | ForEach-Object {
$newName = "image$counter" + $_.Extension
Rename-Item $_.FullName -NewName $newName
$counter++
}
This renames files sequentially like image1.png
, image2.png
, etc.
π‘ Conclusion
Using PowerShell in Windows, you can easily rename multiple files in sequence with just one click! Whether youβre stripping zeroes, adding suffixes, or changing file extensions, this script is a flexible and powerful tool to streamline your file renaming tasks.
Happy scripting! β‘
Top comments (0)