Need help with below code - recurse and count

The folder count is incorrect. In a given directory I want the name of the folder, the folder count, the individual file count in each folder, and the size of the folder. The folder count in each main folder is not rendering correctly. Thanks

$location = Read-Host “Enter Top Level File Path”
$folders = Get-ChildItem -Path $location -Recurse -Directory

$array = @()

foreach ($folder in $folders)
{
$foldername = $folder.FullName

Find files in sub-folders

$files = Get-ChildItem $foldername -Attributes !Directory

Count Folders

$folderCount = Get-ChildItem -Directory

Calculate size in MB for files

$size = $Null
$files | ForEach-Object -Process {
$size += $_.Length
}

$sizeinmb = [math]::Round(($size / 1mb), 1)

Add pscustomobjects to array

$array += [pscustomobject]@{
Folder = $foldername
FolderCount =$folderCount.count
Count = $files.count
‘Size(MB)’ = $sizeinmb
}
}

Generate Report Results in your Documents Folder

$array|Export-Csv -Path C:\file_report.txt

Hi Andrew, welcome to the forum :wave:

Firstly, when posting code in the forum, please can you use the preformatted text </> button. It really helps us with readability, and copying and pasting your code (we don’t have to faff about replacing curly quote marks to get things working).

On the face of it, your code seems OK. This:

$folderCount = Get-ChildItem -Directory
FolderCount  = $folderCount.count

Returns the expected number of folders for me. Please clarify what you mean by:

The folder count in each main folder is not rendering correctly.

If you look in the properties of a given folder there is a list that details the type, location, size, etc. I want teh script to go in each folder and tell me how many the number of files, and folders.


Thanks

I think you’re overcomplicating this task. Actually there are thousands of examples out there. So you do not need to re-invent the wheel again. :wink:

For a given folder this should be enough:

$StartFolder = 'D:\sample\test'

$FilesAndFolders = Get-ChildItem  -Path $StartFolder -Recurse -Force 

[PSCustomObject]@{
    Name = $StartFolder
    SubfolderCount = ($FilesAndFolders | Where-Object -Property Mode -Match -Value '^d').count 
    FileCount      = ($FilesAndFolders | Where-Object -Property Mode -NotMatch -Value '^d' ).Count 
    TotalSize      = ($FilesAndFolders | Where-Object -Property Mode -NotMatch -Value '^d' | Measure-Object -Property Length -Sum).Sum
}

Thanks but this is not my desired output. I need for the script to tell me the number of folders, individual files, as well as the size of each folder in EACH of the folders within the topmost folder. I hope you understand.
Thanks

I do understand. :wink: My code suggestion is not meant to be a complete solution. It’s meant to be food for thought for you to have an idea how to tackle this task. :wink:

Either you create a recursive function or you use a loop over all subfolders of your root folder. :+1:t4: