Windows 10,重命名所有子目录中的所有* .jpg文件,编号从1开始

时间:2020-03-09 15:21:19

标签: powershell recursion batch-rename

我想要解决相同问题的方法,但是在 Windows 10 中。 Recursively rename .jpg files in all subdirectories

我尝试使用以下powershell命令, Get-ChildItem -Recurse -Include *.jpg | % { Rename-Item $_ -NewName ('{0:D1}.jpg' -f $i++)}

,但是它按顺序重命名文件,而无需在每个子文件夹中将索引重设为1。

2 个答案:

答案 0 :(得分:2)

我认为您需要两个单独的Get-ChildItem cmdlet。第一个将收集所有子目录,而在循环时,第二个将收集每个目录中的文件:

Get-ChildItem -Path 'X:\RootFolder\where\the\files\are' -Recurse -Directory | ForEach-Object {
    $count = 1   # reset the counter for this subdir to 1
    Get-ChildItem -Path $_.FullName -Filter '*.jpg' -File | ForEach-Object {
        $_ | Rename-Item -NewName ('{0:D1}.jpg' -f $count++) -WhatIf
    }
}

如果您对控制台中显示的结果感到满意,请删除-WhatIf

P.S。标题为*.png,但是您的代码处理的是*.jpg。没关系,只要您将过滤器设置为正确的扩展名并相应地在代码中调整新名称

答案 1 :(得分:2)

据我所知,您必须将其用作嵌套的foreach:

Foreach ($directory in (Get-ChildItem -Directory)){
     $i = 1
     Get-ChildItem $directory.Fullname -Recurse -Include *.jpg | % { Rename-Item $_ -NewName ('{0:D1}.jpg' -f $i++)}
}

我对其进行了测试,并且效果很好:) 如果它对您有用,请将其标记为可接受的答案。

相关问题