无 BOM 的写输出 [英] Write-Output with no BOM

查看:45
本文介绍了无 BOM 的写输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行这样的命令:

If I run a command like this:

Write-Output March > a.txt

我得到了这个结果:

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

我不想要 BOM.我尝试了不同的操作,如下所示:

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)

但他们似乎都没有解决这个问题.注意我使用的是 PowerShell 5.1.一世确实看到了一些类似的问题,但与此不完全相同,因为它们正在处理管道和外部命令.

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.

推荐答案

如果您只使用 ascii 字符,则 set-content 在 powershell 5.1 中会很好:

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

或者使用这个哈希表在你的 $profile 中将 out-file 的默认编码设置为 ascii.out-file 的默认编码是 utf16 或 'unicode' 编码.'>'是输出文件的快捷方式.必须引用密钥的名称,因为它包含一个冒号.utf8nobom 直到后来的 powershell 版本才可用.'>>'还调用 out-file 并可能在同一文件中混合编码.

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' }

然后这将生成一个 ascii 文件:

Then this will make an ascii file:

Write-Output March > a.txt

这篇关于无 BOM 的写输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆