Xml 无法替换PowerShell中的字符串
有人能告诉我如何用字符串替换相应的值吗 下次你提问时,请把你的问题弄清楚。 要替换字典键值对中的文本。 您的错误是,您总是阅读Xml 无法替换PowerShell中的字符串,xml,string,powershell,powershell-2.0,Xml,String,Powershell,Powershell 2.0,有人能告诉我如何用字符串替换相应的值吗 下次你提问时,请把你的问题弄清楚。 要替换字典键值对中的文本。 您的错误是,您总是阅读$sourcefilename,替换文本并写入destinationfilename。可能只有你字典的最后一个条目被替换了 因此,您只需阅读一次内容,在字典中迭代并替换值: if ("$string" -match "$key") { Write-Host "Attempting to
$sourcefilename
,替换文本并写入destinationfilename
。可能只有你字典的最后一个条目被替换了
因此,您只需阅读一次内容,在字典中迭代并替换值:
if ("$string" -match "$key")
{
Write-Host "Attempting to replace $string with $value in $sourcefilename"
(Get-Content $sourcefilename).Replace("{{$string}}",$value) | set-content $destinationfilename
}
}
Jisaak,谢谢你的回复。我想替换与字典键匹配的文本。这就是添加if条件的原因。当我运行脚本时,它要求我提供一些值
if(“$string”-match“$key”){$templatecontent=Get Content$sourcefilename$Dictionary.Keys |%{$templatecontent=$templatecontent-replace”{{$},($Dictionary[$}}})set Content$destinationfilename}
Outputcmdlet在命令管道位置1设置内容为以下参数提供值:值[0]:
请告诉我可能的解决方案。是的,我忘记将内容通过管道传输到Set Content
cmdlet。修正了我的答案。是的。它现在运转良好。我很感激。非常感谢您提供的解决方案Jisaak。不客气。甚至我建议您使用哈希表而不是口述;-)实际上,我没有将每个字符串与键匹配,而是尝试这样做,if($Dictionary.ContainsKey($string)){$Dictionary.Keys |%{$templatecontent=$templatecontent-替换“{{$string}”,($Dictionary.Keys)}$templatecontent |设置内容$destinationfilename}
,但这不起作用。你知道我在这里犯了什么错误吗
$templatecontent = Get-Content $sourcefilename
$Dictionary.Keys | % { $templatecontent = $templatecontent -replace "{{$_}}", ($Dictionary[$_]) }
templatecontent | set-content $destinationfilename