Monday, June 9, 2008

PowerShell Script to Compute Folder Sizes

I would like to preface this post with a disclaimer. While I have a few languages under my belt, I'm fairly new to PowerShell. Most of my posts on this topic will simply be scripts that I've created or modified for my own purposes. Feel free to use any of them for whatever purpose you choose.

I created this function as part of a larger script I'm writing that archives old users in Active Directory. I needed a way to report the profile size of the archived user and flag large profiles for closer inspection to save on disk space. This code is a modified version of a script I found on Z@RAYS. I'll talk more about the specific changes I made a bit later.

function folderSize ( [string] $folderPath )
{
if($folderPath)
{
#Initialize everything
$totalSize = 0
$folderRoot = Get-ChildItem $folderPath

#Total the subfolder sizes
foreach($folder in $folderRoot)
{
if($folder.mode -match "d")
{
#Retrieve the folder size and add it to the running total
$fsz=((Get-ChildItem $folder.fullname -Recurse -Force | Measure-Object length -sum).sum)
$totalSize = $totalSize + $fsz
}
}

#Add the size of items in the folder root
$filesize=(($folderRoot.fullname | Measure-Object length -Sum).sum)

#Convert to GB and format to 2 decimal places
$totalSize = ($totalSize + $filesize)/1GB
$totalSize = "{0:N2}" -f $totalSize
return $totalSize
}
}
The first section of code initializes our running total to zero and creates an object representing the root folder who's size we want. The second section recurses through each sub folder and adds the size of that sub folder to our running total. Now that we've got the sub folder size, the next section adds the size of any files that happen to be stored in our folder's root. The last section converts the total size to GB and truncates the result to two decimal places before returning the total size.

The primary change I made from the code found on Z@RAYS is in the rounding of our folder size. The original code formatted each sub folder's size into GB with two decimal places before adding it to the total. I found that in situations with large numbers of sub folders, this could introduce a significant rounding error. Saving the formatting for last eliminated that problem. I also wanted my result in GB instead of MB, but this code can easily be modified to return the result in any unit you choose.

No comments: