2016-06-20 40 views
1

我真的很困惑,爲什麼我會在將字符串值附加到CSV時得到一個有趣的輸出。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 2.0。

回答

3

看起來像powershell Set-Content命令默認爲ANSI,但>>回聲默認爲unicode http://www.kongsli.net/2012/04/20/powershell-gotchas-redirect-to-file-encodes-in-unicode/

您可以力Set-Content使用Unicode 集內容$ AutomonitorCSV -Force - 值 「類型,基礎,現狀」 -Encoding統一

或使用

Add-Content $AutomonitorCSV $status 

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

你也可以使用Out-File-encoding參數強制相應的編碼:

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

無論哪種方式,我覺得Set-Content命令做的事情有點出乎意料至於默認編碼。

+0

謝謝,這兩個選項的工作。我確實嘗試了文件,但沒有包含'-Encoding ascii'。 –