Powershell - how to add number of files along size of the folder that contains the files, recursively

Solution 1:

In general, I would suggest to always go into loops with all properties, and do the logic of your code in the loop. Also, save the return you get from a command into a variable, to be able to do multiple operations with it, e.g get the size and also the count.

Also, the formatting of your code was really not nice. Try to format it always in a readable way, you will thank yourself when you write complex stuff and need to edit something in there a year later.

# Get Top-Level Directories recursive and loop
Get-ChildItem -path "C:\install" -Directory -Recurse | ForEach-Object {

    # Get Sub files & folders and calculate stuff that is needed
    $SubFiles = Get-ChildItem -path $_.FullName -Force -Recurse
    $Size = ($SubFiles | Measure-Object -Property Length -Sum -ErrorAction 0).Sum/1kb
    $FileCount = $SubFiles.count

    # Return the output in the format you want to
    [PSCustomObject]@{
        "Name" = $_.FullName
        "Count" = $FileCount
        "Size(KB)" = "{0:N2}" -f $Size
    }
}

btw. if one of your folders has multiple sub folders, it will scan that directory multiple times, for each sub folder - which doesn't make sense to me. Maybe you wanted only the size and count of the top level folders? if so, remove -recurse in the first line of code.