Reputation: 478
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.
Upvotes: 0
Views: 2323
Reputation: 1990
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)
Upvotes: 0
Reputation: 32220
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.
Upvotes: 0