I wanted to automate the creation of a directory tree file in Windows 10.
In PowerShell, I executed the following commands:
cd C:\TreeTest
tree /f > .\TreeStructure.txt
The output was a pretty UTF-8 file:
Now I wanted to do the same thing in a batch file:
@echo off
cd C:\TreeTest
tree /f > .\TreeStructure.txt
But the output from the batch file execution had the encoding screwed up:
Why is the encoding of the PowerShell output different from the output of the batch file?
I know that I can get an ASCII output by adding /a to the tree command, but I would prefer the pretty UTF-8 output to be saved to my tree file.
I tried changing the codepage by adding "chcp 65001" to my batch file, but it didn't change the file output.
Best Answer
LotPing's answer is right. Just for detailed description:
The
>
redirection operator (send specified stream to a file):UCS-2 LE BOM
:cmd.exe
):cmd.exe /A
(default): encoding of an output file isANSI
, andcmd.exe /U
: encoding of an output file isUCS-2 LE
(noBOM
):However, output of the pretty old-fashioned utility
tree.com
isn't ready to be converted to Unicode. Therefore, straightstart "" cmd /U /C "tree>tree_U.txt"
still produces (mojibake) garbled,ANSI
encoded file. The followingcmd
commands should do the trick:BTW, here are those pretty characters and their codes (garbled in
ANSI
):