PowerShell - 将文件重命名为其所在文件夹的名称

时间:2013-06-18 21:25:22

标签: powershell

我不知道这是否最好在PowerShell中完成,但基本上我有很多名称不正确的电影。但是,每部电影的文件夹名称都是正确的。

在文件夹中,我想浏览每个文件夹并将.mp4文件重命名为与文件夹相同的名称。

每个文件夹中只有一个.mp4文件和一个.jpg文件,但是我想重命名只是 .mp4文件(尽管重命名两者都不错。)< / p>

在PowerShell中有一种简单的方法吗?

3 个答案:

答案 0 :(得分:2)

这样的事情应该有效:

# 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"
}

答案 1 :(得分:2)

可读版本:

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

第一个Get-ChildItem获取D:\VideosForEach-Object中的所有目录对象,在以下块中以$_的形式迭代每个目录。

在块中,再次使用Get-ChildItem通过mp4选项从给定目录中获取-Path文件。最后,Rename-Item用于重命名视频文件,而不将其从当前目录移动。

答案 2 :(得分:2)

这是一个跨版本示例:

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