10

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?

2
  • Why are you using Get-Item for this vs [(Get-ChildItem -Path C:\ -Directory).FullName]? No encoding is needed for this kind of use case.
    – postanote
    Commented Oct 19, 2020 at 0:03
  • Because I need the path of the current directory, not paths of subdirectories.
    – GChuf
    Commented Oct 19, 2020 at 10:53

1 Answer 1

10

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.

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.