'Output Filenames in a Folder to a Text File

Using Windows Command Prompt or Windows PowerShell, how can I output all the file names in a single directory to a text file, without the file extension?

In Command Prompt, I was using:

dir /b > files.txt

Result

01 - Prologue.mp3
02 - Title.mp3
03 - End.mp3
files.txt

Desired Output

01 - Prologue
02 - Title
03 - End

Notice the "dir /b > files.txt" command includes the file extension and puts the filename at the bottom.

Without using a batch file, is there a clean Command Prompt or PowerShell command that can do what I'm looking for?



Solution 1:[1]

In 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

Note: You can use dir in PowerShell too, where it is simply an alias of Get-ChildItem. However, to avoid confusion with cmd.exe's internal dir command, which has fundamentally different syntax, it's better to use the PowerShell-native alias, gci. To see all aliases defined for Get-ChildItem, run
Get-Alias -Definition Get-ChildItem

Note that use of PowerShell's > redirection operator - which is effectively an alias of the
Out-File cmdlet - would also result in the undesired inclusion of the output, files.txt, in the enumeration, as in cmd.exe and POSIX-like shells such as bash, because the target file is created first.

By contrast, use of a pipeline with Out-File (or Set-Content, for text input) delays file creation until the cmdlet in this separate pipeline segment is initialized[1] - and because the file enumeration in the first segment has by definition already completed by that point, due to the Get-ChildItem call being enclosed in (...), the output file is not included in the enumeration.

Also note that property access .BaseName was applied to all files returned by (Get-ChildItem ...), which conveniently resulted in an array of the individual files' property values being returned, thanks to a feature called member-access enumeration.

Character-encoding note:

  • In Windows PowerShell, Out-File / > creates "Unicode" (UTF-16LE) files, whereas Set-Content uses the system's legacy ANSI code page.

  • In PowerShell (Core) 7+, BOM-less UTF-8 is the consistent default.

The -Encoding parameter can be used to control the encoding explicitly.


[1] In the case of Set-Content, it is actually delayed even further, namely until the first input object is received, but that is an implementation detail that shouldn't be relied on.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1