Question:
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:
1 2 3 4 5 6 7 8 |
-X |+Dir1 |+Dir2 |+Dir3 | ... |+Dir500 |
What I want to get piped to a txt file is this
1 2 3 4 5 6 |
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,
Answer:
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:
1 2 |
Get-ChildItem "X:\" -directory | Select FullName | Export-Csv "DirectoriesInX.csv" -NoTypeInformation |
PowerShell v2 and below:
1 2 |
Get-ChildItem "X:\" | Where{$_.PSIsContainer} | Select FullName | Export-Csv "DirectoriesInX.csv" -NoTypeInformation |