GTS*_*Joe 5 windows powershell command-prompt
使用 Windows 命令提示符或 Windows PowerShell,如何将单个目录中的所有文件名输出到文本文件,而不带文件扩展名?
在命令提示符中,我使用的是:
dir /b > files.txt
Run Code Online (Sandbox Code Playgroud)
01 - Prologue.mp3
02 - Title.mp3
03 - End.mp3
files.txt
Run Code Online (Sandbox Code Playgroud)
01 - Prologue
02 - Title
03 - End
Run Code Online (Sandbox Code Playgroud)
请注意,“dir /b > files.txt”命令包含文件扩展名并将文件名放在底部。
在不使用批处理文件的情况下,是否有一个干净的命令提示符或 PowerShell 命令可以完成我正在寻找的任务?
在 PowerShell 中:
# Get-ChildItem (gci) is PowerShell's dir equivalent.
# -File limits the output to files.
# .BaseName extracts the file names without extension.
(Get-ChildItem -File).BaseName | Out-File files.txt
Run Code Online (Sandbox Code Playgroud)
注意:您dir也可以在 PowerShell 中使用,它只是Get-ChildItem. 但是,为了避免与具有根本不同语法cmd.exe的内部dir命令混淆,最好使用 PowerShell 本机别名gci。要查看为 定义的所有别名Get-ChildItem,请运行Get-Alias -Definition Get-ChildItem
请注意,使用 PowerShell 的>重定向运算符(实际上是 cmdlet 的别名)也会导致在枚举中Out-File意外包含输出 ,如和 POSIX 类 shell 中的情况,因为首先创建目标文件。files.txtcmd.exebash
相比之下,使用带有Out-File(或Set-Content,用于文本输入) 的管道会延迟文件创建,直到初始化此单独管道段中的 cmdlet [1] - 并且因为第一个段中的文件枚举根据定义已在此时完成,由于Get-ChildItem调用包含在 中(...),因此输出文件不包含在枚举中。
另请注意,属性访问.BaseName应用于 所返回的所有(Get-ChildItem ...)文件,这会方便地导致返回单个文件的属性值数组,这要归功于名为成员访问枚举的功能。
字符编码说明:
在 Windows PowerShell 中,Out-File/>创建“Unicode”(UTF-16LE) 文件,而Set-Content使用系统的旧版 ANSI 代码页。
在 PowerShell (Core) 7+ 中,无 BOM UTF-8 是一致的默认值。
该-Encoding参数可用于显式控制编码。
[1] 在 的情况下Set-Content,它实际上会进一步延迟,即直到收到第一个输入对象为止,但这是不应该依赖的实现细节。
| 归档时间: |
|
| 查看次数: |
13172 次 |
| 最近记录: |