繁体   English   中英

如何在powershell中的多个文件夹中递归更改名称

[英]how to recursively change name across several folders in powershell

我正在尝试递归重命名包含一堆文件夹的文件夹中的文件。

为了更好地澄清,我有一个包含 10 个子文件夹的父文件夹,10 个子文件夹中的每一个都有 17 个声音文件。

我需要重命名 17 个声音文件中的每一个 1,2,3...17

我设法想出了以下代码(现在,写入文件名而不是实际更改它)

$files = gci -Path "D:\PARENT_FOLDER" -Recurse
$i = 1
foreach ($file  in $files) {

$newName = 0
1..$i | % {$newName = $newName+1}
$i++
Write-Host "name is " $newName
}

但我不知道如何让它重置文件夹之间的计数。 现在代码输出从 1 到 180 的名称......

有人可以帮我解决这个问题吗? 提前致谢

好的,在工作了一整天之后,我回到家并从头开始解决这个问题,并提出了一个更简单的解决方案:我只是将“foreach”循环嵌套在另一个循环中,以循环遍历父文件夹中的所有文件夹和所有文件每个文件夹内。

如果有人感兴趣,这里是代码:

$path = "MASTER FOLDER PATH"

$list = Get-ChildItem -Path $path -Directory

foreach ($folder in $list)
{
Write-Host "working on Directory" $folder.FullName -ForegroundColor Green

        foreach ($files in $folder)
        {$files = Get-ChildItem -Path $path\$folder
                $i=1
                foreach ($file in $files) {


                $newName = 0
                1..$i | % {$newName = $newName+1}
                $i++

                Write-Host "Changing file " $file.FullName -NoNewline -ForegroundColor Yellow
                Write-Host " ..." -ForegroundColor Yellow
                Rename-Item -Path $file.FullName -NewName $newName


                }
        }
} 

我感谢您的帮助。 :)

我建议暂时-Recurse部分并手动执行递归操作(也称为循环)。

$list = Get-ChildItem -Path $path -Name -Directory

for ($i=0;$i -le $list.Length-1;$i++) {
$list[$i] = $path + '\' + $list[$i]
}

现在您有一系列文件夹,您现在可以单独寻址。

$path = "(path)" 
$list = Get-ChildItem -Path $path -Name -Directory

for ($i=0;$i -le $list.Length-1;$i++) {
$list[$i] = $path + '\' + $list[$i]
$temp = Get-ChildItem -Path $list[$i] -Name

for ($h=0;$h -le $temp.Length-1;$h++) {
$temp[$h] = $list[$i] + $temp[$h]
Rename-Item -LiteralPath $temp[$h] -NewName $h
}}

这就是我想出来的,希望它有帮助。

这是另一种方式。 我不知道如何递归和重置每个文件夹的编号。 这样我一次只做一个文件夹。 带有两个脚本块的 Foreach 会将第一个脚本块视为“开始”脚本块。

foreach($dir in get-childitem parent) {
  get-childitem parent\$dir | foreach {$i = 1} { rename-item $_.fullname $i -whatif; $i++ }
}

What if: Performing the operation "Rename File" on target "Item: C:\users\js\parent\foo\a Destination: C:\users\js\parent\foo\1".
What if: Performing the operation "Rename File" on target "Item: C:\users\js\parent\foo\b Destination: C:\users\js\parent\foo\2".
What if: Performing the operation "Rename File" on target "Item: C:\users\js\parent\foo\c Destination: C:\users\js\parent\foo\3".
What if: Performing the operation "Rename File" on target "Item: C:\users\js\parent\foo2\a Destination: C:\users\js\parent\foo2\1".
What if: Performing the operation "Rename File" on target "Item: C:\users\js\parent\foo2\b Destination: C:\users\js\parent\foo2\2".
What if: Performing the operation "Rename File" on target "Item: C:\users\js\parent\foo2\c Destination: C:\users\js\parent\foo2\3".

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM