Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list file and folder names in powershell?

I want to write all files and folders' names into a .gitignore file like the below:

Folder1
Folder2
File1.bar
File2.foo

and so on.

The writing part can be achieved with the Out-File command, but I'm stuck in printing those names like the format above.

I'm aware of the command Get-ChildItem but it prints out a bunch of metadata like dates and icons too which are useless for the matter. btw, I'm looking for a single-line command, not a script.

like image 694
Ahmad Reza Enshaee Avatar asked Aug 31 '25 16:08

Ahmad Reza Enshaee


2 Answers

Just print the Name property of the files like:

$ (ls).Name >.gitignore

or:

$ (Get-ChildItem).Name | Out-File .gitignore
like image 187
phuclv Avatar answered Sep 02 '25 13:09

phuclv


I'm aware of the command Get-ChildItem but it prints out a bunch of metadata like dates and icons [...]

That's because PowerShell cmdlets output complex objects rather than raw strings. The metadata you're seeing for a file is all attached to a FileInfo object that describes the underlying file system entry.

To get only the names, simply reference the Name property of each. For this, you can use the ForEach-Object cmdlet:

# Enumerate all the files and folders
$fileSystemItems = Get-ChildItem some\root\path -Recurse |Where-Object Name -ne .gitignore
# Grab only their names
$fileSystemNames = $fileSystemItems |ForEach-Object Name

# Write to .gitignore (beware git usually expects ascii or utf8-encoded configs)
$fileSystemNames |Out-File -LiteralPath .gitignore -Encoding ascii
like image 23
Mathias R. Jessen Avatar answered Sep 02 '25 13:09

Mathias R. Jessen