替换PowerShell中的每个字符串都不能按预期工作

时间:2016-04-26 19:54:01

标签: powershell

我试图写一个循环来替换所有匹配的值。

Key                                                          Value                                                       
---                                                          -----                                                       
client                                                      xxxx                                                  
type                                                         Test                                                        
name                                                     xxx                                          
env                                                    ALL     

我有另一个app.config文件,如下所示,

    <add key="ClientName" value="{{client}}" />
    <add key="InstallForClients" value="{{client}}" />

我要将每个字符串(在两个花括号之间退出)与字典中的每个键匹配。如果匹配,则用值替换字符串。

我无法替换这些值。这是我正在处理的powershell脚本,

if ("$string" -eq "$stringtocheck")
{
echo "Replacing $stringtocheck with $newstring in $source"
(Get-content $source) | ForEach-Object { $_ -replace '{{$stringtocheck}}', $newstring } | Set-Content $destination
}
}

有人可以帮我更新这个替换循环。

1 个答案:

答案 0 :(得分:0)

试试这个

$config = Get-Content 'C:\temp\configoriginal.txt'

$hash = @{
    '{client}' = '{Arizona}'
    '{type}' = '{Test}'
    '{servicename}' = '{DataGenerator}'
    '{filetype}' = '{ALL}'
}

foreach ($key in $hash.Keys) {
    $config = $config -replace [regex]::Escape($key), $hash[$key]
}

$config | Set-Content 'C:\temp\configchanged.txt'