4

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.

1
  • 3
    the fileinfo object that you get from that cmdlet has a .Name property that holds just the name of the file. also, the -Name parameter of that cmdlet will return JUST the name of the file. Commented May 3, 2022 at 10:19

3 Answers 3

10

Just print the Name property of the files like:

$ (ls).Name >.gitignore

or:

$ (Get-ChildItem).Name | Out-File .gitignore
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Both commands will do the job. Please separate them and add $ at the beginning of them so they can be more obvious.
1

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

Comments

1

Would this do?

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

1 Comment

select name then ().name is completely redundant

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.