Logan
Logan

Reputation: 13

PowerShell Find and Replace in file issues

I am having trouble finding how to find and replace in a file using poweshell. The file has several lines that are similar. I need to change the "ACT" to "RDY" in the line that starts with <PC_4 . All Lines start with < and end with >.

The Code:

powershell -Command(Get-Content C:\testfodler\test.XML) -replace '<PC_4 SET_THING="ACT">', '<PC_4 SET_THING="RDY">' | Out-File -encoding ASCII myFile.txt

The error I get is:

The '<' operator is reserved for future use.
Not all parse errors were reported.  Correct the reported errors and try again.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : RedirectionNotSupported

Running this on a windows 10 machine.

Upvotes: 1

Views: 170

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

First, you should quote the value (code) passed to the -Command parameter because it expects a string. How you quote depends on how you call powershell.exe.

If you are in PowerShell or CMD and are calling powershell.exe, you may surround the code passed to -Command with double quotes and double quote escape ("") inner double quotes, which is the PowerShell layer of escaping. Then backslash escape the escaping quote, which is for the cmd layer of escaping.

powershell.exe -command "(Get-Content C:\testfolder\test.XML) -replace '<PC_4 SET_THING=\""ACT\"">', '<PC_4 SET_THING=\""RDY\"">' | Set-Content myfile.txt -encoding ASCII"

Upvotes: 2

Related Questions