0

I am trying to copy csv file contents and append to a text file. The copying and appending works, but the appended format is weird.

This is the command I use:

Get-Content -Path myfile1.csv | Select-object -skip 1 | Out-File mynewfile.txt -Append

The appended text looks like this when opened in notepad:

1 0 2 3 8 9, 1, A B C, P 2 

instead of

102389,1,ABC,P2 

There's a space between every character. Just renaming the .csv to .txt didn't help.

1
  • Check the encoding on the two files. If one is ASCII and the other is UTF-8, that could be the problem. Commented Jul 31, 2021 at 10:19

2 Answers 2

0

Try using Add-Content cmdlet:

The Add-Content cmdlet appends content to a specified item or file. You can specify the content by typing the content in the command or by specifying an object that contains the content.

Get-Content -Path myfile1.csv | Select-object -skip 1 | Add-Content mynewfile.txt 
0

In PowerShell 5.1, the default encoding for Out-File is unicode (UTF16-LE), whereas in PowerShell 7.x the default encoding is utf8NoBOM.
Apparently, your input file is encoded differently, like with ASCII or UTF-8. and when adding UTF16-LE text to it, the result is what you experience.

Out-File has an -Encoding parameter, so you can fix your code by appending -Encoding default OR by using Add-Content instead of Out-File.

Encoding Default is the encoding that corresponds to the system's active code page (usually ANSI)
Add-Content also has a parameter -Encoding. In PowerShell 5.1 it defaults to Default. In PowerShell 7.x the default encoding is utf8NoBOM.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.