Includes/PwSh.Fw.Maths.psm1
<#
.SYNOPSIS Convert size from one unit to another .DESCRIPTION Convert size from one unit to another and return an object with value and unit. User can force the output unit or let the function choose the highest unit. .EXAMPLE 1024 | Convert-Size -From bytes -To KB .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. Choose 'Auto' to let function choose highest unit [validateset("Auto", "Bytes","KB","MB","GB","TB")][string]$To = "auto", # Return only the value [switch]$ValueOnly # [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" } } else { 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) if ($ValueOnly) { return $Value } else { return [PSCustomObject]@{ Value = [Math]::Round($value) Unit = $Unit } } } |