-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormat-Size.psm1
More file actions
97 lines (87 loc) · 3.18 KB
/
Format-Size.psm1
File metadata and controls
97 lines (87 loc) · 3.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
function Format-Size {
param (
[CmdletBinding()]
# Input to format
[Parameter(Mandatory,Position=0,ValueFromPipeline)]
[double[]] $InputObject,
# Specifies the input format. Default is byte.
[Parameter()]
[PSDefaultValue(Help="B")]
[ValidateSet("B","KB","MB","GB")]
[string] $InputFormat = "B",
# Specifies the output format.
[Parameter(Position=1)]
[ValidateSet("","B","KB","MB","GB")]
[string] $OutputFormat,
# Returns the value as a double instead of a string with the format appended
[Parameter()]
[Alias("AsValue","AsNumber")]
# [ValidateScript({ $InputObject.Length -eq 1 -or $OutputFormat })]
[switch] $AsDouble
)
begin {
$InputFormat = $InputFormat.ToUpper()
$OutputFormat = $OutputFormat.ToUpper()
# Validate -AsDouble parameter
if ($AsDouble -and ($InputObject.Length -gt 1 -and -not $OutputFormat)){
throw [System.ArgumentException]::new("The -AsDouble switch can only be used if the -InputObject has a length of 1 or if an -OutputFormat is specified.")
}
function Get-FormattedSize($ByteValue, $Unit) {
if ($Unit -eq "B") {
$doubleValue = $ByteValue
} else {
$doubleValue = Invoke-Expression "$ByteValue / 1$Unit"
}
$doubleValue
}
# Truncates a provided double to a minimum total length of 4 (including the decimal place).
function Format-Truncated($LengthyValue) {
$isSmallNumber = $LengthyValue -eq [System.Math]::Ceiling($LengthyValue)
if ($LengthyValue -ge 1000 -or $isSmallNumber) {
$formattedValue = [System.Math]::Round($LengthyValue)
} else {
$formattedValue = [double]("$LengthyValue".Substring(0,4))
}
$formattedValue
}
}
process {
$output = $InputObject | ForEach-Object {
$ByteSize = -1
# Get the byte size of the input value
if ($InputFormat -eq "B") {
$ByteSize = $_
} else {
$ByteSize = Invoke-Expression "$_ * 1$InputFormat"
}
# If no OutputFormat is specified, dynamically determine unit to use.
if (-not $OutputFormat) {
$OutputFormat = switch ($ByteSize) {
{ $_ -ge 1gb } {
"GB"
continue
}
{ $_ -ge 1mb } {
"MB"
continue
}
{ $_ -ge 1kb } {
"KB"
continue
}
Default {
"B"
}
}
}
$value = Get-FormattedSize $ByteSize $OutputFormat
if ($AsDouble) {
return $value
} else {
$truncValue = Format-Truncated $value
return "$truncValue $OutputFormat"
}
}
$output
}
}