PowerShell - 如何将大小单位表示为变量

PowerShell - How do you represent a unit of size as a variable

我想为 GB 或 TB 等单位大小设置一个变量,以用于计算磁盘容量。这是我的工作示例:

$SourceDriveLetter = "C"
$SourceDrive = Get-Volume -DriveLetter $SourceDriveLetter
$SourceCapacity = [math]::Round(($SourceDrive.Size/1TB),2)
$SourceCapacity
0.42

我想这样设置,这样我就可以轻松地从 TB 更改为 GB。我在电子邮件报告的其他地方使用 $Unit。

$SourceDriveLetter = "C"
$Unit = "TB"
$UnitCalc = 1 * [int]$Unit
$SourceDrive = Get-Volume -DriveLetter $SourceDriveLetter
$SourceCapacity = [math]::Round(($SourceDrive.Size/$UnitCalc),2)
$SourceCapacity

我知道 $Unit 是一个字符串开头,不确定如何在 $UnitCalc 中用数学计算将它表示为文字。任何帮助将不胜感激。

如果您事先知道所有单位,您只需使用 switch 表达式将字符串转换为适当的值:

$Unit = "TB"
$UnitCalc = switch($Unit) {
  "MB" { 1MB }
  "GB" { 1GB }
  "TB" { 1TB }
  default { throw "unhandled unit '$Unit'" }
}

$capacity = 20TB / $UnitCalc # gives 20

如果您不需要错误处理,您可以使用哈希表减少到单行,但请注意,对于未知的单位大小,这会给出 $UnitCalc = $null

$UnitCalc = @{ "MB" = 1MB; "GB" = 1GB; "TB" = 1TB }[$Unit]

确定最佳使用尺寸的代码怎么样?

Clear-Host 

$Size = 22373741824

#Updated per MClayton's suggestion, Thanks! 
$Unit = Switch ($Size) {
          {$Size -gt 1PB} { 'PB' ; Break }
          {$Size -gt 1TB} { 'TB' ; Break }
          {$Size -gt 1GB} { 'GB' ; Break }
          {$Size -gt 1Mb} { 'MB' ; Break }
          Default         { 'KB'         }
        }

"Unit is: $unit"

$SourceCapacity = [math]::Round(($Size/$("1"+$Unit)),2)

"Source Drive capacity is: $SourceCapacity $Unit"

当然,您将用检索到的值变量替换测试变量 $Size 并删除调试输出语句。

HTH

PowerShell 已经识别出 shorthand,例如 1GB1TB。如果您有排除引号并包含 1 的纪律,那么您的代码已经可以工作了。

$SourceDriveLetter = "C"
$Unit = 1TB
$SourceDrive = Get-Volume -DriveLetter $SourceDriveLetter
$SourceCapacity = [math]::Round(($SourceDrive.Size/$Unit),2)
$SourceCapacity

PS > .\Stack Overflow Demo.ps1
0.91

PS > $SourceDrive.Size / 1GB
930.528869628906