Private/ConvertSize.ps1

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
function ConvertSize {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory=$True)]
        [validateset("Bytes","KB","MB","GB","TB")]
        [string]$From,

        [Parameter(Mandatory=$True)]
        [validateset("Bytes","KB","MB","GB","TB")]
        [string]$To,

        [Parameter(Mandatory=$True)]
        [double]$Value,

        [Parameter(Mandatory=$False)]
        [int]$Precision = 4
    )

    switch($From) {
        "Bytes" {$Value = $Value }
        "KB" {$Value = $Value * 1024 }
        "MB" {$Value = $Value * 1024 * 1024}
        "GB" {$Value = $Value * 1024 * 1024 * 1024}
        "TB" {$Value = $Value * 1024 * 1024 * 1024 * 1024}
    }            
                
    switch ($To) {
        "Bytes" {return $value}
        "KB" {$Value = $Value/1KB}
        "MB" {$Value = $Value/1MB}
        "GB" {$Value = $Value/1GB}
        "TB" {$Value = $Value/1TB}
    }

    return [Math]::Round($value,$Precision,[MidPointRounding]::AwayFromZero)
}