How to convert value to KB, MB, or GB depending on digit placeholders?

后端 未结 4 963
离开以前
离开以前 2020-11-30 14:29

I have the following

Import-Module SqlServer

$Analysis_Server = New-Object Microsoft.AnalysisServices.Server  
$Analysis_Server.connect(\"$server\")

$estim         


        
4条回答
  •  情深已故
    2020-11-30 15:16

    Here's two more ways of formatting a size in bytes:

    1) Using a switch()

    function Format-Size() {
        [CmdletBinding()]
        param(
            [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
            [double]$SizeInBytes
        )
        switch ([math]::Max($SizeInBytes, 0)) {
            {$_ -ge 1PB} {"{0:N2} PB" -f ($SizeInBytes / 1PB); break}
            {$_ -ge 1TB} {"{0:N2} TB" -f ($SizeInBytes / 1TB); break}
            {$_ -ge 1GB} {"{0:N2} GB" -f ($SizeInBytes / 1GB); break}
            {$_ -ge 1MB} {"{0:N2} MB" -f ($SizeInBytes / 1MB); break}
            {$_ -ge 1KB} {"{0:N2} KB" -f ($SizeInBytes / 1KB); break}
            default {"$SizeInBytes Bytes"}
        }
    }
    

    2) By performing a loop where the gives byte size is repeatedly divided by 1024

    function Format-Size2 {
        [CmdletBinding()]
        param(
            [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
            [double]$SizeInBytes
        )
    
        $units = "Bytes", "KB", "MB", "GB", "TB", "PB", "EB"
        $index = 0
    
        while ($SizeInBytes -gt 1024 -and $index -le $units.length) {
            $SizeInBytes /= 1024
            $index++
        }
        if ($index) {
            return '{0:N2} {1}' -f $SizeInBytes, $units[$index]
        }
    
        return "$SizeInBytes Bytes"
    }
    

提交回复
热议问题