Using Powershell to recursively output folder contents to separate .txt files

I’m attempting to use Powershell to output my folder contents to a text file recursively, sorted by LastWriteTime.

My directory structure looks like this:

ProjectData
  Proj1
    file1.txt
    file2.txt
  Proj2
    image1.jpg
    file1.txt

I’m attempting to get an output that looks like this:

Proj1.txt (contents of txt file to include file1.txt, file2.txt)
Proj2.txt (contents of txt file to include image1.jpg, file1.txt)

I’ve tried the following, which outputs the entire directory listing into a single txt file. I’m not sure it’s possible to do what I want with Powershell.

Get-ChildItem 'C:\Users\hmd\Desktop\PSTest' | Sort-Object LastWriteTime >> 'C:\Users\hmd\Desktop\PSTest\output.txt'

As well, this produces similar results:

Get-ChildItem -Recurse C:\Users\hmd\Desktop\PSTest | ForEach-Object { $_.Name } > C:\Users\hmd\PSTest\output.txt

I think what needs to happen is, in the ForEach loop, it needs to recursively look into each directly and output the txt file. I’m unclear on how to approach this and would appreciate any suggestions/tips.

>Solution :

If I’m understanding correctly you need to first look for all folders 1 level deep then get all files for each folder:

# look for all directories 1 level deep
Get-ChildItem ProjectData -Directory | ForEach-Object {
    # construct the destination path for this folder
    $dest = Join-Path 'C:\Users\hmd\Desktop\PSTest' -ChildPath "$($_.Name).txt"
    # get all files `Name` from this directory (recursively)
    ($_ | Get-ChildItem -Recurse -File | Sort-Object LastWriteTime).Name |
        # store the files in a txt file using the parent folder name
        Set-Content $dest
}

If you want all files in a single line joined by a delimiter you can use -join:

($_ | Get-ChildItem -Recurse -File | Sort-Object LastWriteTime).Name -join ','

Leave a Reply