跳转到内容

完整脚本

powershell
<#
.SYNOPSIS
递归修改文件夹名、文件名及文件内容中的指定字符串
.DESCRIPTION
功能增强:
1. 支持递归修改文件夹名称中的目标字符
2. 支持递归修改文件名称中的目标字符
3. 支持递归修改文件内容中的目标字符
#>

param(
    [string]$RootPath = ".",    # 目标路径(默认当前目录)
    [Parameter(Mandatory=$true)]
    [string]$OldString,         # 被替换的旧字符
    [Parameter(Mandatory=$true)]
    [string]$NewString,         # 替换后的新字符
    [switch]$WhatIf,            # 模拟运行模式
    [string[]]$FileTypes = @("*.txt", "*.csv", "*.ps1", "*.xml") # 指定处理文件类型
)

# 安全警告
Write-Host "即将执行替换操作:[$OldString] → [$NewString]" -ForegroundColor Yellow
if (-not $WhatIf) {
    $confirm = Read-Host "确认执行?(Y/N)"
    if ($confirm -ne 'Y') { exit }
}

# 函数:递归处理文件夹名称
function Rename-Folders {
    Get-ChildItem -Path $RootPath -Directory -Recurse | 
    Sort-Object -Descending FullName | 
    ForEach-Object {
        $newDirName = $_.Name -replace [regex]::Escape($OldString), $NewString
        if ($newDirName -ne $_.Name) {
            Rename-Item -Path $_.FullName -NewName $newDirName -Verbose -WhatIf:$WhatIf
        }
    }
}

# 函数:递归处理文件名称
function Rename-Files {
    Get-ChildItem -Path $RootPath -File -Recurse -Include $FileTypes | 
    ForEach-Object {
        $newFileName = $_.Name -replace [regex]::Escape($OldString), $NewString
        if ($newFileName -ne $_.Name) {
            Rename-Item -Path $_.FullName -NewName $newFileName -Verbose -WhatIf:$WhatIf
        }
    }
}

# 函数:递归处理文件内容
function Replace-Content {
    Get-ChildItem -Path $RootPath -File -Recurse -Include $FileTypes | 
    ForEach-Object {
        try {
            $content = Get-Content $_.FullName -Raw -Encoding UTF8
            if ($content -match [regex]::Escape($OldString)) {
                $newContent = $content -replace [regex]::Escape($OldString), $NewString
                if (-not $WhatIf) {
                    $newContent | Set-Content $_.FullName -Encoding UTF8 -NoNewline -Force
                }
                Write-Host "已修改文件内容:$($_.FullName)" -ForegroundColor Cyan
            }
        }
        catch {
            Write-Host "处理失败:$($_.Exception.Message)" -ForegroundColor Red
        }
    }
}

# 执行流程
Rename-Folders   # 先处理文件夹名称(逆序防路径失效)
Rename-Files     # 再处理文件名称
Replace-Content  # 最后处理文件内容

Write-Host "操作完成!建议检查文件编码是否匹配(如二进制文件需排除)" -ForegroundColor Green

核心优化解析(基于搜索资料)

  1. 文件内容处理增强
    • 新增Replace-Content函数,使用Get-Content -Raw读取完整内容,通过正则匹配替换字符串 • 支持指定文件类型过滤($FileTypes参数),避免误改二进制文件 • 强制使用-Encoding UTF8参数保障编码一致性

  2. 安全机制升级
    • 文件内容修改前增加匹配检查,避免无意义写入 • 异常捕获机制防止单个文件处理失败导致中断

  3. 执行顺序优化
    • 按文件夹→文件名→文件内容顺序处理,避免路径变更影响后续操作


使用示例

powershell
# 示例1:修改当前目录及子目录中所有.txt/.csv文件的"apple"为"orange"
.\Replace-Script.ps1 -OldString "apple" -NewString "orange" -FileTypes "*.txt","*.csv"

# 示例2:模拟运行测试(仅预览不实际修改)
.\Replace-Script.ps1 -OldString "2023" -NewString "2024" -WhatIf

# 示例3:处理自定义文件类型(如.xml和.ps1)
.\Replace-Script.ps1 -OldString "dev" -NewString "prod" -FileTypes "*.xml","*.ps1"

注意事项(基于搜索资料)

  1. 编码兼容性
    • 非UTF-8编码文件(如ANSI)需调整-Encoding参数,否则可能乱码 • 处理二进制文件(如.exe/.jpg)需从$FileTypes中排除

  2. 权限要求
    • 系统文件需以管理员身份运行PowerShell

  3. 大文件处理
    • 超大文件(>1GB)建议改用流式处理:

    powershell
    (Get-Content $path) -replace $OldString,$NewString | Set-Content $path

操作前建议备份:Copy-Item -Path $RootPath -Destination "备份路径" -Recurse