cstafford
cstafford

Reputation: 387

Powershell .Replace RegEx

RegEx for Replace is kicking my butt. I am trying find:

value="COM8"/>

in a text file and replace "COM8" with another com port (ie "COM9", "COM13", etc).

(Get-Content 'C:\Path\File.config').Replace('/".*?"', '"COM99"') | Set-Content 'C:\Path\File.config'

Thank you in advance for any help you can provide.

Upvotes: 5

Views: 6941

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Get-Content produces a list of strings. Replace() is called on each string via member enumeration. Meaning, you're calling the String.Replace() method, not the Regex.Replace() method. The former does only normal string replacements.

Use the -replace operator instead:

(Get-Content 'C:\Path\File.config') -replace '=".*?"', '="COM99"' |
    Set-Content 'C:\Path\File.config'

Upvotes: 9

Related Questions