PowerShell,无法从文件中删除BOM



我已经尝试了几十个不同的选项一个小时了,去掉BOM,将文件设置为ascii / oem / utf8,遵循这里的想法,但BOM在所有情况下都保持不变。我有点不知所措。

首先,我总是使用Remove-Item-Force来确保在开始之前没有文件的剩余部分,然后我将一些简单的文本管道传输到新创建的文件中:

$out = @'
####################
#
# Shortcuts
#
####################
'@
$OutputEncoding = [Text.Utf8Encoding]::new($false)
$out | Out-File -FilePath $ShortcutNotes -Force -Encoding utf8
# I have tried utf8 / oem / ascii

这部分文本在最终文件中看起来总是很好,没有任何奇怪之处。

但后来我把一些操作的一些相当无害的输出导入到文件中,一切都出了问题:

# Some operations before here, but this is the important line:
$AppName = (($AppShortcut -split "\")[-1] -split ".")[0]
"App added: $AppName" | Out-File -FilePath $ShortcutNotes -Append

最终的结果是,当我在Notepad++中打开文件时,我得到了带有BOM的UTF8,它看起来是这样的(标题部分总是很好,然后其余部分有NULL(:

####################
#
# Shortcuts
#
####################
A[NULL]p[NULL]p[NULL] [NULL]a[NULL]d[NULL]d[NULL]e[NULL]d[NULL]:[NULL] [NULL]G[NULL]o[NULL]o[NULL]g[NULL]l[NULL]e[NULL] [NULL]C[NULL]h[NULL]r[NULL]o[NULL]m[NULL]e

我甚至试着在事后剥离BOM:

(Get-Cotent $ShortcutNotes) -replace "xEFxBBxBF", "" | Set-Content $ShortcutNotes

以上所有操作都失败了,文件总是带有BOM的UTF8,并且总是像上面那样乱码。

我已经没有什么可尝试的了,有人能看到我做错了什么吗?我的输出总是这样混乱?

更新我在标头之后所做的操作非常简单,但它们可能会提示出问题所在。这是被调用并写入文件的函数的一个片段。这似乎是造成问题的原因,但我不知道是如何/为什么:

function Setup-AppAndShortcut ($AppFolder, $ZipFile, $AppExe, $AppShortcut) {
if (Test-Path $AppExe) {
$ShortcutFile = $AppShortcut
$Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
$Shortcut.TargetPath = $AppExe
$Shortcut.Save()
[string]$AppName = (($AppShortcut -split "\")[-1] -split ".")[0]
"App added: $AppName" | Out-File -FilePath $ShortcutNotes -Append   # These are the lines that always end up garbled with NULLs in my final output.
}

使用add content而不是out file-append,这可以在同一文件中混合不同的编码。错误报告:

out file-append(或>>(可以在同一文件中混合使用两种编码。·Issue#9423·PowerShell·GitHub

最新更新