PowerShell无法去除文件BOM,追加内容出现乱码求助
PowerShell追加文件出现UTF8 BOM及NULL乱码的解决方法
问题根源
你的核心问题是写入和追加时编码不统一,加上PowerShell 5.1中Out-File的编码行为易混淆,导致乱码和BOM问题:
- 你设置的
$OutputEncoding仅控制PowerShell管道输出到外部程序的编码,对Out-File无效 - PowerShell 5.1里
Out-File -Encoding utf8生成的是带BOM的UTF-8,而非你想要的无BOM格式 - 追加时未指定
-Encoding参数,Out-File默认使用Unicode(UTF-16LE)编码,这种编码下ASCII字符会被存储为双字节(高字节为0),在UTF8文件中打开就会显示为[NULL] - 你尝试去除BOM的命令写错了(
Get-Cotent应为Get-Content),且Get-Content读取文件时会自动忽略BOM,无法通过字符串替换移除BOM
解决方案
1. 统一使用无BOM的UTF-8编码写入/追加(推荐)
直接用.NET文件操作方法精确控制编码,避免PowerShell cmdlet的编码歧义:
# 定义无BOM的UTF8编码对象 $utf8NoBom = [System.Text.UTF8Encoding]::new($false) # 初始写入文件 $out = @' #################### # # Shortcuts # #################### '@ [System.IO.File]::WriteAllText($ShortcutNotes, $out, $utf8NoBom) # 追加内容(修改函数代码) 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] $line = "`nApp added: $AppName" # 加换行符确保内容换行 [System.IO.File]::AppendAllText($ShortcutNotes, $line, $utf8NoBom) } }
若使用PowerShell 7及以上版本,可直接用Out-File的utf8NoBom编码参数,更简洁:
# 初始写入 $out | Out-File -FilePath $ShortcutNotes -Force -Encoding utf8NoBom # 追加内容 "App added: $AppName" | Out-File -FilePath $ShortcutNotes -Append -Encoding utf8NoBom
2. 修复已有乱码文件
如果已经生成带乱码的文件,可通过以下命令修复:
$filePath = $ShortcutNotes # 读取文件字节流 $bytes = [System.IO.File]::ReadAllBytes($filePath) # 跳过UTF8 BOM(如果存在) if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $bytes = $bytes[3..($bytes.Length-1)] } # 转换为字符串并移除UTF16导致的NULL字符 $content = [System.Text.UTF8Encoding]::new($false).GetString($bytes) -replace "`0", "" # 重新写入无BOM的UTF8文件 [System.IO.File]::WriteAllText($filePath, $content, [System.Text.UTF8Encoding]::new($false))
内容的提问来源于stack exchange,提问作者YorSubs
相关产品推荐
相关产品推荐

