Includes/PwSh.Fw.Maths.psm1

<#
.SYNOPSIS
Short description
 
.DESCRIPTION
Long description
 
.PARAMETER From
Parameter description
 
.PARAMETER To
Parameter description
 
.PARAMETER Value
Parameter description
 
.PARAMETER Precision
Parameter description
 
.EXAMPLE
An example
 
.NOTES
General notes
 
.LINK
http://techibee.com/powershell/convert-from-any-to-any-bytes-kb-mb-gb-tb-using-powershell/2376
#>


function Convert-Size {
    [cmdletbinding()]
    param(
        # Value to convert
        [Parameter(Mandatory=$true,ValueFromPipeLine = $true)][double]$Value,

        # The unit of the input value
        [validateset("Bytes","KB","MB","GB","TB")][string]$From = "Bytes",

        # Unit of the output value. Chosse 'Auto' to let function choose highest unit
        [validateset("Auto", "Bytes","KB","MB","GB","TB")][string]$To = "auto"

        # [int]$Precision = 4
    )
    switch($From) {
        "Bytes" { $value = $Value }
        "KB" { $value = $Value * 1024 }
        "MB" { $value = $Value * 1024 * 1024}
        "GB" { $value = $Value * 1024 * 1024 * 1024}
        "TB" { $value = $Value * 1024 * 1024 * 1024 * 1024}
    }

    if ($To.ToLower() -eq "auto") {
        $To = "Bytes"
        if ($Value -gt 1024) { $To = "KB" }
        if ($Value -gt (1024*1024)) { $To = "MB" }
        if ($Value -gt (1024*1024*1024)) { $To = "GB" }
        if ($Value -gt (1024*1024*1024*1024)) { $To = "TB" }
    }
    switch ($To) {
        "Bytes" { $Value = $Value/1KB; $Unit = "B"}
        "KB" { $Value = $Value/1KB; $Unit = "KB"}
        "MB" { $Value = $Value/1MB; $Unit = "MB"}
        "GB" { $Value = $Value/1GB; $Unit = "GB"}
        "TB" { $Value = $Value/1TB; $Unit = "TB"}
    }

    # return [Math]::Round($value,$Precision,[MidPointRounding]::AwayFromZero)
    return [PSCustomObject]@{
        Value = [Math]::Round($value)
        Unit = $Unit
    }
}