求根据文件夹内指定文件类型移动整个根文件夹的实现脚本
解决方案
原有代码无法实现需求的原因是:仅对匹配到的exe文件所在的直接父目录进行操作,没有定位到源根目录下的一级子文件夹,因此无法移动整个上层文件夹。
PowerShell 实现方案
该方案会自动去重,避免同一个文件夹被重复操作,同时自动创建不存在的目标目录:
$Source = "C:\testsource" $Dest = "C:\testdestination" # 目标目录不存在则自动创建 if (-not (Test-Path $Dest)) { New-Item -ItemType Directory -Path $Dest | Out-Null } # 递归查找所有exe文件,提取对应源路径下的一级子目录并去重 $foldersToMove = Get-ChildItem -Recurse -Path $Source -Filter *.exe -File | ForEach-Object { $relativePath = $_.FullName.Substring($Source.Length).TrimStart('\','/') $firstLevelFolder = $relativePath.Split('\','/')[0] Join-Path $Source $firstLevelFolder } | Select-Object -Unique # 批量移动符合要求的一级文件夹 foreach ($folder in $foldersToMove) { Move-Item -Path $folder -Destination $Dest -Force }
批处理实现方案
通过延迟变量标记已处理的文件夹,避免重复操作:
@echo off setlocal enabledelayedexpansion set "Source=C:\TestSource" set "Dest=C:\TestDestination" :: 目标目录不存在则自动创建 if not exist "%Dest%" md "%Dest%" set "processed=" :: 遍历所有exe文件,提取对应一级子文件夹后移动 for /r "%Source%" %%i in (*.exe) do ( for /f "delims=\" %%a in ("%%~pi:%Source:\=%%") do ( set "targetFolder=%Source%\%%a" :: 仅处理未移动过的文件夹 if "!processed:%%a=!"=="!processed!" ( move /y "!targetFolder!" "%Dest%\" set "processed=!processed!%%a;" ) ) ) endlocal
内容的提问来源于stack exchange,提问作者Michael Moore
相关产品推荐
相关产品推荐

