Public/Get-FolderSize.ps1

<#
.SYNOPSIS
    Calculates the total size of files within a specified directory and its subdirectories.
 
.DESCRIPTION
    The Get-FolderSize function computes the total size of all files within a given directory
    and formats the output based on the size (bytes, KB, MB, GB, or TB).
 
.PARAMETER Share
    Specifies the directory path whose total size is to be calculated. This parameter is mandatory.
 
.EXAMPLE
    PS> Get-FolderSize -Share "C:\Users\Public\Documents"
    This example calculates and displays the size of files in the "Documents" directory under "Public".
 
.OUTPUTS
    String
    Outputs the total size of the directory formatted as a string (e.g., "2.34 GB").
 
.NOTES
    This function handles large directories by skipping inaccessible files and folders.
#>


function Get-FolderSize
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$Share
    )

    process
    {
        # Calculate the total size of all files in the directory, including subdirectories.
        $folderSize = Get-ChildItem -Path $Share -Recurse -Force -ErrorAction SilentlyContinue |
                      Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue

        # Format the output based on the size of the folder
        if ($folderSize.Sum -gt 1TB) {
            [string]::Format("{0:0.00} TB", $folderSize.Sum / 1TB)
        } elseif ($folderSize.Sum -gt 1GB) {
            [string]::Format("{0:0.00} GB", $folderSize.Sum / 1GB)
        } elseif ($folderSize.Sum -gt 1MB) {
            [string]::Format("{0:0.00} MB", $folderSize.Sum / 1MB)
        } elseif ($folderSize.Sum -gt 1KB) {
            [string]::Format("{0:0.00} kB", $folderSize.Sum / 1KB)
        } elseif ($folderSize.Sum -gt 0) {
            [string]::Format("{0:0.00} B", $folderSize.Sum)
        } else {
            "0 B"
        }
    }
}