1

I have an array of folders, called $FolderArray. It contains about 40 folders. Inside each folder are a bunch of txt files. I want to loop through each folder to get the number of files in each folder, as well as the total size of each folder. I got the number of files in each folder to work, but for the folder size, it ends up outputting the file size of the last file in each folder.

I pulled this out of a larger snippet of my code, so if anything needs more clarification please let me know. I appreciate the help!

$ProcessedLocation = "C:\Users\User.Name\Documents"
$FolderArray = gci -Path $ProcessedLocation | Where-Object {$_.PSIsContainer} | Foreach-Object {$_.Name}

Foreach ($i in $FolderArray) 
{
    $FolderLocation = $ProcessedLocation + $i
    [int]$FilesInFolder = 0
    Get-ChildItem -Path $FolderLocation -Recurse -Include '*.txt' | % {
        $FilesInFolder = $FilesInFolder + 1
        $Length = $_.Length
        $FolderSize = $FolderSize + $Length
    }

    Write-Host $FolderSize

}
2
  • You loop over $FolderArray twice. Is $FolderArray an array of strings or objects (maybe show us how you populate/assign it in the first place)? Commented Jan 28, 2016 at 19:58
  • @MathiasR.Jessen I edited it to give more context. Commented Jan 28, 2016 at 20:08

1 Answer 1

2

You are iterating over $FolderArray twice, once in the foreach($i in $FolderArray) loop, and then again inside the loop body:

foreach($i in $FolderArray){
    Get-ChildItem $FolderArray # don't do this
}

If you want to look into each folder in $FolderArray individually, reference the current variable (in your example that would be $i).

I would recommend saving the output from Get-ChildItem to a variable and then grab the size and count of the files from that:

# keep folders as DirectoryInfo objects rather than strings
$FolderArray = Get-ChildItem -Path $ProcessedLocation 

foreach ($Folder in $FolderArray) 
{
    # retrieve all *.txt files in $Folder
    $TxtFiles = Get-ChildItem -Path $Folder -Recurse -Include '*.txt'

    # get the file count
    $FilesInFolder = $TxtFiles.Count

    # calculate folder size
    $FolderSize = ($TxtFiles | Measure -Sum Length).Sum

    # write folder size to host
    $FolderSizeMB = $FolderSize / 1MB
    Write-Host "$Folder is $FolderSizeMB MB in size"
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.