PowerShell 7:检查多级子文件夹并将文件上移一级并重命名
PowerShell 文件移动与重命名实现方案
完整代码
# 定义主目录路径 $mainDir = "C:\MainDirectory" # 递归获取所有位于二级子文件夹中的文件 $targetFiles = Get-ChildItem -Path $mainDir -File -Recurse | Where-Object { # 判断文件的父文件夹的父目录是否为主目录(即文件在二级子文件夹内) $_.Directory.Parent.FullName -eq $mainDir } foreach ($file in $targetFiles) { # 生成新文件名:二级文件夹名 + 原文件名 $newFileName = $file.Directory.Name + $file.Name # 拼接新文件的完整路径(一级子文件夹下) $newFilePath = Join-Path -Path $file.Directory.Parent.FullName -ChildPath $newFileName # 处理文件名重复情况:如果新路径已存在,添加数字后缀 $counter = 1 while (Test-Path -Path $newFilePath) { $newFileName = "{0}{1}({2}){3}" -f $file.Directory.Name, $file.BaseName, $counter, $file.Extension $newFilePath = Join-Path -Path $file.Directory.Parent.FullName -ChildPath $newFileName $counter++ } # 移动并重命名文件 Move-Item -Path $file.FullName -Destination $newFilePath -Force Write-Host "已移动文件:$($file.FullName) -> $newFilePath" } # 可选:删除移动后为空的二级子文件夹 $emptySubFolders = Get-ChildItem -Path $mainDir -Directory -Recurse | Where-Object { $_.Parent.FullName -eq $mainDir -and (Get-ChildItem -Path $_.FullName -Recurse | Measure-Object).Count -eq 0 } foreach ($folder in $emptySubFolders) { Remove-Item -Path $folder.FullName -Force Write-Host "已删除空文件夹:$($folder.FullName)" }
关键逻辑说明
- 筛选目标文件:通过
Where-Object判断文件的父文件夹的父目录是否为主目录,确保只处理二级子文件夹内的文件 - 生成新文件名:直接将二级文件夹名称拼接在原文件名前,完全匹配需求中的示例格式
- 重复文件名处理:加入循环判断,如果目标路径已存在同名文件,自动添加数字后缀避免覆盖
- 空文件夹清理:可选步骤,移动完成后自动删除空的二级子文件夹,保持目录结构整洁
使用注意事项
- 先替换
$mainDir为你的实际主目录路径 - 建议先在测试目录中运行,验证逻辑无误后再处理真实数据
-Force参数会覆盖目标路径中已存在的同名文件(如果未启用重复后缀逻辑),根据需要调整
内容的提问来源于stack exchange,提问作者user602214076
相关产品推荐
相关产品推荐

