PowerShell's -replace
operator is regex-based; since your intent is to replace all |
characters verbatim, you must escape |
as \|
, given that |
is a regex metacharacter (a character with special meaning in the context of a regex (regular expression)):
powershell -Command "(gc output.txt) -replace '\|', ' ' | Out-File -encoding ASCII output.txt"
In cases where escaping individual characters isn't an option or would be cumbersome - e.g. if you're given a search string that you want to treat literally, as a whole - use [regex]::Escape()
:
powershell -Command "(gc output.txt) -replace [regex]::Escape('|'), ' ' | Out-File -encoding ASCII output.txt"
Alternatively, in your simple case you could use the .Replace()
string method, which invariably performs verbatim replacements and therefore does not require escaping:
powershell -Command "(gc output.txt).Replace('|', ' ') | Out-File -encoding ASCII output.txt"
Note:
- Unlike PowerShell's operators, the
[string]
type's .Replace()
method is case-sensitive, invariably so in Windows PowerShell, and by default in PowerShell (Core) 6+.
See also:
For general guidance on when to use PowerShell's -replace
operator vs. the .NET [string]
type's .Replace()
method, see the bottom section of this answer.
For robustly escaping all metacharacters in a -replace
search regex and/or in its replacement operand in order to treat one or both as verbatim strings, see this answer.