0

I'm trying to write a loop for matching the strings with keys in the dictionary.

I'm trying to match each and every string in the app.config file with each and every key in the dictionary. for example, there is one string called "client", I have to match this string with all the keys in dictionary. if the string matches, replace the value "Arizona" with string in app.config file, otherwise skip.

Can someone please suggest me in writing the loop for matching and replacing.

2
  • Use [Regex]::Replace with MatchEvaluator. Commented Apr 25, 2016 at 16:30
  • @PetSerAl Actually I'm trying to write separate script just for matching the strings and replacing the values. Commented Apr 25, 2016 at 16:39

2 Answers 2

0

If I'm understanding your question, then don't see any reason to use Regex.Replace here. String.Replace is probably better since you want to match literal string values.

The weird thing about hash tables is that they're harder to enumerate than arrays, so they're a bit more awkward to feed to foreach or ForEach-Object.

Try something like this:

foreach ($Key in $HashTable.Keys) {
    $FieldName = '{{' + $Key.ToString() + '}}';
    $FieldValue = $HashTable.Item($Key).ToString();
    $AppConfig = $AppConfig.Replace($FieldName, $FieldValue);
}

Or you can use this:

foreach ($Hash in $HashTable.GetEnumerator()) {
    $FieldName = '{{' + $Hash.Key.ToString() + '}}';
    $FieldValue = $Hash.Value.ToString();
    $AppConfig = $AppConfig.Replace($FieldName, $FieldValue);
}

Both should work. You must specify the GetEnumerator() method because hash tables are not normally enumerated objects.

Sign up to request clarification or add additional context in comments.

2 Comments

Why use regex? Because it's usually faster, doesn't require a loop and it's fun. :-)
@Bacon Bits, Thanks for sharing the solution. But somehow it is not able to replace the values.
0

The simple implementation for the script will look like below. I have tested it for the inputs you have specified successfully.

[regex]::Replace($appConfigFile, "{{(\w*)}}",{param($match) $dictionaryObject[$($match.Groups[1].Value)]})

Assuming, $appConfigFile has the contents of the App.Config file and $dictionaryObject has been created as below:

$dictionaryObject = @{}
$dictionaryObject.Add("client","Arizona") 
$dictionaryObject.Add("type","Test")

...and so on.

Reference: Regex.Replace Method (String, MatchEvaluator)

Comments

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.