Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively renaming files with Powershell

I currently have a line to batch rename files in a folder that I am currently in.

dir | foreach { move-item -literal $_ $_.name.replace(".mkv.mp4",".mp4") }

This code works perfectly for whatever directory I'm currently in, but what I want is to run a script from a parent folder which contains 11 child-folders. I can accomplish my task by navigating to each folder individually, but I'd rather run the script once and be done with it.

I tried the following:

get-childitem -recurse | foreach { move-item -literal $_ $_.name.replace(".mkv.mp4",".mp4") }

Can anyone please point me in the right direction here? I'm not very familiar with Powershell at all, but it suited my needs in this instance.

like image 626
Matthew Avatar asked Feb 06 '14 18:02

Matthew


People also ask

How do I bulk Rename files in PowerShell?

What to Know. 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 a folder in PowerShell?

Cmdlet. Rename-Item cmdlet is used to rename a folder by passing the path of the folder to be renamed and target name.

How do I change a file extension in PowerShell?

Change file extensions with PowerShell You can also use the Rename-Item to change file extensions. If you want to change the extensions of multiple files at once, use the Rename-Item cmdlet with the Get-ChildItem cmdlet.


2 Answers

You were close:

Get-ChildItem -File -Recurse | % { Rename-Item -Path $_.PSPath -NewName $_.Name.replace(".mkv.mp4",".mp4")}
like image 194
Cole9350 Avatar answered Oct 11 '22 21:10

Cole9350


There is a not well-known feature that was designed for exactly this scenario. Briefly, you can do something like:

Get-ChildItem -Recurse -Include *.ps1 | Rename-Item -NewName { $_.Name.replace(".ps1",".ps1.bak") }

This avoids using ForEach-Object by passing a scriptblock for the parameter NewName. PowerShell is smart enough to evaluate the scriptblock for each object that gets piped, setting $_ just like it would with ForEach-Object.

like image 44
Jason Shirk Avatar answered Oct 11 '22 20:10

Jason Shirk