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

PowerShell脚本开发需求:规范主文件夹子目录命名格式并批量创建统一子文件夹结构

PowerShell脚本修正:规范文件夹命名并创建统一子结构

先来看看你的脚本里存在的几个关键问题,我们一步步修正:

  • 正则表达式缺少结束符$,导致部分不符合的名称(比如A1234Extra)会被误判为符合格式
  • 重命名逻辑错误:你用了$_但在ForEach循环里应该引用$dir,而且-replace的用法完全反了,会把正确的匹配内容删掉,而不是提取有效部分
  • 拼写错误:$folder_names应该是$folders_names(多了个s)
  • 遗漏了Orders下的两个子文件夹创建
  • 路径拼接方式不严谨,直接用"$root\$dir"可能会出现格式问题
  • 没有判断文件夹是否已存在,重复创建会抛出错误

下面是修正后的完整脚本:

# 主文件夹路径
$root = "C:\Work files\Test\Main folder"
# 匹配规则:大写字母开头 + 四位数字,严格匹配整个文件夹名
$pattern = "^[A-Z]\d{4}$"
# 定义需要创建的基础子文件夹结构
$baseFolders = @("Customers", "Supplier", "Items")
# Orders文件夹下的子结构
$ordersSubFolders = @("Sub Folder1", "Sub Folder2")

# 获取主文件夹下的所有子目录
$dirs = Get-ChildItem -Path $root -Directory

foreach ($dir in $dirs) {
    # 检查文件夹名称是否符合规范
    if (-not ($dir.Name -match $pattern)) {
        # 尝试从现有名称中提取第一个大写字母+后续四位数字的有效部分
        if ($dir.Name -match "([A-Z]\d{4})") {
            $newName = $matches[1]
            # 重命名文件夹(-Force确保覆盖同名文件夹,谨慎使用)
            Rename-Item -Path $dir.FullName -NewName $newName -Force
            # 更新$dir变量为重命名后的文件夹对象
            $dir = Get-Item -Path (Join-Path $root $newName)
            Write-Host "已修正文件夹名称:$($dir.Name) -> $newName"
        }
        else {
            Write-Warning "无法从文件夹名称 '$($dir.Name)' 中提取有效格式,跳过重命名"
            continue
        }
    }

    # 创建基础子文件夹
    foreach ($folderName in $baseFolders) {
        $folderPath = Join-Path -Path $dir.FullName -ChildPath $folderName
        if (-not (Test-Path -Path $folderPath)) {
            New-Item -Path $folderPath -ItemType Directory | Out-Null
            Write-Host "已创建文件夹:$folderPath"
        }
    }

    # 创建Orders文件夹及其子文件夹
    $ordersPath = Join-Path -Path $dir.FullName -ChildPath "Orders"
    if (-not (Test-Path -Path $ordersPath)) {
        New-Item -Path $ordersPath -ItemType Directory | Out-Null
        Write-Host "已创建文件夹:$ordersPath"
    }
    foreach ($subFolder in $ordersSubFolders) {
        $subFolderPath = Join-Path -Path $ordersPath -ChildPath $subFolder
        if (-not (Test-Path -Path $subFolderPath)) {
            New-Item -Path $subFolderPath -ItemType Directory | Out-Null
            Write-Host "已创建文件夹:$subFolderPath"
        }
    }
}

Write-Host "所有操作完成!"

关键改进点说明:

  • 正则表达式优化:用^[A-Z]\d{4}$严格匹配整个文件夹名,确保只有「单个大写字母+四位数字」的名称才符合规范
  • 重命名逻辑修正:从不符合规范的名称中提取有效部分(如果存在),如果完全无法提取则给出警告并跳过
  • 路径处理更安全:使用Join-Path拼接路径,避免因特殊字符或格式问题导致的路径错误
  • 存在性检查:创建文件夹前先判断是否已存在,避免重复创建抛出错误
  • 结构完整性:补充了Orders下的两个子文件夹创建逻辑
  • 状态反馈:添加了Write-Host输出操作日志,方便查看执行情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:12:40