Reputation: 115
I'm having issues with this snippet of code to find the folders in a directory and list with sizes but I keep running into a error
$Directory = Read-Host "Enter your directory"
$colItems = (Get-ChildItem $Directory | {$_.Attributes -match 'Directory'} |Measure-Object -Property Length -Sum )
After adding bit after | to show the sizes I started getting errors.
Upvotes: 1
Views: 372
Reputation: 1475
You can use the Scripting.FileSystemObject COM object for simplicity.
$Directory = Read-Host "Enter your directory"
$fso = New-Object -ComObject Scripting.FileSystemObject
Get-ChildItem -Path $Directory | ? { $_.PSIsContainer } | % { $fso.GetFolder($_.FullName).size/1kb }
Upvotes: 1
Reputation: 874
Try this
$Folders = Get-ChildItem $Directory | Where-Object {$_.Attributes -eq 'Directory'}
foreach ($Folder in $Folders)
{
$FolderSize = Get-ChildItem $Folder.Fullname -recurse | Measure-Object -property length -sum
$Folder.FullName + " -- " + "{0:N2}" -f ($FolderSize.sum / 1MB) + " MB"
}
-Recurse Parameter makes sure that apart from getting System.IO.DirectoryInfo
you are also getting System.IO.FileInfo
objects which contain Length property.
I would also suggest that instead using
$Folders = Get-ChildItem $Directory | Where-Object {$_.Attributes -eq 'Directory'}
You can use:
$Folders = Get-ChildItem $Directory | Where-Object {$_.PSIsContainer -eq $True}
This property will be available for other providers (registry, cert store, etc.) as well.
Upvotes: 0
Reputation: 29450
Directory objects (objects of type DirectoryInfo
) don't have a length property, which is why you are getting errors. In order to get the space taken up by directories in powershell you'll have to recursively search through all the subdirectories and adding up the length of all the files that they contain. Fortunately there are several sources available to show you how to do this. Here's one.
Upvotes: 1