跳转到内容
markdown
# PowerShell 多级目录结构递归替换工具指南

## 功能概述
本工具用于递归替换文件系统中任意位置的连续目录结构,支持以下核心功能:
- 动态层级替换(支持1-N层目录结构)
- 安全预览模式(-WhatIf参数)
- 智能路径验证
- 执行前二次确认
- 内容无损迁移
- 空目录自动清理

## 完整脚本代码

```powershell
param(
    [Parameter(Mandatory = $true)]
    [string]$OldStructure,
    
    [Parameter(Mandatory = $true)]
    [string]$NewStructure,
    
    [Parameter()]
    [ValidateScript({
        if (-not (Test-Path $_ -PathType Container)) {
            throw "路径不存在或不是目录: $_"
        }
        $true
    })]
    [string]$RootPath = $(Get-Location).Path,
    
    [switch]$WhatIf
)

$oldParts = $OldStructure -split '/'
$newParts = $NewStructure -split '/'
$structureDepth = $oldParts.Count

if ($oldParts.Count -ne $newParts.Count) {
    throw "错误:旧结构 ($structureDepth 层) 与新结构 ($($newParts.Count) 层) 的层级数量不一致"
}

$regexPattern = ($oldParts | ForEach-Object { [regex]::Escape($_) }) -join '\\'
$fullMatchPattern = "(.*?\\?)($regexPattern)(\\|$)"

Write-Host "正在扫描目录 (旧结构深度: $structureDepth 层)..." -ForegroundColor Cyan
Write-Host "扫描根目录: $RootPath" -ForegroundColor DarkGray

$candidates = Get-ChildItem -Path $RootPath -Recurse -Directory |
    Where-Object { $_.FullName -match $fullMatchPattern } |
    Sort-Object { $_.FullName.Split('\').Count } -Descending

if (-not $candidates) {
    Write-Host "未找到匹配的目录结构" -ForegroundColor Yellow
    exit
}

if (-not $WhatIf) {
    # 安全确认提示内容
    # ...
}

foreach ($dir in $candidates) {
    try {
        # 路径替换和操作逻辑
        # ...
    }
    catch {
        Write-Warning "操作失败: $($dir.FullName)"
        Write-Warning $_.Exception.Message
    }
}

if ($WhatIf) {
    Write-Host "`n预览模式已结束 (模拟影响目录数: $($candidates.Count))" -ForegroundColor Cyan
} else {
    Write-Host "`n成功完成结构替换 (实际处理目录数: $($candidates.Count))" -ForegroundColor Green
}

使用说明

基本参数

参数说明示例值
-OldStructure要替换的旧结构(/分隔)"old/project"
-NewStructure新目录结构(/分隔)"new/backup"
-RootPath搜索根目录(默认当前目录)"D:\data"
-WhatIf启用预览模式[开关参数]

使用示例

powershell
# 预览模式(单层结构)
.\rename.ps1 -OldStructure "temp" -NewStructure "cache" -WhatIf

# 实际执行(多层结构)
.\rename.ps1 -OldStructure "project/src" -NewStructure "archive/code" -RootPath "C:\work"

# 复杂结构替换(当前目录)
.\rename.ps1 -OldStructure "a/b/c/d" -NewStructure "x/y/z/w"

典型输出

正在扫描目录 (旧结构深度: 2 层)...
扫描根目录: C:\test

即将执行以下操作:
根目录    : C:\test
旧结构    : a/b (共 2 层)
新结构    : x/y (共 2 层)
影响目录数: 3
示例修改  :
  C:\test\demo\a\b
  → C:\test\demo\x\y

技术原理

正则表达式构建

powershell
# 示例:将 "a/b/c" 转换为正则模式
$regexPattern = "a\\b\\c"
$fullMatchPattern = "(.*?\\?)(a\\b\\c)(\\|$)"

匹配模式说明:

  1. (.*?\\?) 捕获前置路径
  2. (a\\b\\c) 精确匹配目标结构
  3. (\\|$) 确保结构完整性

目录处理算法

  1. 深度优先扫描Get-ChildItem -Recurse
  2. 结构匹配:正则表达式全文匹配
  3. 排序机制:按路径深度降序排列
  4. 原子操作
    • 新建目标目录
    • 迁移文件内容
    • 删除源目录

注意事项

安全规范

  1. 始终先在测试目录验证
  2. 生产环境操作前必须使用-WhatIf
  3. 确保对目标目录有完全控制权限
  4. 避免在系统目录(如Windows、Program Files)操作

异常处理

错误类型处理方式
路径不存在验证脚本自动拦截
权限不足捕获异常并跳过
文件正在使用记录错误继续后续操作
目录非空保留源目录并显示警告

扩展知识

PowerShell特性应用

  1. 参数验证
powershell
[ValidateScript({Test-Path $_})]  # 路径存在性检查
  1. 管道优化
powershell
Get-ChildItem | Where-Object | Sort-Object  # 流式处理提升性能
  1. 路径操作
powershell
$_.FullName.Split('\')  # 跨平台路径分割

正则表达式特殊处理

  1. 转义处理:
powershell
[regex]::Escape("test.dir") → "test\.dir"
  1. 上下文保留:
powershell
-replace "(prefix)$regexPattern", "`$1$newStructure"

版本更新日志

版本主要特性
1.0基础多级目录替换功能
1.1增加-WhatIf参数和安全确认
1.2支持动态层级结构
1.3优化根目录默认值处理
1.4增强正则匹配算法和错误处理机制

推荐测试方案

  1. 创建测试环境:
powershell
New-Item -Path "test/a/b/c" -ItemType Directory -Force
"test" > test/a/b/c/file.txt
  1. 执行测试命令:
powershell
.\rename.ps1 -OldStructure "a/b/c" -NewStructure "x/y/z" -WhatIf
  1. 验证结果:
  • 检查预览输出是否符合预期
  • 确认实际文件未修改
  • 测试不同层级结构的边界情况

> 注意:实际使用时请根据具体需求调整参数和目录结构,建议在非生产环境充分测试后再进行重要操作。