代码之家  ›  专栏  ›  技术社区  ›  mhenrixon

如何使用powershell在文件中的特定行后插入文本?

  •  1
  • mhenrixon  · 技术社区  · 15 年前

    作为大型重构的一部分,我删除了一些重复的类和枚举。我移动了名称空间并重新构造了所有内容,以便将来更容易维护。

    我目前拥有的代码不起作用,但我想这是我需要的。

    function Insert-Usings{
        trap {
            Write-Host ("ERROR: " + $_) -ForegroundColor Red
            return $false 
        }
        (Get-ChildItem $base_dir -Include *.asmx,*.ascx,*.cs,*.aspx -Force -Recurse -ErrorAction:SilentlyContinue) | % {
        $fileName  = $_.FullName
        (Get-Content $fileName) | 
            Foreach-Object 
            {
                $_
                if ($_ -cmatch "using Company.Shared;") { 
                        $_ -creplace "using Company.Shared;", "using Company.Common;"
                }
                elseif ($_ -cmatch "using Company") {
                    #Add Lines after the selected pattern 
                    "using Company.Services.Contracts;"
                }
                else{
                    $_
                }
            }
        } | Set-Content $fileName
    }
    

    代码倾向于使用Company.Services.Contracts语句输出(覆盖整个文件)。

    1 回复  |  直到 15 年前
        1
  •  4
  •   Roman Kuzmin    15 年前

    目前还不太清楚您到底要得到什么,但我将尝试猜测,请参阅代码中的注释。我认为,最初的代码有几个错误,其中一个是严重的: Set-Content 在错误的管道/循环中使用。这是正确的代码。

    function Insert-Usings
    {
        trap {
            Write-Host ("ERROR: " + $_) -ForegroundColor Red
            return $false
        }
        (Get-ChildItem $base_dir -Include *.asmx,*.ascx,*.cs,*.aspx -Force -Recurse -ErrorAction:SilentlyContinue) | % {
            $fileName  = $_.FullName
            (Get-Content $fileName) | % {
                if ($_ -cmatch "using Company\.Shared;") {
                    # just replace
                    $_ -creplace "using Company\.Shared;", "using Company.Common;"
                }
                elseif ($_ -cmatch "using Company") {
                    # write the original line
                    $_
                    # and add this after
                    "using Company.Services.Contracts;"
                }
                else{
                    # write the original line
                    $_
                }
            } |
            Set-Content $fileName
        }
    }
    

    例如,它取代了:

    xxx
    
    using Company.Shared;
    
    using Company;
    
    ttt
    

    xxx
    
    using Company.Common;
    
    using Company;
    using Company.Services.Contracts;
    
    ttt
    

    注意:假设您不应该将此代码多次应用于源代码,此代码不是为此而设计的。

    推荐文章