代码之家  ›  专栏  ›  技术社区  ›  Mike Christensen

使用PowerShell[duplicate]用文件中的环境变量替换字符串

  •  0
  • Mike Christensen  · 技术社区  · 7 年前

    我有一个类似这样的文件:

    <Parameter Name="WebImage" Value="web:${BuildNumber}" />
    <Parameter Name="ApiImage" Value="api:${BuildNumber}" />
    

    ${xxx} 在包含环境变量的文件中 xxx

    我在尝试这样的事情:

    (Get-Content .\Cloud.xml) -replace "\$\{(\w+)\}", "$([Environment]::GetEnvironmentVariable('$1'))"
    

    然而,我只是得到:

    <Parameter Name="WebImage" Value="web:" />
    <Parameter Name="ApiImage" Value="api:" />
    

    这个 GetEnvironmentVariable 呼叫工作,因为我可以:

    (Get-Content .\Cloud.xml) -replace "\$\{(\w+)\}", "$([Environment]::GetEnvironmentVariable('BuildNumber'))"
    

    $1 电话工作,因为我可以做:

    (Get-Content .\Cloud.xml) -replace "\$\{(\w+)\}", '$1'
    

    我会得到:

    <Parameter Name="WebImage" Value="web:BuildNumber" />
    <Parameter Name="ApiImage" Value="api:BuildNumber" />
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   Kirill Pashkov    7 年前

    尝试使用 $Matches 自动变量。

    (Get-Content .\Cloud.xml) | 
        ForEach-Object { 
            if ($_ -match "\$\{((\w+))\}")
            {
                $_ -replace "\$\{(\w+)\}",$([Environment]::GetEnvironmentVariable($Matches[1]))
            }
            else
            {
                $_
            }
        }
    
    推荐文章