I ve got a script which get each folder and get name,filescount,size of each folder.
Size with measure-object doesn t work.
My first try using my own object to handle this([pscustomobject]).
May I integrate a command (measure-object) in an object ?
Get-ChildItem d:\ -Directory -Recurse -Depth 2 -ErrorAction SilentlyContinue|
ForEach-Object{
[pscustomobject]@{
FullName = $_.Fullname
FileCount = $_.GetFiles().Count
size=measure-object -sum -property length
}
} | sort -Property filecount -Descending
Thks ,)
CodePudding user response:
Unfortunately folders don't actually have a size (Windows is just kind enough to find out for us when we check the properties of it)
So in your script you need to get all child items of the current iterations folder and measure their combined size.
Get-ChildItem d:\ -Directory -Recurse -Depth 2 -ErrorAction SilentlyContinue |
ForEach-Object {
[pscustomobject]@{
FullName = $_.Fullname
FileCount = $_.GetFiles().Count
size = (Get-Childitem -Path $_.Fullname -recurse | measure-object -property length -sum).sum
}
} | sort -Property filecount -Descending
CodePudding user response:
You will be using the result from .GetFiles()
twice, first for getting the total file count and the second time to get the sum of the file's Length
, hence I would advise you to store the result of that method call in a variable for further manipulation.
To get the folder size, you can either use Enumerable.Sum
:
Get-ChildItem D:\ -Directory -Recurse -Depth 2 -ErrorAction SilentlyContinue | & {
process {
$files = $_.GetFiles()
[pscustomobject]@{
FullName = $_.FullName
FileCount = $files.Count
Size = [Linq.Enumerable]::Sum([int64[]] $files.ForEach('Length'))
}
}
} | Sort-Object -Property Filecount -Descending
Or, if you want to use Measure-Object
, the Size
property would be:
Size = ($files | Measure-Object Length -Sum).Sum
Lastly, if you want to do a recursive search per folder, you can target the .GetFiles(String, SearchOption)
overload using AllDirectories
for SearchOption Enum:
$files = $_.GetFiles('*', [IO.SearchOption]::AllDirectories)