powershellget-childitemforeach-object

Create file list in every subfolder using PowerShell


I'm very new to PowerShell and have basically zero knowledge about PowerShell scripting, which is why I need some help.

I have folder structure with subfolders (as shown below) for which I want to generate a filelist.txt in every 1st level subfolder using Get-ChildItem -Recurse.

Main Folder  
├───Sub 1
│   │   file.ext
│   └───Sub A
│           file.ext   
└───Sub 2 
|   |   file.ext
|   └───Sub B
└─── etc.

So far, I experimented with some code I found online but either I'm getting errors or absolutely nothing happens. This is the closest thing to what I want, as it creates filelist.txt files in the correct directories, but unfortunately those files are empty. In addition, a filelist.txt is created in the main folder which I don't want.

Get-ChildItem -Recurse -Directory | 
    ForEach-Object {
        New-Item -ItemType file -Path "$($_.FullName)" -Name "filelist.txt"
        Get-ChildItem $_ -Recurse > filelist.txt
    } 

Any help or suggestions are very appreciated!


Solution

  • If you're looking for the immediate sub-folders of Main Folder you shouldn't use -Recurse on your first call to Get-ChildItem -Directory as that would give you all sub-folders recursively as zett42 pointed out in his helpful comment.

    Regarding your export line:

    Get-ChildItem $_ -Recurse > filelist.txt
    

    It would place the filelist.txt file on your current location not on the subfolders, it would also replace the file per loop iteration.

    The code would look like this if I understood correctly what you were looking for:

    Get-ChildItem 'path\to\Main Folder' -Directory | ForEach-Object {
        $destination = Join-Path $_.FullName -ChildPath filelist.txt
        Get-ChildItem -LiteralPath $_.FullName -Recurse |
            Set-Content $destination
    }
    

    Worth noting that this would only export the absolute paths of the files and folders under each sub-folder of Main Folder, however it might be worth changing the export type to CSV to have the properties of each object as you see them on your console:

        $destination = Join-Path $_.FullName -ChildPath filelist.csv
        Get-ChildItem -LiteralPath $_.FullName -Recurse |
            Export-Csv $destination -NoTypeInformation