Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through files and rename using PowerShell?

Tags:

I would like to rename all the jpg files in a folder to uniform convention like Picture00000001.jpg where 00000001 is a counter.

It would be a walk in the park in C# but I would think this is the kind of bread and butter stuff that PowerShell was made for.

I'm guessing something like

$files = ls *.jpg $i=0 foreach($f in $files) { Rename-Item $f -NewName "Picture"+($i++)+".jpg" } 

But before I hit the gas on this I would like to 1) format the counter, and 2) have some sense that this is in fact even a good idea.

If this sounds more like OCD than a good idea please speak up.

like image 359
Ralph Shillington Avatar asked Oct 06 '09 00:10

Ralph Shillington


People also ask

How do I bulk rename files in PowerShell?

Open File Explorer, go to a file folder, select View > Details, select all files, select Home > Rename, enter a file name, and press Enter. In Windows PowerShell, go to a file folder, enter dir | rename-item -NewName {$_.name -replace “My”,”Our”} and press Enter.

How do I rename multiple files sequentially?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.

How do you rename a file in PowerShell?

To rename and move an item, use Move-Item . You can't use wildcard characters in the value of the NewName parameter. To specify a name for multiple files, use the Replace operator in a regular expression. For more information about the Replace operator, see about_Comparison_Operators.


1 Answers

You can do this fairly simply in PowerShell:

ls *.jpg | Foreach -Begin {$i=1} `    -Process {Rename-Item $_ -NewName ("Picture{0:00000000}.jpg" -f $i++) -whatif} 

If you're looking for the "basename" and if you're on PowerShell 2.0 just use the Basename property that PowerShell adds to each FileInfo object:

ls *.jpg | Format-Table Basename 

Note that on PowerShell 1.0, the PowerShell Community Extensions adds this same Basename property.

If the intent is to append a counter string to the file's basename during the rename operation then try this:

ls *.jpg | Foreach {$i=1} `    {Rename-Item $_ -NewName ("$($_.Basename){0:00000000#}.jpg" -f $i++) -whatif} 
like image 179
Keith Hill Avatar answered Oct 11 '22 07:10

Keith Hill