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

4
我不知道这是否最好由PowerShell完成,但基本上我有很多电影名称不正确。每个电影的文件夹名称是正确的。
在一个文件夹内,我希望遍历每个文件夹并将.mp4文件重命名为与文件夹相同的名称。
每个文件夹中只有一个.mp4文件和一个.jpg文件,但我只想重命名.mp4文件(尽管两个文件都重命名也不会有问题)。
是否有一种简单的方法在PowerShell中实现这个功能?
3个回答

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

这个很棒,谢谢。能否解释一下它是如何工作的呢?(这有助于我更好地理解) - user475353
我很难给出比注释更详细的描述,但是我可以评论并说这非常棒,完全符合您的要求。 - suzumakes

2

一份易于阅读的版本:

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

第一个Get-ChildItem获取D:\Videos中的所有目录对象,ForEach-Object遍历这些目录对象,并将每个目录作为$_传递到以下代码块中。
在代码块内部,再次使用Get-ChildItem通过-Path选项从给定目录获取一个mp4文件。最后,使用Rename-Item重命名视频文件,而不将其移动到其他目录。

1
这是一个跨版本的示例:
Get-ChildItem D:\temp\*\*.mp4 | Rename-Item -NewName {$_.Directory.Name +'.mp4'}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接