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

使用PowerShell仅取消XML配置中第二个authentication节点的注释

问题修复方案

问题根因

你现有脚本的问题在于:每次匹配到Token类型的authentication注释开头后,直接对整个xml文件内容数组执行-replace全局替换操作,而非仅处理目标注释区间内的行,因此所有匹配</authentication> -->的内容都会被替换。

修复后脚本

$web_service_config_path = [IO.Path]::Combine("D:\Scripts\Powershell", "Web_Sample.config")
# 按行读取配置内容
$xmlLines = Get-Content $web_service_config_path
# 存储处理后的行内容
$processedLines = @()
# 标记是否处于目标Token注释的处理区间
$inTargetBlock = $false
$endProcessed = $false

foreach ($line in $xmlLines) {
    if ($endProcessed) {
        # 已处理完目标块,后续行直接原样保留
        $processedLines += $line
        continue
    }

    if (-not $inTargetBlock) {
        # 匹配Token类型authentication的注释开头
        if ($line -match '^\s*<!--\s*<authentication authenticationType="Token"\s*sessionTimeout="00:10:00"') {
            # 去掉开头的注释标记,同时修改sessionTimeout为00:30:00
            $processedLine = $line -replace '^\s*<!--\s*<authentication authenticationType="Token"\s*sessionTimeout="00:10:00"', '<authentication authenticationType="Token" sessionTimeout="00:30:00"'
            $processedLines += $processedLine
            $inTargetBlock = $true
        }
        else {
            # 非目标行直接原样保留
            $processedLines += $line
        }
    }
    else {
        # 匹配目标块的结束注释
        if ($line -match '</authentication>\s*-->') {
            # 去掉结尾的注释标记
            $processedLine = $line -replace '</authentication>\s*-->', '</authentication>'
            $processedLines += $processedLine
            $inTargetBlock = $false
            $endProcessed = $true
        }
        else {
            # 目标块中间的行直接原样保留
            $processedLines += $line
        }
    }
}

# 输出处理后的文件,可根据原文件编码调整Encoding参数
$processedLines | Out-File -FilePath "D:\Scripts\Powershell\Web_new.config" -Encoding UTF8

脚本说明

  • 采用逐行处理的逻辑,只有匹配到Token类型的authentication注释块时才进入处理状态
  • 仅修改目标块的开头注释和结尾注释,不会影响其他位置的相同匹配内容
  • 处理完目标块后后续内容直接原样输出,执行效率更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:18:01