Okay, so I’ve set up a hash table with names being what to replace and keys being what to replace with, like this:
$r = @{
"dog" = "canine";
"cat" = "feline";
"eric" = "eric cartman"
}
What should I do next? I’ve tried this:
(Get-Content C:\scripts\test.txt) | Foreach-Object {
foreach ( $e in $r.GetEnumerator() ) {
$_ -replace $e.Name, $e.Value
}
} | Set-Content C:\scripts\test.txt.out
But it doesn’t work at all, it just writes each line three times, without replacing anything.
EDIT: Contains of test.txt:
dog
cat
eric
test.txt.out:
dog
dog
dog
cat
cat
cat
eric
eric
eric
Here’s one way to do it:
The reason you were seeing each line three times is because of the nested foreach loop. A replace operation was running once per hashtable entry for every line in the file. That doesn’t change the source file, but by default it does output the result of the replace (even if nothing is changed).
You can get the desired functionality by reading the file into a variable first, and then using your looping replace to update that variable. You also don’t need a separate foreach loop for the file contents; the replace can run against the full text in one pass per hashtable entry.