簡體   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