首页 > 解决方案 > 将返回值存储到变量

问题描述

我有以下代码可以根据大小转换分配GB/TB值

$datastoreCapacity = $store.CapacityGB
$postfixes = @("GB", "TB", "PB" )
for ($i=0; $datastoreCapacity -ge 1024 -and $i -lt $postfixes.Length; $i++) { $datastoreCapacity = $datastoreCapacity / 1024; }
return "" + [System.Math]::Round($datastoreCapacity,2) + " " + $postfixes[$i];

$datastoreFree = $store.FreeSpaceGB
$postfixes = @("GB", "TB", "PB" )
for ($i=0; $datastoreFree -ge 1024 -and $i -lt $postfixes.Length; $i++) { $datastoreFree = $datastoreFree / 1024; }
return "" + [System.Math]::Round($datastoreFree,2) + " " + $postfixes[$i];


但是,当我尝试将返回值分配给如下变量时,我遇到了错误

$datastoreCapacity = return "" + [System.Math]::Round($datastoreCapacity,2) + " " + 

请让我知道如何将值存储在变量中

标签: powershell

解决方案


为什么不为此创建一个小的辅助实用程序函数:

function Format-Capacity ([double]$SizeInGB) {
    $units = 'GB', 'TB', 'PB'
    for ($i = 0; $SizeInGB -ge 1024 -and $i -lt $units.Count; $i++) {
        $SizeInGB /= 1024
    }
    '{0:N2} {1}' -f $SizeInGB, $units[$i]
}

然后获得格式化的大小就像:

$datastoreCapacity = Format-Capacity $store.CapacityGB
$datastoreFree = Format-Capacity $store.FreeSpaceGB

推荐阅读