0

I'm trying to write a loop for replacing the all the matching values.

Key                                                          Value                                                       
---                                                          -----                                                       
client                                                      xxxx                                                  
type                                                         Test                                                        
name                                                     xxx                                          
env                                                    ALL     

and I have another app.config file, looks as follows,

    <add key="ClientName" value="{{client}}" />
    <add key="InstallForClients" value="{{client}}" />

I'm tring to match each and every string (which exits between two curly braces ) with each and every key in dictionary. if it is match, replace string with value.

I'm not able to replace the values. Here is the powershell script I'm working on,

if ("$string" -eq "$stringtocheck")
{
echo "Replacing $stringtocheck with $newstring in $source"
(Get-content $source) | ForEach-Object { $_ -replace '{{$stringtocheck}}', $newstring } | Set-Content $destination
}
}

Can someone please help me in updating this replacing loop.

2
  • not sure if this is the only issue, but right here: -replace '{{$stringtocheck}}' you should change the single quotes to double quotes if you want to use the value of your $stringtocheck variable Commented Apr 26, 2016 at 20:27
  • Even with double quotes, it is not working. Commented Apr 26, 2016 at 20:36

1 Answer 1

0

try this

$config = Get-Content 'C:\temp\configoriginal.txt'

$hash = @{
    '{client}' = '{Arizona}'
    '{type}' = '{Test}'
    '{servicename}' = '{DataGenerator}'
    '{filetype}' = '{ALL}'
}

foreach ($key in $hash.Keys) {
    $config = $config -replace [regex]::Escape($key), $hash[$key]
}

$config | Set-Content 'C:\temp\configchanged.txt'
Sign up to request clarification or add additional context in comments.

3 Comments

Updated my script with this line, $config = $source -replace [regex]::Escape($stringtocheck), $myDictionary.GetEnumerator() $config | Set-Content $destination But I'm still not able to replace the values.
you said you updated your script. have you tried just using my script? try replacing c:\temp\configoriginal.txt with the path of your config file.
I have used this command. $config = $source -replace [regex]::Escape($stringtocheck), $myDictionary.GetEnumerator() $config | Set-Content $destination

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.