Public/ConvertTo-DattoByteSize.ps1
|
function ConvertTo-DattoByteSize { <# .SYNOPSIS Converts a byte count into binary storage units. .DESCRIPTION Returns the original byte count, values in KiB through TiB, and a compact human-readable value. The Datto schema uses raw bytes for several SaaS storage fields. .PARAMETER Bytes The byte count. .PARAMETER Precision Decimal places used for the human-readable value. .EXAMPLE ConvertTo-DattoByteSize -Bytes 123456789 .OUTPUTS PSCustomObject #> [CmdletBinding()] param( [Parameter(Mandatory, ValueFromPipeline)] [ValidateScript({ $_ -ge 0 })] [decimal]$Bytes, [Parameter()] [ValidateRange(0, 6)] [int]$Precision = 2 ) process { $units = @('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB') $index = 0 $value = $Bytes while ($value -ge 1024 -and $index -lt ($units.Count - 1)) { $value = $value / 1024 $index++ } [pscustomobject][ordered]@{ Bytes = $Bytes KiB = $Bytes / 1KB MiB = $Bytes / 1MB GiB = $Bytes / 1GB TiB = $Bytes / 1TB Value = [Math]::Round($value, $Precision) Unit = $units[$index] HumanReadable = ('{0:N' + $Precision + '} {1}') -f $value, $units[$index] } } } |