val
val

Reputation: 1709

How to rename files using a list file?

I have 100s of files that I would like to rename in a specific manner according to a correlated list. Rather than repeating the same cmdlets, as below, I would like to point the cmdlet to a couple of list files (below) containing the old and new names, say old.txt and new.txt. How do I do this using PowerShell?

Example:

Rename-Item -Path "E:\MyFolder\old1.pdf" -NewName new1.pdf
Rename-Item -Path "E:\MyFolder\old2.tif" -NewName new2.pdf
Rename-Item -Path "E:\MyFolder\old3.pdf" -NewName new3.pdf

List Files:

old.txt =

old1.pdf
old2.tif
old3.pdf

new.txt =

new1.pdf
new2.tif
new3.pdf

Upvotes: 2

Views: 1562

Answers (3)

Keith Hill
Keith Hill

Reputation: 201842

So just for yucks, here is the one-liner version. It does depend on you being in the C:\MyFolder dir when you run it but that could easily be changed to a variable:

Get-Content new.txt -PipelineVariable NewName | 
    Foreach {$oldNames = Get-Content old.txt;$i=0} {Get-ChildItem $oldNames[$i++]} | 
    Rename-Item -NewName {$NewName} -WhatIf

Upvotes: 2

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174720

To avoid misalignment between the entries in old.txt and new.txt files, you could also put the files into a CSV file:

renames.csv =

old1.pdf,new1.pdf
old2.tif,new2.tif
old3.pdf,new3.pdf

Now you can use Import-Csv to import your "translation sets":

$Renames = Import-Csv '.\renames.csv' -Header "OldName","NewName"

foreach($File in $Renames) {
    Rename-Item $File.OldName $File.NewName
}

Upvotes: 5

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200393

Simply read your two files into two lists and process them like this:

$old = Get-Content 'old.txt'
$new = Get-Content 'new.txt'

Set-Location '$:\MyFolder'

for ($i = 0; $i -lt $old.Count; $i++) {
  Rename-Item $old[$i] $new[$i]
}

Upvotes: 5

Related Questions