使用PowerShell删除层级结构中的所有中间文件夹
需求说明
我有一批从文档管理系统导出的文件,初始路径类似:
C:\Export\{GUID}\Files\{GUID}\0\0-999\2\L\L\file1.txt C:\Export\{GUID}\Files\{GUID}\0\0-999\3\L\L\file1.txt C:\Export\{GUID}\Files\{GUID}\0\0-999\4\L\L\MultiFileName\file1.txt C:\Export\{GUID}\Files\{GUID}\0\0-999\5\L\L\file2.txt etc...
后续路径简化后为:
C:\Export\2\L\L\file1.txt C:\Export\3\L\L\file1.txt C:\Export\4\L\L\MultiFileName\file1.txt C:\Export\5\L\L\file2.txt ... C:\Export\1999\L\L\file1999.txt
希望将所有文件迁移到C:\Export目录下,最终效果如下:
C:\Export\file1.txt C:\Export\file1-{something}.txt C:\Export\MultiFileName\file1.txt C:\Export\file2.txt ... C:\Export\file1999.txt
核心要求:
- 删除所有名为
L或0-1999之间数字的中间文件夹 - 保留文件最后的合法子文件夹(如示例中的
MultiFileName) - 自动处理重名文件冲突
PowerShell实现脚本
# 定义目标根目录 $targetRoot = "C:\Export" # 递归获取所有需要处理的嵌套文件 Get-ChildItem -Path $targetRoot -File -Recurse | Where-Object { $relativePath = $_.FullName.Substring($targetRoot.Length + 1) # 仅处理包含需要剔除的路径段的文件 $relativePath -match '(L|\d{1,4})\\' } | ForEach-Object { $file = $_ # 拆分文件的相对路径段 $pathSegments = $file.FullName.Substring($targetRoot.Length + 1) -split '\\' # 过滤掉需要删除的路径段:L 或 0-1999的数字 $filteredSegments = $pathSegments | Where-Object { $_ -ne 'L' -and (-not ($_ -match '^\d{1,4}$' -and [int]$_ -ge 0 -and [int]$_ -le 1999)) } # 构建目标文件路径 $targetPath = Join-Path -Path $targetRoot -ChildPath ($filteredSegments -join '\') # 自动创建目标文件夹(如果不存在) $targetDir = Split-Path -Path $targetPath -Parent if (-not (Test-Path -Path $targetDir)) { New-Item -Path $targetDir -ItemType Directory -Force | Out-Null } # 处理重名文件:自动添加递增后缀 if (Test-Path -Path $targetPath) { $baseName = [System.IO.Path]::GetFileNameWithoutExtension($file.Name) $extension = [System.IO.Path]::GetExtension($file.Name) $counter = 1 do { $newFileName = "$baseName-$counter$extension" $targetPath = Join-Path -Path $targetDir -ChildPath $newFileName $counter++ } while (Test-Path -Path $targetPath) } # 执行文件移动 Move-Item -Path $file.FullName -Destination $targetPath -Force } # 可选:清理迁移后遗留的空文件夹 Get-ChildItem -Path $targetRoot -Directory -Recurse | Where-Object { $_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0 } | Remove-Item -Recurse -Force
脚本说明
- 路径过滤逻辑:通过正则匹配+数值范围判断,精准剔除路径中名为
L或0-1999的数字文件夹 - 合法目录保留:仅保留不符合过滤规则的路径段,确保像
MultiFileName这类自定义子目录被完整保留 - 重名冲突处理:如果目标位置已存在同名文件,自动在文件名后添加递增数字后缀(如
file1-1.txt、file1-2.txt) - 空目录清理:可选步骤,自动删除迁移后所有空的嵌套目录,保持目标目录整洁
内容的提问来源于stack exchange,提问作者Stuggi
相关产品推荐
相关产品推荐

