如何根据数字占位符将值转换为 KB、MB 或 GB? [英] How to convert value to KB, MB, or GB depending on digit placeholders?

查看:64
本文介绍了如何根据数字占位符将值转换为 KB、MB 或 GB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容

Import-Module SqlServer

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

$estimatedSize = $([math]::Round($($($Analysis_Server.Databases[$cube].EstimatedSize)/1024/1024),2))

这为我生成了以 MB 为单位的大小

this generates for me the size in MB

我想增强它以使其更易于用户阅读,尤其是对于两位数 MB 的值

I would like to enhance this to make it more user friendly readable especially for values that are in the double digit MB

例如,有时我会得到值 50.9 MB,这很好.但其他一些值是 37091 MB3082.86 MB,我希望像这样的值自动转换为 GB (37.09 GB, 3.08 GBcode> 分别)如果它们在 GB 范围内.

for example, sometimes i get values 50.9 MB which is good. but some other values are 37091 MB or 3082.86 MB, and i'd like values like that to be automatically converted to GB (37.09 GB, 3.08 GB respectively) if they are in the GB range.

如果有不在MB范围内的值,它们应该以KB为单位显示

and if there are values that are not in MB range, they should be displayed in KB

0.78 MB 应该是 780 KB

我怎样才能做到这一点?

how can i accomplish this?

推荐答案

这里有另外两种以字节为单位格式化大小的方法:

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

1) 使用 switch()

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) 通过执行一个循环,其中给定的字节大小重复除以 1024

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"
}

这篇关于如何根据数字占位符将值转换为 KB、MB 或 GB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆