我有以下内容
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))
Run Code Online (Sandbox Code Playgroud)
这会为我生成大小(以 MB 为单位)
我想增强这一点,使其更加用户友好可读,特别是对于两位数 MB 的值
例如,有时我会得到50.9 MB很好的值。但其他一些值是37091 MB或,并且我希望这样的值在 GB 范围内3082.86 MB自动转换为 GB (分别)。37.09 GB, 3.08 GB
如果有不在 MB 范围内的值,则应以 KB 为单位显示
即0.78 MB应该是780 KB
我怎样才能做到这一点?
以下是格式化字节大小的另外两种方法:
1) 使用 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"}
}
}
Run Code Online (Sandbox Code Playgroud)
2) 通过执行循环,将给定的字节大小重复除以 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"
}
Run Code Online (Sandbox Code Playgroud)
将KB : 1024vs1000讨论放在一边,因为我们应该使用KiB,但没有人这样做,包括 Microsoft(PowerShell、Explorer 等):
Run Code Online (Sandbox Code Playgroud)PS C:\> 1Kb 1024
使用Windows Shell shlwapi.h StrFormatByteSize函数:
$Shlwapi = Add-Type -MemberDefinition '
[DllImport("Shlwapi.dll", CharSet=CharSet.Auto)]public static extern int StrFormatByteSize(long fileSize, System.Text.StringBuilder pwszBuff, int cchBuff);
' -Name "ShlwapiFunctions" -namespace ShlwapiFunctions -PassThru
Function Format-ByteSize([Long]$Size) {
$Bytes = New-Object Text.StringBuilder 20
$Return = $Shlwapi::StrFormatByteSize($Size, $Bytes, $Bytes.Capacity)
If ($Return) {$Bytes.ToString()}
}
Run Code Online (Sandbox Code Playgroud)
例子:
PS C:\> Format-ByteSize 37091MB
36.2 GB
PS C:\> Format-ByteSize 3082.86MB
3.00 GB
PS C:\> Format-ByteSize 0.78MB
798 KB
PS C:\> Format-ByteSize 670
670 bytes
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4478 次 |
| 最近记录: |