Powershell .Replace RegEx

2020-04-30 03:33发布

问题:

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.

回答1:

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'