Tuesday, December 14, 2010

Powershell to get folder size with Get-ChildItem

Here's my script of the day. I wanted to write a Powershell script which could retrieve the files and folders size for a specified list of volumes. It was important for me to include also empty directories and zero size files, which is not so easy to get with the standard 'Get-ChildItem' method.

The script will return for each volume:
  • the name of the subfolder
  • the total size of the subfolder
  • the number of files in the subfolder (including zero size files)
  • the average file size

Here's the code.
I haven't had the time to optimize it, but it does work and does what it says it does.

Feel free to use it if you need it and to leave a comment if you want to suggest an improvement or a correction.

  1. clear-host  
  2. $volumes = "c:\","e:\","f:\","x:\" 
  3. foreach ($startFolder in $volumes){ 
  4. $colItems = (Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object) 
  5. foreach ($i in $colItems) 
  6.     { 
  7.         $subFolderItems = (Get-ChildItem $i.FullName -Recurse | Measure-Object -property length -sum) 
  8.         $count = @((Get-ChildItem $i.FullName -force -recurse  | where {$_.length -ge 0} )).Count 
  9.         if($count -eq 0)  
  10.             { 
  11.             if($subFolderItems.sum -lt 1) 
  12.                 { 
  13.                 $avgsize = 0 
  14.                 $totalsize = 0 
  15.                 } 
  16.             else 
  17.                 { 
  18.                 $avgsize = "Not possible" 
  19.                 $totalsize = "Not possible" 
  20.                 } 
  21.             } 
  22.         else 
  23.             { 
  24.             $avgsize = [math]::round($subFolderItems.sum/$count / 1MB,2) 
  25.             $totalsize = [math]::round($subFolderItems.sum / 1MB,2) 
  26.             } 
  27.         $output_final = $startFolder + ",",$i.FullName + ",",$totalsize + " MB,",$count + ",",$avgsize + " MB"  
  28.         $output_final | Out-File -Append 'folder-size-log.csv' -Encoding ASCII  
  29.     }  
  30. }  

2 comments:

  1. Nice - exactly what I was looking for and does exactly what it says!

    ReplyDelete
  2. How to get information about only directory, not volume?

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...