替换键值对中的文本

Replace a text from the key value pairs

我正在尝试从字典的键值对中替换文本。这是我正在处理的 powershell 脚本,

foreach ($string in $templatestrings) {


               if($Dictionary.ContainsKey($string))
                {
                    $Dictionary.Keys | % { $templatecontent = $templatecontent -replace "{{$string}}", ($Dictionary[$_]) }
                 }  

    }
 $templatecontent | set-content $destinationfilename

}

基本上如果文本值与字典键匹配,那么我们将用字典值替换文本。似乎更换部件没有按预期工作。我想用字典值替换文本值。 I'm storing the text values in $templatecontent variable. 谁能告诉我替换这些文本值的正确方法。

您已经检查字典是否包含您的键,因此您可以使用索引运算符访问要替换的值 []:

foreach ($string in $templatestrings) 
{
    if($Dictionary.ContainsKey($string))
    {
        $templatecontent = $templatecontent -replace "{{$string}}", ($Dictionary[$string])
    }  
}

但是,您可以将其简化很多,正如我在上一个回答中所展示的那样:

$templatecontent = Get-Content $sourcefilename
$Dictionary.Keys | % { $templatecontent = $templatecontent -replace "{{$_}}", ($Dictionary[$_]) } 
templatecontent | set-content $destinationfilename

这三行将用字典中的 value 替换每个 {{key}}。您甚至不需要 regex 来捕获 $templatestrings.