Home > OS >  Why the Powershell command replace not working for me
Why the Powershell command replace not working for me

Time:01-21

I am trying to replace a string in a file like this:

c:\>powershell -Command (gc D:\xxxxxxx\index.html) ^   
 -replace '^<script src="js/locale/languageholder.js"^>^</script^>', '' ^
| Out-File -encoding ASCII "D:\yyyyyyyyy\index.html"

the string I want to remove is:

<script src="js/locale/languageholder.js"></script>

no errors, but it is just not replaced. I assume there must be some charactors to be escaped, but couldn't figure it out.

In the code ^ is used to escape <, otherwise it will show this error:

< was unexpected at this time.

Getting the same error using \ to escape

CodePudding user response:

You need to \-escape all " characters that you want to pass through to the PowerShell command that is ultimately executed, after the PowerShell CLI has stripped unescaped " characters, if any, during command-line parsing:

powershell -Command (gc D:\xxxxxxx\index.html) ^   
 -replace '^<script src=\"js/locale/languageholder.js\"^>^</script^>', '' ^
  | Out-File -encoding ASCII \"D:\yyyyyyyyy\index.html\"

See this answer for more information.

CodePudding user response:

The easiest way is to have an external powershell file:

replace.ps1:

(gc index.html) -replace '<script src="js/locale/languageholder.js"></script>' |
  set-content index2.html

Then run:

powershell -file replace.ps1
  •  Tags:  
  • Related