Home > OS >  How to list file and folder names in powershell?
How to list file and folder names in powershell?

Time:05-04

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.

CodePudding user response:

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

CodePudding user response:

Just print the Name property of the files

(ls).Name >.gitignore
(Get-ChildItem).Name | Out-File .gitignore

CodePudding user response:

Would this do?

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