1

I am really confused on why I am getting a funny output when appending string value to a CSV.

I have the following code

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

Which outputs

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 

I need to append the $status at the end of the csv as the software needs to pick this line up. However it keeps adding spaces after each character. When I output in powershell it looks fine. How do I get it to output properly so I get

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

Note, I have to use PowerShell v2.0 because of 2003 hosts.

1 Answer 1

3

Looks like the powershell Set-Content command defaults to ANSI, but the >> echo defaults to unicode http://www.kongsli.net/2012/04/20/powershell-gotchas-redirect-to-file-encodes-in-unicode/ .

You can either force Set-Content to use Unicode Set-Content $AutomonitorCSV -Force -Value "Type,Base,Status" -Encoding Unicode

or use

Add-Content $AutomonitorCSV $status 

which seems to use the original format of the file.

You could also use Out-File with the -encoding parameter to force the appropriate encoding:

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

Either way, I'd think that the Set-Content command is doing something a little unexpected with regards to the default encoding.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, both options work. I did try out-file but did not inlcude -Encoding ascii.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.