当我使用它时:
"$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"
文件中的文字看起来很奇怪,看起来像这样:
如果我将代码更改为只写入现有文件,如:
$LogFile = "C:\ArchiveStorage\Log.txt"
文本文件应该是:
为什么它会制作空格和所有随机的废话?
答案 0 :(得分:3)
你被双字节Unicode击中了。例如,当字母A
写入文件时,通常会有一个字节值0x41
。在双字节Unicode中,A
的字节值为0x0041
或0x4100
,具体取决于字节顺序。
当记事本打开一个没有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。