Get-ItemSize.ps1

<#PSScriptInfo
 
.VERSION 1.0.1
 
.GUID 8631301f-cf6a-4b3c-abbb-5043fd3a2a83
 
.AUTHOR Kalichuza
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS File, Folder, Size, Get-Size, Get-ItemSize
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
.PRIVATEDATA
 
#>


<#
 
.DESCRIPTION
 Gets the size of a file or folder
 
#>
 

param (
    [Parameter(Mandatory = $true)]
    [string]$Path,

    [ValidateSet("File", "Folder")]
    [string]$Type
)

function Get-SizeInfo {
    param (
        [string]$Path,
        [string]$Type
    )

    if (-Not (Test-Path $Path)) {
        Write-Host "Error: Path not found!" -ForegroundColor Red
        return
    }

    $item = Get-Item -Path $Path -Force

    if ($Type -eq "Folder" -or $item.PSIsContainer) {
        # If it's a folder, calculate the total size of its contents
        $size = (Get-ChildItem -Path $item.FullName -Recurse -File | Measure-Object -Property Length -Sum).Sum
    }
    elseif ($Type -eq "File" -or -Not $item.PSIsContainer) {
        # If it's a file, get its size directly
        $size = $item.Length
    }
    else {
        Write-Host "Error: Invalid type specified. Use -Type File or -Type Folder." -ForegroundColor Red
        return
    }

    # Convert size to human-readable format
    $sizeFormatted = Convert-Size $size

    # Output result
    [PSCustomObject]@{
        Name = $item.Name
        Size = $sizeFormatted
    }
}

function Convert-Size {
    param (
        [double]$SizeBytes
    )

    switch ($SizeBytes) {
        { $_ -ge 1TB } { "{0:N2} TB" -f ($_ / 1TB); break }
        { $_ -ge 1GB } { "{0:N2} GB" -f ($_ / 1GB); break }
        { $_ -ge 1MB } { "{0:N2} MB" -f ($_ / 1MB); break }
        { $_ -ge 1KB } { "{0:N2} KB" -f ($_ / 1KB); break }
        default { "{0} Bytes" -f $_; break }
    }
}

# Call function dynamically with provided parameters (Only once)
Get-SizeInfo -Path $Path -Type $Type