0

I have the following hashtable:

$lookupTable = @{
    "^XXX"="123";
    "^YYY"="456";
    "cat"="dog"
}

I'm performing a bulk find & replace operation in files as such:

Foreach-Object {
    $file = $_
    Write-Host "$file"
    (Get-Content -Path $file) | ForEach-Object {
        $line = $_
        $lookupTable.GetEnumerator() | ForEach-Object {
            $line = $line -replace "$_.Name", "$_.Value"
        }
        $line
    } | Set-Content -Path $file
}

You'll notice I have an anchor/caret (^) on the first two pairs of the hashtable. This is because I want to perform a regex on these so they only match if they are at the beginning of the line. For the third set ("cat"="dog") I want to match anywhere (no regular expressions). Unfortunatley, it seems to be taking the ^ literally and is not finding matches nor doing a regex evaluation. I tried defining the regex like below and it works for the first two sets ("XXX"="123" & "YYY"="456"), but it won't work for the third set ("cat"="dog") as I need to find cat anywhere in the file, not just at the beginning of the line:

$line = $line -replace "^$($_.Name)", "$($_.Value)"

How can I accomplish this? Thank you very much.

Dominic Brunetti
  • 989
  • 3
  • 18
  • 36

1 Answers1

0

I figured it out. The trick was to remove the quotes (") from $line = $line -replace "$_.Name", "$_.Value" so it would actually interpolate the item vs. treating it as a literal string. So the correct code should be:

$line = $line -replace $_.Name, $_.Value

Dominic Brunetti
  • 989
  • 3
  • 18
  • 36
  • 1
    Your solution is effective (and better than your original attempt), but the explanation isn't correct: `"..."` strings _do_ interpolate (unlike `'..'` strings), it's just that you need to enclose _expressions_ such as property references in `$(...)` - see the linked post. – mklement0 Jul 30 '19 at 23:27
  • 1
    Spot on. I wasn't sure what to search for and as I'm sure you know, learning is like peeling an onion. Thank you for the linked post. I'm studying up on how PowerShell handles `"..."`. – Dominic Brunetti Jul 31 '19 at 00:25
  • Glad to hear it. Can I suggest you correct your answer so as not to confuse future readers? – mklement0 Jul 31 '19 at 14:44