Skip to content

Instantly share code, notes, and snippets.

@msftrncs
Last active December 1, 2021 20:42
Show Gist options
  • Save msftrncs/e2937c64396868efbf731084f9b89d7b to your computer and use it in GitHub Desktop.
Save msftrncs/e2937c64396868efbf731084f9b89d7b to your computer and use it in GitHub Desktop.
Format-Bytes: My Version
filter Format-Bytes {
if ($_ -is [ValueType]) {
$x = if (0 -ne $_) {
[Math]::Min([int][Math]::Truncate([Math]::Log([Math]::Abs($_), 1kb)), 8)
} else {
0
}
if ($x -eq 0) {
"$_ B"
} else {
"{0:N2} $('KMGTPEZY'[$x - 1])B" -f ($_ / [Math]::Pow(1kb, $x))
}
} else {
$_ # return the input because it could not be processed
}
}
@msftrncs
Copy link
Author

This is my take on the many variations of Format-Bytes function. I have applied it as a filter, which means it works exclusively with pipelines.

1tb | Format-Bytes # returns '1.00 TB'
1023 | Format-Bytes # returns '1023 B'
1024, -1073741824000000000pb | Format-Bytes # returns '1.00 KB', '-1,000,000,000.00 YB'

If NULL is input, NULL will be returned.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment