powershellutf-8byte-order-mark

Write-Output with no BOM


If I run a command like this:

Write-Output March > a.txt

I get this result:

        U+FEFF    
M       U+004D          
a       U+0061          
r       U+0072    
c       U+0063          
h       U+0068 
        U+000D       
\n      U+000A       

I do not want the BOM. I tried different actions, like this:

$OutputEncoding = [System.Text.UTF8Encoding]::new($false)
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
[Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false)
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)

but none of them seem to address the issue. Note I am using PowerShell 5.1. I did see some similar questions, but not quite the same issue as this, as they were dealing with piping and external commands.


Solution

  • If you're only using ascii characters, set-content would be fine in powershell 5.1:

    Write-Output March | set-content a.txt
    'March' | set-content a.txt
    

    Or set the default encoding of out-file to ascii in your $profile with this hashtable. The default encoding of out-file is utf16 or 'unicode' encoding. '>' is a shortcut for out-file. The name of the key has to be quoted because it contains a colon. utf8nobom isn't available until later powershell versions. '>>' also invokes out-file and may mix encodings in the same file.

    $PSDefaultParameterValues = @{ 'out-file:encoding' = 'ascii' }
    

    Then this will make an ascii file:

    Write-Output March > a.txt