Skip to content

Commit bafeb97

Browse files
committed
New: Format Bytes as Filesize
1 parent af13f5c commit bafeb97

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
function Format-HumanizeFileSize {
2+
<#
3+
.synopsis
4+
Convert integer bytes into a humanized abbreviated strings
5+
.notes
6+
Pwsh 6.2 and 7 added additional units: <https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_numeric_literals?view=powershell-7.4#integer-literals>
7+
.example
8+
pwsh> Format-HumanizeFileSize 1.234kb
9+
1.2 KB
10+
11+
pwsh> Format-HumanizeFileSize 1.234kb -Digits 5
12+
1.23438 KB
13+
.example
14+
pwsh> 12.45gb, .9mb, 91231451, 2 | Format-HumanizeFileSize | Join-string -sep ', '
15+
12.5 GB, 921.6 KB, 87.0 MB, 2.0 b
16+
#>
17+
# Converts size in bytes to a humanized string
18+
[Alias('FormatFilesize')]
19+
[OutputType( [String]) ]
20+
param(
21+
# Size in bytes. future could include [uint64]. I used [long] because pwsh 5.1 and 7 use that
22+
[Parameter( Mandatory, ValueFromPipeline)]
23+
[long[]] $SizeInBytes,
24+
25+
# 0-to-number of digits after the decimal
26+
[Parameter()]
27+
[int] $Digits = 1
28+
)
29+
30+
# example final template string:
31+
# '{0:n2} TB'
32+
process {
33+
$Prefix = '{0:n', $Digits, '}' -join ''
34+
foreach($Item in $SizeInBytes) {
35+
switch( $Item) {
36+
# outer bounds
37+
{ $_ -lt 1kb } { "$Prefix b" -f $_ ; break}
38+
{ $_ -ge 1pb } { "$Prefix PB" -f ($_ / 1pb) ; break}
39+
# rest
40+
{ $_ -ge 1tb } { "$Prefix TB" -f ($_ / 1tb) ; break}
41+
{ $_ -ge 1gb } { "$Prefix GB" -f ($_ / 1gb) ; break}
42+
{ $_ -ge 1mb } { "$Prefix MB" -f ($_ / 1mb) ; break}
43+
{ $_ -ge 1kb } { "$Prefix KB" -f ($_ / 1kb) ; break}
44+
default {
45+
# break should be redundant, and this should too, unless there's a logic error
46+
throw "ShouldNeverReachCase: $SizeInBytes"
47+
}
48+
}
49+
}
50+
}
51+
}
52+
53+
$Samples = [long[]]@(
54+
780, 1234,
55+
0.8kb, 1.2kb,
56+
0.8mb, 1.2mb,
57+
0.8gb, 1.2gb,
58+
0.8tb, 1.2tb,
59+
0.8pb, 1.2pb
60+
)
61+
$Samples | %{
62+
[pscustomobject]@{
63+
BytesAsLong = $_
64+
Humanized = Format-HumanizeFileSize $_ -Digits 2
65+
}
66+
}
67+
68+
<# output
69+
BytesAsLong Humanized
70+
----------- ---------
71+
780 780.00 b
72+
1234 1.21 KB
73+
819 819.00 b
74+
1229 1.20 KB
75+
838861 819.20 KB
76+
1258291 1.20 MB
77+
858993459 819.20 MB
78+
1288490189 1.20 GB
79+
879609302221 819.20 GB
80+
1319413953331 1.20 TB
81+
900719925474099 819.20 TB
82+
1351079888211149 1.20 PB
83+
84+
#>

0 commit comments

Comments
 (0)