Tuesday 2 August 2011

Powershell Folder Size

Powershell Folder Size

Script purpose
Calculate the size in bytes of a folder.

Script notes
I have some scripts that move folders from one drive to another or one pc to another. I use this to log size of folders that I move, before and after the move is completed.
The second script displays the bytes in a more user/log friendly manner.

function Get-FolderSize([string]$FolderPath) {
<#
    .Synopsis
        gets the folder size recursive
    .Example
        [long]$result = Get-FolderSize "C:\temp"
    .Parameter Source
    .Link
        http://heazlewood.blogspot.com/
#>
    [long]$FolderLength = (Get-ChildItem -LiteralPath $FolderPath -Recurse | Measure-Object -Property Length -Sum).Sum
    return $FolderLength 
}

#
function Get-BytesasString([long]$Bytes) {
<#
    .Synopsis
        Displays the bytes in a pretty way
    .Link
        http://heazlewood.blogspot.com/
#>
    if ($Bytes -gt 1073741823)
    {
        [Decimal]$size = $Bytes / 1073741824
        return "{0:##.##} GB" -f $size 
    }
    elseif ($Bytes -gt 1048575)
    {
        [Decimal]$size = $Bytes / 1048576
        return "{0:##.##} MB" -f $size
    }
    elseif ($Bytes  -gt 1023)
    {
        [Decimal]$size  = $Bytes / 1024
        return "{0:##.##} KB" -f $size
    }
    elseif ($Bytes -gt 0)
    {
        [Decimal]$size = $Bytes
        return "{0:##.##} bytes" -f $size
    }
    else
    {
        return "0 bytes";
    }
}

No comments:

Post a Comment