Powershell Add-content Out-File Text错误

时间:2014-09-04 10:09:17

标签: file powershell logging spaces ps1

当我使用它时:

"$LogTime $CurrentDate Invalid Archive Grouping selected. You selected '$ArchiveGrouping'" | Out-File $LogFile -Append -Force 

要写入使用此代码生成的文件:

$Logdate = Get-Date
$Logname = $Logdate.ToString("yyyyMMdd") + ".txt"
Add-Content -Path C:\ArchiveStorage\$Logname "Log" -force
$LogFile = "C:\ArchiveStorage\$Logname"

文件中的文字看起来很奇怪,看起来像这样: enter image description here

如果我将代码更改为只写入现有文件,如:

$LogFile = "C:\ArchiveStorage\Log.txt"

文本文件应该是: enter image description here

为什么它会制作空格和所有随机的废话?

2 个答案:

答案 0 :(得分:3)

你被双字节Unicode击中了。例如,当字母A写入文件时,通常会有一个字节值0x41。在双字节Unicode中,A的字节值为0x00410x4100,具体取决于字节顺序。

当记事本打开一个没有Unicode byte order mark的文件时,它假定文件内容中的所有额外00都是空格。这就是你看到w e r i d s p a c i n g的原因。

要修复此问题,请尝试将-Encoding ASCII参数与Add-Content一起使用。

答案 1 :(得分:2)

“Log”条目看起来不同,因为它们是使用Add-Content编写的,它使用ASCII的默认编码,而Out-File使用Unicode的默认编码。

在Out-File上指定编码类型,或切换到“Log”标题和详细信息行使用Add-Content。