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

如何对父文件夹下的每个子文件夹批量执行指定PowerShell脚本?

PowerShell 批量扁平化一级子目录脚本实现

最终脚本

# 接受传入的父文件夹路径参数
param(
    [Parameter(Mandatory = $true)]
    [string]$ParentFolderPath
)

# 校验父文件夹路径是否存在
if (-not (Test-Path -Path $ParentFolderPath -PathType Container)) {
    Write-Error "指定的父文件夹路径不存在,请检查输入"
    exit 1
}

# 遍历父文件夹下所有一级子文件夹
Get-ChildItem -Path $ParentFolderPath -Directory -Depth 0 | ForEach-Object {
    $currentRoot = $_.FullName
    # 1. 移动当前子文件夹下所有递归文件到子文件夹根目录
    Get-ChildItem -Path $currentRoot -Recurse -File | Move-Item -Destination $currentRoot -Force
    # 2. 删除当前子文件夹下所有子目录
    Get-ChildItem -Path $currentRoot -Recurse -Directory | Remove-Item -Recurse -Force
    # 3. 删除当前子文件夹根目录下所有JSON文件
    Get-ChildItem -Path $currentRoot -Filter "*.json" -File | Remove-Item -Force
}

脚本说明

  • 无需手动切换工作目录,所有操作通过绝对路径执行,避免误操作其他目录文件
  • 仅处理父文件夹下的一级子文件夹,不会修改父文件夹本身的内容
  • 默认添加-Force参数,同名文件会直接覆盖、只读文件/目录会直接删除,不需要该逻辑可删除对应位置的-Force参数

使用方法

  1. 将上述脚本保存为FlattenChildFolders.ps1
  2. 打开PowerShell终端,执行以下命令即可:
.\FlattenChildFolders.ps1 -ParentFolderPath "替换为你的父文件夹绝对路径"

提示:首次运行可先在所有Remove-Item后添加-WhatIf参数,执行后会先预览要删除的内容,确认无误后再去掉-WhatIf正式执行,避免误删数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:24:03