GChuf
GChuf

Reputation: 2230

PowerShell Out-File outputs extra spaces in between characters

I'm using a simple script that outputs current directory's path inside a log file:

(Get-Item .).FullName | out-file "C:\windows\system32\rcwm\rc.log" -append

This works most of the time. However, seemingly at random, appending will result in added spaces after every character in the output string. My rc.log file will then look like this:

C:\Users\root\Desktop\2222
C : \ U s e r s \ r o o t \ D e s k t o p \ 2 2 2 2 

Notice how I outputted the same directory name twice, and the results inside the log file were different.

Once this happens, every subsequent string appended into the log file will have spaces in between characters.

What could be the issue?

Upvotes: 10

Views: 13653

Answers (1)

GChuf
GChuf

Reputation: 2230

After some time, I decided to try to change the encodings with which powershell outputs strings inside my log file.

I still don't understand why or how powershell decides which encoding to use, but it's best if you let powershell know which encoding you want to use:

(Get-Item .).FullName | out-file "C:\windows\system32\rcwm\rc.log" -append -Encoding UTF8

For me, UTF-8 seems to work best.

C:\Users\root\šč   (UTF8)
C:\Users\root\??   (ASCII)
C : \ U s e r s \ r o o t \ a   (UNICODE)
 C   :   \   U   s   e   r   s   \   r   o   o   t   \   a   (UTF32)
C:\Users\root\šč\ő\~2\üē (UTF8)

Output file

EDIT: I've since come across "chcp" command (change code page). The code for UTF-8 is 65001. For more information, you can take a look at this question here.

Upvotes: 10

Related Questions