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 )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.
{
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 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:
Post a Comment