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.