作者falcon (falken)
看板EZsoft
标题Re: [打屁] 批次把档案放到资料夹的最上层
时间Mon Dec 1 07:05:40 2025
不确定这样是不是你要的
仅供参考
范例:不保持原目录结构,把档案都移到第一层子目录
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://webptt.com/cn.aspx?n=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