Re: [打屁] 批次把檔案放到資料夾的最上層

看板EZsoft (小軟體)作者 (falken)時間2周前 (2025/12/01 07:05), 2周前編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/3 (看更多)
不確定這樣是不是你要的 僅供參考 範例:不保持原目錄結構,把檔案都移到第一層子目錄 D:\dir\dir1\dir1\file D:\dir\dir1\file D:\dir\dir2\dir2\file1 D:\dir\dir2\dir2\file2 在 D:\dir 執行以下指令碼後的結果: D:\dir\dir1\file D:\dir\dir1\file_1 D:\dir\dir2\file1 D:\dir\dir2\file2 # 取得工作目錄下所有的子目錄 Get-ChildItem -Directory | ForEach-Object { # 子目錄路徑 $dirPath = $_.FullName # 取得所有子目錄與其子目錄之下的檔案 Get-ChildItem -LiteralPath $dirPath -File -Recurse | ForEach-Object { # 檔案已經在子目錄下第一層,跳過這一項 if ($_.DirectoryName -eq $dirPath) { return } # 自動變更目標檔名避免衝突 # 目標路徑:子目錄路徑\原檔名與自動尾綴.副檔名 $suffix = ''; $index = 0 do { $desPath = "$dirPath\$($_.BaseName)$suffix$($_.Extension)" $index++; $suffix = "_$index" } until (-not (Test-Path -LiteralPath $desPath)) # 移動檔案到目標路徑 $_ | Move-Item -Destination $desPath } # 刪除所有子目錄下的空資料夾 Get-ChildItem -LiteralPath $dirPath -Directory -Recurse | Sort-Object -Descending -Property FullName | Remove-Item -Force } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 106.64.137.222 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/EZsoft/M.1764543942.A.B8D.html 如果要維持結構,例如: D:\dir\dir1\dir1\file D:\dir\dir1\file D:\dir\dir2\file1 D:\dir\dir2\file2 # 取得工作目錄下所有的子目錄 Get-ChildItem -Directory | ForEach-Object { # 子目錄路徑 $dirPath = $_.FullName # 找到要移動的子目錄 $subDir = Get-Item -LiteralPath $dirPath while (1) { $subItems = $subDir | Get-ChildItem if (($subItems.Count -eq 1) -and $subItems[0].PsIsContainer){ $subDir = $subItems[0]; continue } break } # 不用處理 if ($dirPath -eq $subDir.FullName) { return } # 移動到第一層並使用臨時名稱 $suffix = ''; $index = 0 do { $temPath = ".\$($subDir.Name)$suffix" $index++; $suffix = "_$index" } until (-not (Test-Path -LiteralPath $temPath)) $subDir | Move-Item -Destination $temPath # 取代子目錄 $dirPath | Get-ChildItem -Recurse -Force | Sort-Object -Descending -Property FullName | Remove-Item -Force $dirPath | Remove-Item -Force Move-Item -LiteralPath $temPath -Destination $dirPath } ※ 編輯: falcon (106.64.137.222 臺灣), 12/01/2025 14:07:03 ※ 編輯: falcon (106.64.137.222 臺灣), 12/01/2025 14:22:44
文章代碼(AID): #1fBCt6kD (EZsoft)
文章代碼(AID): #1fBCt6kD (EZsoft)