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 = @()
while ($stack.Length -gt 0)
$folder = $stack.Pop()
gci $folder |% `
$item = $_
$total_size += $_.Length
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