Saving 'tree /f /a" results to a textfile with unicode support

前端 未结 12 1731
清歌不尽
清歌不尽 2021-02-02 07:10

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 st

12条回答
  •  醉酒成梦
    2021-02-02 07:54

    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

提交回复
热议问题