PowerShell - rename the file to the name of the folder in which it is located

I don't know if this was best done in PowerShell, but basically I have a lot of movies with the wrong names. However, the folder name for each movie is correct.

Inside the folder, I want to view each folder and rename the .mp4 file with the same name as the folder.

Each folder has only a .mp4 file and a .jpg file, but I want to rename only the .mp4 file (although renaming both would really be nice too.)

Is there an easy way to do this in PowerShell?

+4
source share
3 answers

readable version:

Get-ChildItem -Attributes Directory D:\Videos | ForEach-Object { Get-ChildItem -Path $_ *.mp4 | Rename-Item -NewName "$_.mp4" } 

The first Get-ChildItem gets all the directory objects inside the D:\Videos and ForEach-Object iterations over each of these directories as $_ in the next block.

Inside the Get-ChildItem block, it is used again to get the mp4 file from this directory using the -Path option. Finally, the Rename-Item used to rename the video file without moving it from the current directory.

+2
source

Something like this should work:

 # run from your D:\Movies (or whatever) folder # Go through all subfolders of the folder we're currently in, and find all of the .MP4 # files. For each .MP4 file we find... ls -Recurse -Filter *.mp4 | %{ # Get the full path to the MP4 file; use it to find the name of the parent folder. # $_ represents the .MP4 file that we're currently working on. # Split-Path with the -Parent switch will give us the full path to the parent # folder. Cast that path to a System.IO.DirectoryInfo object, and get the # Name property, which is just the name of the folder. # There are other (maybe better) ways to do this, this is just the way I chose. $name = ([IO.DirectoryInfo](Split-Path $_.FullName -Parent)).Name # Tell the user what we're doing... Write-Host "Renaming $_ to $($name).mp4..." # Rename the file. # We have to provide the full path to the file we're renaming, so we use # $_.FullName to get it. The new name of the file is the same as that of the # parent folder, which we stored in $name. # We also remember to add the .MP4 file extension back to the name. Rename-Item -Path $_.FullName -NewName "$($name).mp4" } 
+2
source

Here is an example cross version:

 Get-ChildItem D:\temp\*\*.mp4 | Rename-Item -NewName {$_.Directory.Name +'.mp4'} 
+2
source

Source: https://habr.com/ru/post/1486932/


All Articles