dir/b > files.txt
我想必须在PowerShell中完成以保护unicode标志。
Get-ChildItem | Select-Object -ExpandProperty Name > files.txt
或更短:
ls | % Name > files.txt
但是,您可以在cmd
中轻松完成相同的操作:
cmd /u /c "dir /b > files.txt"
/u
开关告诉cmd
将重定向到文件中的内容写为Unicode。
Get-ChildItem
实际上已经有相当于dir /b
的旗帜:
Get-ChildItem -name
(或dir -name
)
在PSH中,dir
(其中包含Get-ChildItem
)为您提供了对象(如another answer中所述),因此您需要选择所需的属性。使用Select-Object
(别名select
)创建具有原始对象属性子集的自定义对象(或者可以添加其他属性)。
然而,在这种情况下,可以在格式阶段进行它可能是最简单的
dir | ft Name -HideTableHeaders | Out-File files.txt
(ft
是format-table
。)
如果你想在files.txt
中使用不同的字符编码(out-file
默认使用UTF-16)使用-encoding
标志,你还可以追加:
dir | ft Name -HideTableHeaders | Out-File -append -encoding UTF8 files.txt
由于powershell处理对象,因此您需要指定处理管道中每个对象的方式。
此命令将仅打印每个对象的名称:
dir | ForEach-Object { $_.name }
简单的说:
dir -Name > files.txt
刚刚找到这篇精彩帖子,但也需要它用于子目录:
DIR /B /S >somefile.txt
使用:
Get-ChildItem -Recurse | Select-Object -ExpandProperty Fullname | Out-File Somefile.txt
或短版本:
ls | % fullname > somefile.txt