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

如何用PowerShell递归扁平化P:\files目录?求循环实现方案

扁平化PowerShell目录结构:移动所有子目录文件到根目录

既然你已经能正确获取所有层级的文件,实现移动的方式很直接,这里给你两种实用写法:

  • 管道式(最简洁):
    直接把获取到的文件通过管道传给Move-Item命令,指定目标路径为根目录即可:

    Get-ChildItem -LiteralPath P:\files -Directory | Get-ChildItem -Recurse -File | Move-Item -Destination P:\files
    
  • 显式foreach循环(适合需要额外自定义逻辑的场景):
    先把文件存入变量,再逐个执行移动操作:

    $targetFiles = Get-ChildItem -LiteralPath P:\files -Directory | Get-ChildItem -Recurse -File
    foreach ($file in $targetFiles) {
        Move-Item -LiteralPath $file.FullName -Destination P:\files
    }
    

额外提示

如果移动完成后需要清理所有空的子目录,可以执行:

Get-ChildItem -LiteralPath P:\files -Directory -Recurse | Remove-Item -Recurse

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:31:42