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

PowerShell脚本无法插入新行问题及文件写入验证咨询

问题背景

我想写一个小工具,在文件里找出所有这种格式的行:

[SecuredEndpoint(widgets.UpdateWidget)]

然后把它们改成:

//[SecuredEndpoint(widgets.UpdateWidget)]
 [AllowAnonymous]

目前我写了一段脚本(先在内存处理,还没写入文件):

#Find and comment out all [SecuredEndpoint] attributes
(Get-Content -path .\TestController.cs -Raw) -replace '\[SecuredEndpoint','//\[SecuredEnpoint' | Foreach-Object {
        $_ # send the current line to output
        if ($_ -match "//[SecuredEndpoint") 
        {
            #Add Lines after the selected pattern 
            "[AllowAnonymous]"
        }
    }

这段脚本能正确注释所有[SecuredEndpoint]行,但没法在注释后的行后面插入新行,执行结果如下:

[Route("widgets/")]
    [HttpGet]
    //[SecuredEnpoint(mywidget.GetAll)]
    public List<Widgets> GetWidgets()
    {
    }

    [Route("widgets/)]
    [HttpPost]
    //[SecuredEnpoint(mywidget.Create)]
    public List<Widgets> GetWidgets()
    {
    }

没有报错信息。

问题
  1. 逻辑里缺了什么才能实现插入新行?
  2. 修复后,下面这段写入文件的脚本是否可行?
(Get-Content -path .\TestController.cs -Raw) -replace '\[SecuredEndpoint','//[SecuredEnpoint' | Foreach-Object {
        $_ # send the current line to output
        if ($_ -match "//\[SecuredEndpoint") 
        {
            #Add Lines after the selected pattern 
            "[AllowAnonymous]"
        }
    } Set-Content .\TestController.cs
解答

问题1:无法插入新行的原因及修复

你用了Get-Content -Raw参数,这会把整个文件当成单个字符串传给管道,而不是按行拆分。Foreach-Object只会处理一次整个文件内容,不会逐行检查,自然没法在目标行后插入新行。另外脚本里还有拼写错误:SecuredEnpoint少了个d,会导致匹配逻辑失效。

修正后的内存处理脚本:

# 注释所有[SecuredEndpoint]属性并插入[AllowAnonymous]
Get-Content -path .\TestController.cs | Foreach-Object {
    # 替换并输出当前行
    $modifiedLine = $_ -replace '\[SecuredEndpoint','//\[SecuredEndpoint'
    $modifiedLine
    # 检查当前行是否是被注释后的目标行
    if ($modifiedLine -match "//\[SecuredEndpoint") 
    {
        # 保持和原代码一致的缩进(这里假设是4个空格,可根据实际调整)
        "    [AllowAnonymous]"
    }
}

问题2:写入文件的脚本是否可行

原脚本有两个致命问题,直接用会失效:

  1. 保留了-Raw参数,逐行处理逻辑无法生效;
  2. 管道末尾的Set-Content语法错误,应该用| Set-Content ...的形式。

修复后的写入文件脚本是可行的,代码如下:

Get-Content -path .\TestController.cs | Foreach-Object {
    $modifiedLine = $_ -replace '\[SecuredEndpoint','//\[SecuredEndpoint'
    $modifiedLine
    if ($modifiedLine -match "//\[SecuredEndpoint") 
    {
        "    [AllowAnonymous]"
    }
} | Set-Content .\TestController.cs

注意事项:

  • 要确保插入的[AllowAnonymous]行缩进和原代码一致,避免破坏格式;
  • 建议先备份原文件,防止意外修改导致代码丢失;
  • 如果原代码中[SecuredEndpoint]行的缩进不是4个空格,要对应调整插入行的空格数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:25:32