mahesh
mahesh

Reputation: 478

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

            }
          }

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

Upvotes: 2

Views: 165

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58991

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

Upvotes: 1

Related Questions