Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question
2  
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

1 Answer 1

up vote 0 down vote accepted

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
share|improve this answer
    
and this worked like a charm too... thanks a lot! –  koma5 Sep 25 '13 at 12:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.