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

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

            }
          }

Can someone kinldy tell me how to replace the respective values with strings .

0

1 Answer 1

1

Please nail down your problem next time you ask a question. You want to replace a text from the key value pairs of a dictionary.

You mistake was, that you always read the $sourcefilename, replaced the text and wrote to destinationfilename. Probably only the last entry of your dictionary was replaced.

So you have to read the content only once, iterate over your dictionary and replace the values:

$templatecontent = Get-Content $sourcefilename
$Dictionary.Keys | % { $templatecontent = $templatecontent -replace "{{$_}}", ($Dictionary[$_]) } 
templatecontent | set-content $destinationfilename
Sign up to request clarification or add additional context in comments.

5 Comments

Jisaak, thanks for the reply. I wanted to replace the text if it matches with the dictionary key. That is the reason for adding the if condition. When I'm running the script, it is asking me for some value if ("$string" -match "$key") { $templatecontent = Get-Content $sourcefilename $Dictionary.Keys | % { $templatecontent = $templatecontent -replace "{{$_}}", ($Dictionary[$_]) } set-content $destinationfilename } Output cmdlet Set-Content at command pipeline position 1 Supply values for the following parameters: Value[0]: Can you please tell me the possible solution.
yes, I forgot to pipe the content to the Set-Content cmdlet. Fixed my answer.
Yes. It is working fine now. I appreciate it. Thank you so much for the solution Jisaak.
you are welcome. Even I suggested you to use a hashtable instead of a dictonary ;-)
Actually instead of matching each string with key, I'm trying to do this, if($Dictionary.ContainsKey($string)) { $Dictionary.Keys | % { $templatecontent = $templatecontent -replace "{{$string}}", ($Dictionary.Keys) } $templatecontent | set-content $destinationfilename } But this is not working. Do you know what is the mistake I'm doing here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.