The problem isn't whether you're using relative or absolute paths (assuming your relative paths are relative to the right directory).
Rather, the problem is that the -replace
operator is regex-based, and that |
is therefore interpreted as a regex metacharacter (representing alternation).
Therefore, you need to escape such metacharacters, using \
(or, if you were to do this programmatically, you could use the [regex]::Escape()
method).
Additionally, since your replacement operation isn't line-specific, you can speed up your operation by reading the file into memory as a whole, using the -Raw
switch.
That, in turn, requires that you use the -NoNewLine
switch when (re)writing the file.
Also, with text input, Set-Content
is preferable to Out-File
for performance reasons.
To put it all together:
(Get-Content -Raw .\test.csv) -replace '\|', '$' | Set-Content -NoNewLine .\test.csv
Note: Use the -Encoding
parameter as needed, as the input file's encoding will not be honored:
In Windows PowerShell, Out-File
produces UTF-16LE ("Unicode") files by default, whereas Set-Content
uses the system's ANSI code page.
In PowerShell (Core) 7+, BOM-less UTF-8 is the consistently applied default.