# adding file size of two or more files in powershell

Why is the following snippet only adding the byte-size of the last file to 0 and not the size of all files matching?

$sizeOfVhds = 0 (Get-Item "\\blahhh.com\foo\bar\*.vhd") | ForEach-Object {$sizeOfVhds = $sizeOfVhds +$_.length
}


I'm trying to sum the size of two or more vhd files in a given directory. I'm not trying to calculate the human readable size.

-
I'm not very experienced with PS, but get-item will only get a single object. Don't you want get-childitem since you want an array with all VHDs? –  nixda Sep 23 '13 at 10:49
@nixda does have at least part of your problem. Combine it with measure item –  AthomSfere Sep 23 '13 at 16:28
hard to believe ... but a reboot solved my Problem. The above code and the solution of @nixda worked perfectly. –  koma5 Sep 25 '13 at 12:15

There's an easier way to do this using the measure-object cmdlet. Here's an example where you can assume $Files contains a collection of FileInfo objects. PS C:\>$Files | measure-object -Property length -sum

Count    : 61
Average  :
Sum      : 167476924
Maximum  :
Minimum  :
Property : Length


Here's an example using the input you provided that extracts the sum in a single statement:

PS C:\> $sum = ((Get-ChildItem "\\blahhh.com\foo\bar\*.vhd") | Measure-Object -Property length -sum) | Select-Object -ExpandProperty Sum PS C:\>$sum
Sum of the value of 'length' for each object in collection outputted here

-
and this worked like a charm too... thanks a lot! –  koma5 Sep 25 '13 at 12:15