Question:
I have a function that performs a regex replace in a file. The problem is that that it adds a character (0x00) to the start of every file it touches (even the ones that it doesn’t find a match for!). Since I am editing csproj files, MSBuild gives me this error:
1 2 |
error MSB4025: The project file could not be loaded. '.', hexadecimal value 0x00, is an invalid character. Line 2, position 1. |
Here is my function:
1 2 3 4 5 6 7 8 9 10 11 12 |
function fileStringRegExReplace ([string] $fileToChange, [string] $oldString, [string] $newString) { echo "f" | xcopy "$fileToChange" "$fileToChange.og.cs" /Y /Q $file = Get-Content "$fileToChange.og.cs" | Foreach-Object { $_ -replace $oldString, $newString } | Out-File "$fileToChange" Remove-Item "$fileToChange.og.cs" } |
How can I replace the lines I want and not change any other part of the file?
Answer:
It sounds like it’s writing a BOM at the beginning of the file. You can set the encoding to ASCII (which has no BOM) using the -Encoding ASCII
parameter on out-file
.