If you run
Out-File -InputObject "A" -FilePath "test.txt"
you will get both a BOM at the start of the file and a windows-newline at the end of the file. The same happens with Set-Content.
How can I prevent this from happening? What is the best way to output a string, and only the string, to a file?
If your string is plain ASCII I've noticed that you could do this in PowerShell5 (no -NoNewline in PowerShellS4)
Out-File -InputObject "A" -FilePath "test.txt" -Encoding "ascii" -NoNewline
but this does not help much if you have something outside of ASCII.
This is one of those things that PowerShell doesn't really help you do, but you can do with the underlying .NET framework very easily. What you want is UTF8 encoding without a BOM, and to get that, you use the default constructor of the UTF8Encoding class:
$encoding = New-Object System.Text.UTF8Encoding [System.IO.File]::WriteAllText("$pwd\test.txt", "Testing", $encoding)
PowerShell's cmdlets, unfortunately, don't take an actual Encoding object. Instead, they take an enumerated type that's meant to be more user friendly (with tab completion and whatnot).
When calling the .NET methods directly, just be careful not to send in any relative paths. The .NET framework's idea of your "current directory" is different from what PowerShell uses for its PSDrives. Here's how you can safely translate an arbitrary PSPath into one that's safe for .NET (even if the path doesn't already exist):
You can also use Resolve-Path, but unfortunately, that will fail if the item doesn't exist yet.
Not the pretties thing I've seen, but it works 🙂 Thanks
You must be logged in to reply to this topic.