How to total Kbytes of several files
I'm looping through a directory full of files and need to get the grand total of all the files in a directory. However I'm getting a conversion problem due to the way I fetch/calculate the kilobytes.
Here is my code:
$dest开发者_开发知识库inationDir = "\\server\folder"
$filename = "FILE_1234567.xls"
$filesize = 0
$totalfilesize = 0
$filesize = Get-ChildItem ($destinationDir + "\" + $filename) | Select-Object @{Name="Kbytes";Expression={"{0:N0}" -f ($_.Length / 1Kb)}}
$totalfilesize += [int]($filesize)
Write-Host $filesize
Write-Host $totalfilesize
However when I run this I get the following error message:
Cannot convert the "@{Kbytes=93}" value of type "Selected.System.IO.FileInfo" to type "System.Int32".
At C:\Sample.ps1:7 char:18
+ $totalfilesize += <<<< $filesize
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
I'm pretty new to Powershell but it seems like I cannot cast $filesize
to an integer for totaling. Can anyone help with where I've gone wrong?
Direct answer:
Ok, first I'll just answer your question about why your code is getting that error. Basically, Select-Object
is returning an object which has a KBytes property - that object is what you're trying to add to $totalfilesize
. There are two ways around this:
One option is to use a foreach to emit the value that you want.
$filesize = Get-ChildItem ($destinationDir + "\" + $filename) | ForEach-Object { $_.Length / 1kb }
Try this, and you'll see the result is an int, because it's only returning $_.Length, which is an int.
Alternatvely, you could add the .KBytes property instead of adding the result of Select-Object:
$totalfilesize += [int]($filesize.KBytes)
Caveat
Are you planning to iterate over multiple files? If so, then you may run into issues because in that case you'll get an array back. You can avoid that by moving the addition into a loop based on the get-childitem results:
$destinationDir = "$pshome"
$filename = "*"
$totalfilesize = 0
$filesize = Get-ChildItem ($destinationDir + "\" + $filename) | ForEach-Object { $totalfilesize += $_.Length / 1kb }
Write-Host $totalfilesize
Finally, there's the Measure-Object cmdlet which does stuff like this for free:
[int]((Get-ChildItem $PSHOME | Measure-Object -Sum Length).Sum / 1kb)
Hope that helps
精彩评论