You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell移动指定归档目录内容到新路径并保留原有文件夹结构

PowerShell 实现归档目录内容按结构移动方案

以下脚本可直接满足需求:匹配所有名称符合* Archive规则的子目录,将目录内所有内容移动到指定目标路径,完整保留内部文件夹层级,且不会修改原父目录的结构。

# 配置目标归档根路径,可根据实际需求修改
$targetRoot = 'C:\Users\Documents\Archive'
# 获取所有匹配规则的归档目录,和你原有写法逻辑完全一致
$archiveDirs = Get-ChildItem -Path 'C:\Unsigned Items\*\*\* Archive' -Directory

foreach ($archiveDir in $archiveDirs) {
    # 递归遍历当前归档目录下的所有文件
    Get-ChildItem -Path $archiveDir.FullName -Recurse -File | ForEach-Object {
        # 计算文件相对于当前归档目录的相对路径
        $relativePath = $_.FullName.Substring($archiveDir.FullName.Length).TrimStart('\')
        # 拼接文件在目标位置的完整路径
        $destPath = Join-Path -Path $targetRoot -ChildPath $relativePath
        # 自动创建目标路径下不存在的层级目录
        $destDir = Split-Path -Path $destPath -Parent
        if (-not (Test-Path -Path $destDir)) {
            New-Item -Path $destDir -ItemType Directory -Force | Out-Null
        }
        # 执行移动操作,加-Force会自动覆盖目标路径下的同名文件,不需要可删除该参数
        Move-Item -Path $_.FullName -Destination $destPath -Force
    }
}
  • 如果你已经提前通过$srcRoot = (Get-ChildItem -Path 'C:\Unsigned Items\*\*\* Archive' -Directory).FullName拿到了归档目录路径数组,直接把foreach的遍历对象替换为$srcRoot即可,不需要修改其他逻辑
  • 移动效果示例:原路径C:\Users\Nick\Documents\City 1\City 1 Archive\2024\05\receipt.pdf,移动后对应路径为C:\Users\Documents\Archive\2024\05\receipt.pdf,内部层级完全不变
  • 首次执行建议先做验证:把脚本中Move-Item开头的行替换为Write-Host "待移动: $($_.FullName) -> $destPath",运行后会打印所有文件的移动映射,确认路径符合预期后再换回移动命令正式执行
  • 脚本默认不会移动归档目录下的空文件夹,如果需要完整保留空目录结构,可在文件遍历逻辑结束后,补充遍历归档目录下的所有子目录,在目标路径对应位置创建同名空目录即可

内容的提问来源于stack exchange,提问作者Medium Rare

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 10:18:43