Wednesday, March 23, 2016

Redirecting command prompt output to files without butchering the encoding

I just answered this Super User question, which asked how to stop the command prompt from mangling the encoding of the fancy box-drawing characters in the output of tree. The characters showed up fine in the console, but got wrecked when the output was redirected to a file. No amount of chcp encoding changing helped.

The only way around it I could think of was to use a program that plays nice with text encoding. PowerShell was a great candidate - it handles UTF-16LE just fine, and can easily put the output of a classic command into a file.

The old broken command:

tree > tree.txt

The PowerShell command (with equivalent shorter version below):

Invoke-Expression "tree" | Out-File "tree.txt"
iex "tree" > "tree.txt"

Running the PowerShell command from the command prompt:

powershell -command "iex \"tree\" > \"tree.txt\""

The resulting file is intact and can be seen with type or in Notepad.

No comments:

Post a Comment