50

I'm trying to use the tree command in a windows commandline to generate a text file listing the contents of a directory but when I pipe the output the unicode characters get stuffed up.

Here is the command I am using:

tree /f /a > output.txt

The results in the console window are fine:

\---Erika szobája
        cover.jpg
        Erika szobája.m3u
        Kátai Tamás - 01 Télvíz.ogg
        Kátai Tamás - 02 Zölderdõ.ogg
        Kátai Tamás - 03 Renoir kertje.ogg
        Kátai Tamás - 04 Esõben szaladtál.ogg
        Kátai Tamás - 05 Ázik az út.ogg
        Kátai Tamás - 06 Sûrû völgyek takaród.ogg
        Kátai Tamás - 07 Õszhozó.ogg
        Kátai Tamás - 08 Mécsvilág.ogg
        Kátai Tamás - 09 Zúzmara.ogg

But the text file is no good:

\---Erika szob ja
        cover.jpg
        Erika szob ja.m3u
        K tai Tam s - 01 T‚lv¡z.ogg
        K tai Tam s - 02 Z”lderdä.ogg
        K tai Tam s - 03 Renoir kertje.ogg
        K tai Tam s - 04 Esäben szaladt l.ogg
        K tai Tam s - 05 µzik az £t.ogg
        K tai Tam s - 06 S–r– v”lgyek takar¢d.ogg
        K tai Tam s - 07 åszhoz¢.ogg
        K tai Tam s - 08 M‚csvil g.ogg
        K tai Tam s - 09 Z£zmara.ogg

How can I fix this? Ideally the text file would be exactly the same as the output in the console window.

I tried Chris Jester-Young's suggestion (what happened, did you delete it Chris?) of running the command line with the /U switch, it looked like exactly what I needed but it does not appear to work. I have tried opening the file in both VS2008 and notepad and both show the same incorrect characters.

11
  • Heh, I originally wrote a response to this thinking that it must work, but then I tested it and it didn't. D'oh! Sep 26, 2008 at 10:30
  • Yep I originally wrote you a comment thanking you for it and then had to delete it when I realised it didn't work! cmd /U looked perfect, why doesn't it do the job? Hmm
    – Paul Batum
    Sep 26, 2008 at 10:33
  • Try using an echo command to prepend the byte order mark to the file? en.wikipedia.org/wiki/Byte-order_mark
    – moonshadow
    Sep 26, 2008 at 10:40
  • Yes, I deleted my post: there's no point leaving misinformation around for people to stumble on, only to realise it doesn't work. :-| Sep 26, 2008 at 10:41
  • Paul, how are you viewing the text file? Sep 26, 2008 at 10:50

14 Answers 14

73

Have someone already tried this:

tree /f /a |clip

Open notepad, ctrl + V, save in notepad as output.txt with unicode support?

0
17

Use PowerShell:

powershell -command "tree /f > tree.txt"

Test case:

create.ps1:

mkdir "Erika szobája"
$null | Set-Content "Erika szobája/cover.jpg"
$null | Set-Content "Erika szobája/Erika szobája.m3u"
$null | Set-Content "Erika szobája/Kátai Tamás - 01 Télvíz.ogg"
$null | Set-Content "Erika szobája/Kátai Tamás - 02 Zölderdõ.ogg"
$null | Set-Content "Erika szobája/Kátai Tamás - 03 Renoir kertje.ogg"
$null | Set-Content "Erika szobája/Kátai Tamás - 04 Esõben szaladtál.ogg"
$null | Set-Content "Erika szobája/Kátai Tamás - 05 Ázik az út.ogg"
$null | Set-Content "Erika szobája/Kátai Tamás - 06 Sûrû völgyek takaród.ogg"
$null | Set-Content "Erika szobája/Kátai Tamás - 07 Õszhozó.ogg"
$null | Set-Content "Erika szobája/Kátai Tamás - 08 Mécsvilág.ogg"
$null | Set-Content "Erika szobája/Kátai Tamás - 09 Zúzmara.ogg"

Output:

tree.txt:

Folder PATH listing
Volume serial number is 00000000 0000:0000
C:.
│   create.ps1
│   tree.txt
│   
└───Erika szobája
        cover.jpg
        Erika szobája.m3u
        Kátai Tamás - 01 Télvíz.ogg
        Kátai Tamás - 02 Zölderdo.ogg
        Kátai Tamás - 03 Renoir kertje.ogg
        Kátai Tamás - 04 Esoben szaladtál.ogg
        Kátai Tamás - 05 Azik az út.ogg
        Kátai Tamás - 06 Sûrû völgyek takaród.ogg
        Kátai Tamás - 07 Oszhozó.ogg
        Kátai Tamás - 08 Mécsvilág.ogg
        Kátai Tamás - 09 Zúzmara.ogg

EDIT:

Enhanced and improved version for power users

List tree menu working with Unicode

Test case:

$null | Set-Content "欲速则不达.txt"
$null | Set-Content "爱不是占有,是欣赏.txt"
$null | Set-Content "您先请是礼貌.txt"
$null | Set-Content "萝卜青菜,各有所爱.txt"
$null | Set-Content "广交友,无深交.txt"
$null | Set-Content "一见钟情.txt"
$null | Set-Content "山雨欲来风满楼.txt"

$null | Set-Content "悪妻は百年の不作。.txt"
$null | Set-Content "残り物には福がある。.txt"
$null | Set-Content "虎穴に入らずんば虎子を得ず。.txt"
$null | Set-Content "夏炉冬扇.txt"
$null | Set-Content "花鳥風月.txt"
$null | Set-Content "起死回生.txt"
$null | Set-Content "自業自得.txt"

$null | Set-Content "아는 길도 물어가라.txt"
$null | Set-Content "빈 수레가 요란하다.txt"
$null | Set-Content "방귀뀐 놈이 성낸다.txt"
$null | Set-Content "뜻이 있는 곳에 길이 있다.txt"
$null | Set-Content "콩 심은데 콩나고, 팥 심은데 팥난다.txt"

From his answer, @Chris Jester-Young wrote:

Now, in ulib, the WriteString method is implemented in two classes, SCREEN and STREAM. The SCREEN version uses WriteConsoleW directly, so all the Unicode characters get correctly displayed. The STREAM version converts the Unicode text to one of three different encodings (_UseConsoleConversions ⇒ console codepage (GetConsoleCP), _UseAnsiConversions ⇒ default ANSI codepage, otherwise ⇒ default OEM codepage), and then writes this out.

This means that we cannot rely on getting the characters from a stream. File redirections won't work. We have to rely on writing to the console to get the Unicode characters.

The workaround, or hack, is to write the tree to the console and then dump the buffer to a file.

I have written the scripts to add the tree context menu when you right click on directories in Explorer. Save the files in the same directory and then run Install list menu.bat as administrator to install.

I have moved the latest code to GitHub:

2
  • For escaping the output filename if it has spaces, double up the inner double quotes: powershell -command "tree /f > ""output file.txt""" Jul 10, 2018 at 0:05
  • to create a new file just use New-Item
    – phuclv
    Dec 27, 2023 at 1:23
11

If you output as non-Unicode (which you apparently do), you have to view the text file you create using the same encoding the Console window uses. That's why it looks correct in the console. In some text editors, you can choose an encoding (or "code page") when you open a file. (How to output as Unicode I don't know. cmd /U doesn't do what the documentation says.)

The Console encoding depends on your Windows installation. For me, it's "Western European (DOS)" (or just "MS-DOS") in Microsoft Word.

3
  • 1
    How do I determine the encoding the console windows uses? I tried opening in word and it gave me the choice of encodings, I checked some of the more obvious ones and none of them looked right.
    – Paul Batum
    Sep 26, 2008 at 11:02
  • I answered this within the answer above.
    – bzlm
    Sep 26, 2008 at 11:07
  • 4
    Thanks bzim, you were right, opening in msword with "ms-dos" encoding works fine. Next step is for my program to parse the file, should be just a simple matter of selecting the equivalent encoding. Cheers!
    – Paul Batum
    Sep 26, 2008 at 20:45
6

I decided I had to have a look at tree.com and figure out why it's not respecting the Unicode setting of the console. It turns out that (like many of the command-line file utilities), it uses a library called ulib.dll to do all the printing (specifically, TREE::DisplayName calls WriteString in ulib).

Now, in ulib, the WriteString method is implemented in two classes, SCREEN and STREAM. The SCREEN version uses WriteConsoleW directly, so all the Unicode characters get correctly displayed. The STREAM version converts the Unicode text to one of three different encodings (_UseConsoleConversions ⇒ console codepage (GetConsoleCP), _UseAnsiConversions ⇒ default ANSI codepage, otherwise ⇒ default OEM codepage), and then writes this out. I don't know how to change the conversion mode, and I don't believe the conversion can be disabled.

I've only looked at this briefly, so perhaps more adventurous souls can speak more about it! :-)

4
  • Actually, "tree.com" not respecting the settings of cmd.exe looks like it's by design. In the documentation for cmd.exe, it specifically states that internal commands will have Unicode output. However, when I tried this with "dir", I got the same results. And "dir" is an internal command. Right?
    – bzlm
    Sep 27, 2008 at 7:14
  • Heh, after seeing /u not work, I'd be the last one to refer to the documentation for anything. :-P I'll see if I can spend some time on IDA figuring out what dir does in Unicode mode.... Sep 27, 2008 at 10:18
  • Well, just saying the docs were right on this particular point. =] To me, it looks like a garble of UTF-16 and the console encoding, since a file named "hö" will appear in redirected output from "dir" thus: 00 <ascii for h> 00 <console encoding code for "ö">
    – bzlm
    Sep 28, 2008 at 15:06
  • nods Sure. But ouch, with the UTF-16 representation of console codes, as opposed to Unicode code points! That's seriously wrong.... Sep 29, 2008 at 4:15
6

This will save the results as ASCII (American Standard Code for Information Interchange) on your desktop, ASCII\ANSI doesn't recognize every international or extended character:

tree /f > ascii.txt

This will convert your ASCII text to Unicode (/c must precede actual command):

cmd /u /c type ascii.txt > unicode.txt

So why not just think of the ascii file as a temporary file and delete it?

del ascii.txt

If you must put all in one line you could use:

tree /f > ascii.txt & cmd.exe /u /c type ascii.txt > unicode.txt & del ascii.txt
1
5

You can try

tree /A > output.txt

Though it looks different from the CMD line, it still could be acceptable. :P

4

The short answer is you cannot and this is because tree.com is an ANSI application, even on Windows 7.

The only solution is to write your own tree implementation. Also you could file a bug to Microsoft, but I doubt they are not already aware about it.

3

XP1's answer is great, but had a minor caveat: the output encoding is UCS2-LE, while I'd prefer UTF8 (smaller filesize, and more widespread).

After a lot of searching and head scratching, I can finally present you the following command, that produces an UTF8-BOM file:

PowerShell -Command "TREE /F | Out-File output.txt -Encoding utf8"

If the output filename has spaces:

PowerShell -Command "TREE /F | Out-File ""output file.txt"" -Encoding utf8"

Many thanks to this article: https://www.kongsli.net/2012/04/20/powershell-gotchas-redirect-to-file-encodes-in-unicode/


Also, personally I have created the following files in my PATH:

xtree.cmd:

@IF [%1]==[] @(
    ECHO You have to specify an output file.
    GOTO :EOF
)

@PowerShell -Command "TREE | Out-File %1 -Encoding utf8"

xtreef.cmd:

@IF [%1]==[] @(
    ECHO You have to specify an output file.
    GOTO :EOF
)

@PowerShell -Command "TREE /F | Out-File %1 -Encoding utf8"

Finally, instead of tree > output.txt I just do xtree output.txt

2

This worked for me:

tree /f /a > %temp%\Listing >> files.txt
1
1

I've managed to properly output non-ascii characters from tree command into a file via Take Command Console.

In TCC type "option" and on first tab select "Unicode output". Then simply run

tree /f /a > output.txt
0

I've succeeded getting the output as it is in console, with all non-ascii characters not converted, by outputting to the console (just tree) and then copying from it (system menu -> Edit -> Mark, selecting all, Enter). Console buffer size should be increased in advance, depending on number files/folders, in the console's properties (system menu -> Properties). Other ways didn't work. tree|clip, mentioned in an earlier post, converts non-ascii characters to ascii ones the same as tree>file.txt.

0

I used this method to catalog nearly 100 SDRAM and USB flashdrives and it worked fine.

From within DOS....

C:\doskey [enter] {to enable handy keyboard shortcuts}

C:\tree j:\ >> d:\MyCatalog.txt /a [enter] {j:= is my USB drive ; d:= is where I want catalog ; /a = see other postings on this page}

0

XP1's answer is great, or at least the best here—tree command just can't handle some symbols even with this treatment.

However, at least on my setup, this script will generate trees missing the final line. While I'm unsure why exactly this happens, it can be fixed by modifying function listTree to look like this:

function listTree {
    tree /f
    echo .
}

Where echo . prints a line for PowerShell to cannibalize freely. This sacrifice sates it and the tree is output in entirety.

1
0

I decided to revise my solution because I was not satisfied with the result. The solution I present to you is strikingly simple. I take the result from TREE.COM and replace the characters. This will work in ANSI or UTF8. But to make it work with accentuated letters in UTF8 when your language is not English (USA) characters, you may need to use "Beta: Use Unicode UTF-8 for worldwide language support" found in this article.

function Show-Tree {
    param (
        [string]$Path = $PWD
    )

    $tr = CMD.EXE /U /C "TREE.COM ""$Path"" /A /F"
    $tr -replace '\|','│' -replace '\+','├' -replace '-','─' -replace '\\','└'
}
Show-Tree

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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