Reputation: 53263
I want to get all the names in a directory as a comma separated string so that I can pass them as a parameter to a cmdlet.
How can I get all the file names in a directory as a comma separated string in Powershell?
Upvotes: 6
Views: 6675
Reputation: 6884
For those who may be more comfortable with the classic Windows dir
, here's a variant of Eddie's answer (which used the *nix-like ls
, which of course ps also supports):
(dir -name) -join ','
This would produce the exact same result as his ls
example. (To be clear, this would work ONLY in powershell--as requested in the question here--but not in the Windows Command line.)
And if you wanted to remove folder names from the results (in either his or my example), add the -file switch: (dir -file -name) -join ','
or (ls -file).name -join ','
.
And of course you could follow the dir
(or ls
) with a pattern of files to be found, or a folder in which to look. These examples are simply getting ALL files in the current folder. To find all filename of exe's starting j, this would work:
(dir j*.exe -file -name) -join ','
Or to name a path as well, note that if the folder has spaces you must quote the path, as in:
(dir "C:\Program Files\Java\jdk-17\bin\j*.exe" -file -name) -join ','
FWIW, this dir
in powershell is an alias of Get-ChildItem
, and using help dir
will show its many other args/switches.
Upvotes: 0
Reputation: 1490
Quickest/shortest way:
(ls).name -join ','
For specific folder-path:
(ls path\to\folder).name -join ','
Upvotes: 4
Reputation: 37750
This should work:
(ls C:\PATH\TO\FOLDER | select -expandproperty name) -join ','
If there are subfolders in there that you want to avoid:
(ls C:\PATH\TO\FOLDER | ?{$_.PSIsContainer -eq $false} | select -expandproperty name) -join ','
Upvotes: 2