pixel
pixel

Reputation: 10557

Get Directories Names Only

I have a directoy X that has say 500 subdirectories. What I need is a quick way to just get only my directory and the names of these 500 subdirectories in my X directory (so, no Mode, no LastWriteTime or anything else, just the name) and pipe it to a file.

So, for example, I have this:

-X
 |+Dir1
 |+Dir2
 |+Dir3
 |
 ...
 |+Dir500

What I want to get piped to a txt file is this

X/Dir1
X/Dir2
X/Dir3
...
X/Dir500

How can I do this using PowerShell or CommandLine? I am using Windows 7 and PowerShell 4.0 Thanks,

Upvotes: 7

Views: 37602

Answers (2)

Nate
Nate

Reputation: 862

Get-ChildItem will do the same thing as dir in command-line: it gets whatever is in your directory. You're looking only for directories. PS v3 and up has this built-in by using the flag of -directory. In older PowerShell versions, you can pipe your Get-ChildItem to a Where{$_.PSIsContainer to get directories and then pipe that to select Name to just get the names of the directories, not their full paths (e.g. "Dir1" vs. "X:\Dir1"). If you want the full path, use select FullName. Assuming you want that as a CSV, pipe that to Export-Csv followed by the name of the CSV you're creating, such as DirectoriesInX.csv and if you don't want the type information, add the flag of -NoTypeInformation.

PowerShell v3 and up:

Get-ChildItem "X:\" -directory | Select FullName | Export-Csv "DirectoriesInX.csv" -NoTypeInformation

PowerShell v2 and below:

Get-ChildItem "X:\" | Where{$_.PSIsContainer} | Select FullName | Export-Csv "DirectoriesInX.csv" -NoTypeInformation

Upvotes: 14

sodawillow
sodawillow

Reputation: 13176

I would have not used -Recurse based on requirement.

Moreover, OP wants to pipe output to a file :

(Get-ChildItem "X" -Directory).FullName | Out-File c:\myList.txt

The -Directory switch is only available from PS3.

The -Recurse switch would go as deep as possible in the tree and list all folders

Upvotes: 4

Related Questions