CSV附加普通字符串/文本行

时间:2016-06-20 16:18:56

标签: csv powershell

我真的很困惑为什么在将字符串值附加到CSV时我得到一个有趣的输出。

我有以下代码

Set-Content $AutomonitorCSV -Force -Value "Type,Base,Status"
$now = get-date -Format "ddd MMM dd HH:mm:ss BST yyyy"
$status = "<!>Status,Last ran at $now"
$status >> $AutomonitorCSV

哪个输出

Type,Base,Status
< ! > S t a t u s , L a s t   r a n   a t   M o n   J u n   2 0   1 6 : 2 8 : 3 3   B S T   2 0 1 6 

我需要在csv末尾添加$status,因为软件需要选择此行。但是它会在每个字符后面添加空格。当我在powershell中输出它看起来很好。如何正确输出以便我得到

Type,Base,Status
<!>Status,Last ran at Mon Jun 20 16:28:33 BST 2016

注意,由于2003年的主机,我必须使用PowerShell v2.0。

1 个答案:

答案 0 :(得分:3)

看起来powershell Set-Content命令默认为ANSI,但>> echo默认为unicode http://www.kongsli.net/2012/04/20/powershell-gotchas-redirect-to-file-encodes-in-unicode/

您可以强制Set-Content使用Unicode     Set-Content $ AutomonitorCSV -Force -Value&#34; Type,Base,Status&#34; - 编码Unicode

或使用

Add-Content $AutomonitorCSV $status 

似乎使用了文件的原始格式。

您还可以使用Out-File -encoding参数强制进行相应的编码:

$status | Out-File -Append $AutomonitorCSV -Encoding ascii

无论哪种方式,我都认为Set-Content命令在默认编码方面做了一些意想不到的事情。