Search code examples
powershellexportget-childitem

Exporting directory file names


I'm trying to create a script which prompts for a path which is to be exported onto a .csv which displays the names of the folders and the named of the contents of the folders. Something like this, but without the Mode & Length.

I would like to keep the gaps between each folder.

Example - (Without the Mode/Length)

Directory: C:\Users\khalifam\Desktop\TestFolder1


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       24/07/2019     15:50                TestFolder2
d-----       24/07/2019     15:50                TestFolder3


    Directory: C:\Users\khalifam\Desktop\TestFolder1\TestFolder2


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       30/05/2019     11:05           1696 EC2Key1.pem


    Directory: C:\Users\khalifam\Desktop\TestFolder1\TestFolder3


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       31/05/2019     16:16          22027 Dropbox-f

My script so far:

$FilePathLocation = Read-Host -Prompt 'Please enter the the path of the fold you wish to export'

Set-Location $FilePathLocation

gci -Recurse | select DirectoryName, FullName | FT

Current output:

Please enter the the path of the fold you wish to export: C:\Users\khalifam\Desktop\TestFolder1

DirectoryName                                     FullName                                                                            Root
-------------                                     --------                                                                            ----
                                                  C:\Users\khalifam\Desktop\TestFolder1\TestFolder2                                   C:\
                                                  C:\Users\khalifam\Desktop\TestFolder1\TestFolder3                                   C:\
C:\Users\khalifam\Desktop\TestFolder1\TestFolder2 C:\Users\khalifam\Desktop\TestFolder1\TestFolder2\EC2Key1.pem
C:\Users\khalifam\Desktop\TestFolder1\TestFolder3 C:\Users\khalifam\Desktop\TestFolder1\TestFolder3\Dropbox-CCEN-Course.docx

Solution

  • Enumerate directories recursively first, then process the content of each directory without recursion. Note that the output generated by this is NOT an actual CSV.

    Get-ChildItem $FilePathLocation -Directory -Recurse | ForEach-Object {
        "{0}`n" -f $_.FullName
        Get-ChildItem $_.FullName |
            Select-Object Name, LastWriteTime |
            Format-Table |
            Out-String
    } | Set-Content 'output.txt'
    

    Also note that this requires PowerShell v3 or newer. If you're stuck with an older version you need to remove the parameter -Directory and use a Where-Object filter instead.