How to list file and folder names in powershell?

6.8k views Asked by At

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.

3

There are 3 answers

1
phuclv On BEST ANSWER

Just print the Name property of the files

$ (ls).Name >.gitignore
$ (Get-ChildItem).Name | Out-File .gitignore
0
Mathias R. Jessen On

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
1
GetSomeLemons On

Would this do?

(get-childitem -Path .\ | select name).name | Out-File .gitignore