Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Using Measure-Object to sum file sizes in Powershell

Originally posted on: http://geekswithblogs.net/alexhildyard/archive/2017/03/15/using-measure-object-to-sum-file-sizes-in-powershell.aspx

Be aware that this line:

gci -r "C:\temp\test"  | measure-object -Property Length -sum

will throw an error if it encounters a folder whose only contents is another (empty) folder; this is because measure-object tries in this case to measure an object which does not have a “length” property defined:

PS C:\Projects> Get-ChildItem -Recurse "C:\temp\test"  | measure-object -property length -sum

measure-object : The property "length" cannot be found in the input for any objects.

At line:1 char:42

+ ... dItem -Recurse "C:\temp\test"  | measure-object -property length -sum

+                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: (:) [Measure-Object], PSArgumentException

    + FullyQualifiedErrorId : GenericMeasurePropertyNotFound,Microsoft.PowerShell.Commands.MeasureObjectCommand

 

There are various ways to achieve the correct effect, based on the idea that objects returned by gci that are directories will have the PSIsContainer property set to $true. For example:

 

$root = "c:\Oracle"

 

$total_files = 0

$total_size = [int]0

 

[System.Collections.Stack]$stack = @()

$stack.Push($root)

 

while ($stack.Length -gt 0)

{

    $folder = $stack.Pop()

 

    gci $folder |% `

    {

        $item = $_

       

        if ($item.PSIsContainer)

        {

            $stack.Push($item.FullName)

        }

        else

        {

             $total_size += $_.Length

             $total_files ++

 

        }

     }

}

 

Write-Host "Total size: $([Math]::Round($total_size / 1Mb, 2)) Mb over $total_files files"



This post first appeared on , please read the originial post: here

Share the post

Using Measure-Object to sum file sizes in Powershell

×

Subscribe to

Get updates delivered right to your inbox!

Thank you for your subscription

×