无法替换 PowerShell 中的字符串

Not able to replace the strings in PowerShell

            if ("$string" -match "$key")
            {
                    Write-Host "Attempting to replace $string with $value in $sourcefilename"

                   (Get-Content $sourcefilename).Replace("{{$string}}",$value) | set-content $destinationfilename

            }
          }

谁能告诉我如何用字符串替换各个值。

确定您的问题 下次您提问时。 您想从字典的键值对中替换文本。

你的错误是,你总是阅读 $sourcefilename,替换文本并写信给 destinationfilename。可能只有你字典的最后一个条目被替换了。

所以你只需要阅读一次内容,遍历你的字典并替换值:

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