Is it possible to rename each file in a folder with a different name using powershell or a batch file?

Viewed 141

I've tried looking this up but have got nowhere so far and I'm on a time limit. Let's say I have three files that have similar clones in multiple folders:

(folder1)
image1.png
image2.png
image3.png

(folder2)
image1.png
image2.png
image3.png

I want to rename these using cmd prompt, powershell, or using a .bat to:

(folder1)
B-Sign.png
B-Gauge.png
B-Cup.png

(folder2)
G-Sign.png
G-Gauge.png
G-Cup.png

I intend to run the commands for each folder as only the front of the name is different. I want something simple.

rename-item *.png B-Sign.png
rename-item *.png B-Gauge.png

When it needs a different prefix I would just find and replace the prefix with the new one using ctrl+H in notepad.

Problem is I can't figure out, in any of these, how to automatically cycle to the next file in the folder instead of changing all of the files' names at once. Any one can help?

1 Answers

Yes that's very easy in PowerShell:

Get-ChildItem "C:\temp\Folder1" |
Rename-Item -NewName { "B-" + $_.Name }

The new name is a result of an Expression that Rename-Item knows to evaluate. Because the information is sent down the pipeline the Rename-Item command is run once per file, resulting in names like your example.

Also you can use the filter parameter as you described with either of the below:

Get-ChildItem "C:\temp\Folder1\*.png" |
Rename-Item -NewName { "B-" + $_.Name }

I prefer to filter using the -Filter parameter:

Get-ChildItem "C:\temp\Folder1" -Filter *.png |
Rename-Item -NewName { "B-" + $_.Name }

You can store the folder in a variable too:

$Folder = "C:\temp\Folder1"

Get-ChildItem $Folder -Filter *.png |
Rename-Item -NewName { "B-" + $_.Name }

Update:

Per comments here's an example to correlate a list of prefixes with the renames you want to do:

$Prefix = 'B-'

$NewNames =
@(
    'Sign'
    'Guage'
    'Cup'
)

# If New names are stored ina file simply do:
# $NewNames = Get-Content <FilePath>

$Folder = "C:\temp\Test_10-30-20"

$Files = Get-ChildItem $Folder -Filter *.png

For( $i = 0; $i -lt $Files.Count; ++$i )
{
    $CurrentFile = $Files[$i]
    $NewName = $Prefix + $NewNames[$i] + $CurrentFile.Extension
        
    Rename-Item $CurrentFile.FullName -NewName $NewName
}
Related