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

作者: falcon (falken)   2025-12-01 07:05:40
不確定這樣是不是你要的
僅供參考
範例:不保持原目錄結構,把檔案都移到第一層子目錄
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
}

Links booklink

Contact Us: admin [ a t ] ucptt.com