2016-05-04 5 views
0

辞書のキー値のペアのテキストを置き換えようとしています。ここで私が働いている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.誰かが私にこれらのテキスト値を置き換える正しい方法を教えてもらえますか?

+0

このコードを使用して、最後の質問とはどのように違うのですか? – Matt

+0

@Matt 実際に前の質問では、各文字列をキーで照合して値を置き換えていました。今、 'if条件 'を次のように更新しました。 ' $ Dictionary.ContainsKey($ string) '.. 値を置き換える正しい方法を教えてください。ありがとうございました。 – mahesh

答えて

0

あなたはすでにあなたがインデックス演算子[]を使用して交換する値にアクセスできるように辞書があなたの鍵が含まれているかどうか確認してください。

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

私は私の最後に示したようしかし、あなたは、このをたくさん簡素化することができます答え:彼は辞書fromt

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

これら3行はvalueを持つすべての{{key}}を置き換えます。 $templatestringsをキャプチャするために、regexは必要ありません。

+0

はい。これはうまくいきます。私はそれを感謝します。解決策をありがとうございました。 – mahesh