Forum Discussion
Abdullah_Shurjeel
Dec 03, 2020Copper Contributor
Powershell - Retrieve folder size for each folders in the output (Length Property).
My requirement is to retrieve all files from a directory when provided as an input to a certain folder level with the following properties: Name, FullName, Length, LastWriteTime. Current code: ...
- Dec 17, 2020
Abdullah_Shurjeel It looks like Measure-Object Windows PowerShell is behaving slightly differently to PSCore. I've changed the $Length= .... line to the following which appears to be working as expected.
$Length= (Get-ChildItem $FileOrFolder.FullName -Recurse | Where-Object {$_.Attributes -notcontains "Directory"} | Measure-Object -Sum -Property Length).Sum
ChrisBradshaw
Dec 16, 2020Iron Contributor
Abdullah_Shurjeel how about this:
$Directory = 'Input'
#Collect a list of all the files and folders
$FilesAndFolders =Get-ChildItem -Path $Directory -Recurse -Depth 2
#Loop through the files and folders
Foreach ($FileOrFolder in $FilesAndFolders) {
if ($FileOrFolder.Attributes -contains "Directory") {
#This is a folder - calculate the total folder size
$Length= (Get-ChildItem $FileOrFolder -Recurse | Measure-Object -Sum Length).Sum
$FileOrFolder | Select-Object Name, FullName, @{Name="Length"; Expression={$Length}}, LastWriteTime
} else {
#This is a file
$FileOrFolder | Select-Object Name, FullName, Length, LastWriteTime
}
}
Abdullah_Shurjeel
Dec 17, 2020Copper Contributor
I am getting the below error:
Measure-Object : The property "Length" cannot be found in the input for any objects.
At line:8 char:58
+ ... et-ChildItem $FileOrFolder -Recurse | Measure-Object -Sum Length).Sum
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Measure-Object], PSArgumentException
+ FullyQualifiedErrorId : GenericMeasurePropertyNotFound,Microsoft.PowerShell.Commands.MeasureObjectCommand
- ChrisBradshawDec 17, 2020Iron Contributor
Abdullah_Shurjeel It looks like Measure-Object Windows PowerShell is behaving slightly differently to PSCore. I've changed the $Length= .... line to the following which appears to be working as expected.
$Length= (Get-ChildItem $FileOrFolder.FullName -Recurse | Where-Object {$_.Attributes -notcontains "Directory"} | Measure-Object -Sum -Property Length).Sum
- Abdullah_ShurjeelMar 04, 2021Copper ContributorThanks Chris for the response.
The code is working now.