Skip to content

Instantly share code, notes, and snippets.

@shiguruikai
Last active July 4, 2020 08:54
Show Gist options
  • Save shiguruikai/209899022c408c7a70988b21945597f0 to your computer and use it in GitHub Desktop.
Save shiguruikai/209899022c408c7a70988b21945597f0 to your computer and use it in GitHub Desktop.
function Format-Bytes {
[OutputType([string])]
[CmdletBinding()]
param (
[Parameter(Position = 0, Mandatory, ValueFromPipeline)]
[long] $Value,
[Parameter(Position = 1)]
[int] $DecimalPlaces = 1
)
if ($DecimalPlaces -lt 0) {
$DecimalPlaces = 0
}
if ($Value -lt 0) {
return $('-' + (Format-Bytes [System.Math]::Abs($Value) $DecimalPlaces))
}
return $(switch ($Value) {
{ $_ -lt 1KB } { "{0:n$DecimalPlaces} B" -f $Value; break }
{ $_ -lt 1MB } { "{0:n$DecimalPlaces} KB" -f ($Value / 1KB); break }
{ $_ -lt 1GB } { "{0:n$DecimalPlaces} MB" -f ($Value / 1MB); break }
{ $_ -lt 1TB } { "{0:n$DecimalPlaces} GB" -f ($Value / 1GB); break }
{ $_ -lt 1PB } { "{0:n$DecimalPlaces} TB" -f ($Value / 1TB); break }
default { "{0:n$DecimalPlaces} PB" -f ($Value / 1PB) }
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment