我正在尝试使用 Get-CimInstance 获取计算机名称、型号、制造商和 RAM 大小,并稍后将其格式化为表格,而无需 TotalMemorySize,仅包含我的 RAM 表槽。 我所坚持的是将字节转换为 GB:
Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object Name, Manufacturer, Model, TotalPhysicalMemory,
@{
Name = "RAM"
Expression = {
'GB' ([math]::[int](TotalPhysicalMemory / 1024 / 1024 / 1024))
}
Format-Table *
}
最佳答案
由于您使用的是 calculated property与 script block (
{ ... }
) 作为其Expression
条目值,您必须使用 automatic$_
variable引用手边的输入对象;因此,$_.TotalPhysicalMemory
检索(当前)管道输入对象的.TotalPhysicalMemory
属性值。PowerShell 支持binary multiplier suffixes在数字文字中,这样您就可以使用
1gb
表示 1 gibibyte ([Math]::Pow(1024, 3)
),例如。要在 PowerShell 中连接字符串,您需要
+
运算符(以字符串作为 LHS)。但是,对于更复杂的字符串格式,您可以使用-f
,即 format operator ;{0}
引用第一个 RHS 操作数,{0:F0}
将其格式化为 float (F
),并带有0
位小数,有效地将其四舍五入为整数。
把它们放在一起:
Get-CimInstance -ClassName Win32_ComputerSystem |
Select-Object Name, Manufacturer, Model, TotalPhysicalMemory, @{
Name = 'RAM'
Expression = { '{0:F0}GB' -f ($_.TotalPhysicalMemory / 1gb) }
} |
Format-Table # format as table *for display only*
关于powershell - 如何在 Get-CimInstance 中用 2-3 行将 TotalPhysicalMemory 转换为 GB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77391149/