为何PowerShell 5会向日志文件添加空字符而PowerShell 7不会?
PowerShell 5中Out-File写入日志出现字符间空字符的问题及解决方法
问题场景
脚本同时兼容PowerShell 7和5,但在PowerShell 5环境下,用以下代码写入的日志文件每个字符后都会插入空字符(在VSCode中可见,复制后仅显示空值0),PowerShell 7中写入的日志格式正常。
原日志写入代码:
Write-Output "$logDate $thisScriptName v$thisScriptVersion - Script Started" | Out-File $logHistory -Append
问题原因
PowerShell 5中Out-File的默认编码为Unicode(UTF-16LE),这种编码会给每个ASCII字符额外分配一个空字节,导致日志文件出现字符间的空字符;而PowerShell 7中Out-File的默认编码改为了UTF-8,因此无此问题。
解决方法
有两种可行的解决方式:
- 方式一:给
Out-File显式指定编码参数,比如ASCII或UTF-8:Write-Output "$logDate $thisScriptName v$thisScriptVersion - Script Started" | Out-File $logHistory -Append -Encoding ascii # 或者使用UTF-8编码 # Write-Output "$logDate $thisScriptName v$thisScriptVersion - Script Started" | Out-File $logHistory -Append -Encoding utf8 - 方式二:改用
Add-Content命令替代Out-File,该命令在PowerShell 5中的默认编码更符合常规文本需求:Add-Content -Value "$logDate $thisScriptName v$thisScriptVersion - Script Started" -Path $logHistory
内容的提问来源于stack exchange,提问作者RapidScampi
相关产品推荐
相关产品推荐

