【问题标题】:Not able to replace the strings in PowerShell无法替换 PowerShell 中的字符串
【发布时间】:2016-08-26 16:31:14
【问题描述】:
            if ("$string" -match "$key")
            {
                    Write-Host "Attempting to replace $string with $value in $sourcefilename"

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

            }
          }

谁能告诉我如何用字符串替换相应的值。

【问题讨论】:

    标签: xml string powershell powershell-2.0


    【解决方案1】:

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

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

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

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

    【讨论】:

    • Jisaak,感谢您的回复。如果文本与字典键匹配,我想替换它。这就是添加 if 条件的原因。当我运行脚本时,它要求我提供一些值if ("$string" -match "$key") { $templatecontent = Get-Content $sourcefilename $Dictionary.Keys | % { $templatecontent = $templatecontent -replace "{{$_}}", ($Dictionary[$_]) } set-content $destinationfilename } 输出cmdlet Set-Content at command pipeline position 1 Supply values for the following parameters: Value[0]: 你能告诉我可能的解决方案吗?
    • 是的,我忘记将内容通过管道传输到 Set-Content cmdlet。修正了我的答案。
    • 是的。现在工作正常。我很感激。非常感谢 Jisaak 的解决方案。
    • 不客气。甚至我建议您使用哈希表而不是字典 ;-)
    • 实际上,我没有将每个字符串与键匹配,而是尝试这样做,if($Dictionary.ContainsKey($string)) { $Dictionary.Keys | % { $templatecontent = $templatecontent -replace "{{$string}}", ($Dictionary.Keys) } $templatecontent | set-content $destinationfilename } 但这不起作用。你知道我在这里犯了什么错误吗
    猜你喜欢
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 2013-02-01
    • 2017-03-06
    • 2011-01-20
    • 2015-10-30
    • 1970-01-01
    相关资源
    最近更新 更多