【问题标题】:Concatenate string to integer inside of Get-WmiObject table - PowerShell将字符串连接到 Get-WmiObject 表内的整数 - PowerShell
【发布时间】:2021-10-28 21:00:44
【问题描述】:

我想将“GB”添加到“Size”的每个实例,以便每个输出显示“8GB”。我不确定如何将字符串添加或连接到表中的整数...

我尝试简单地添加+"GB",将“GB”分配给一个变量,然后添加+ $GB。但是回来Select-Object : A positional parameter cannot be found that accepts argument 'System.Object[]'.

输入:

$RAM = Get-WmiObject Win32_PhysicalMemory -ComputerName $Computer |
        select DeviceLocator,Manufacturer,PartNumber, @{n="Size";e={[math]::truncate($_.Capacity / 1073741824)}},Speed | FT -AutoSize
Write-Output $RAM

输出:

DeviceLocator Manufacturer PartNumber         Size Speed
------------- ------------ ----------         ---- -----
DIMM1         000000000000                       8  1600
DIMM2         000000000000                       8  1600
DIMM3         000000000000                       8  1600
DIMM4         000000000000                       8  1600

【问题讨论】:

  • [math]::truncate($_.Capacity / 1gb).ToString() + "GB"
  • @AbrahamZinala 成功了,谢谢!就像我理解的那样,基本上它将它变成一个字符串然后添加另一个字符串?另外,我不知道我可以使用1gb 而不是输入1073741824。再次感谢。

标签: powershell get-wmiobject


【解决方案1】:

你有很多选择:

@{n="Size";e={'{0}GB' -f ($_.Capacity / 1Gb)}}
@{n="Size";e={"$($_.Capacity / 1Gb)GB"}}
@{n="Size";e={$($_.Capacity / 1Gb).ToString()+'GB'}}

注意这里需要按照Abraham 在他的评论中的建议调用.ToString() 方法,否则你最终会得到一个空属性,甚至更糟:

PS \> 1+'a'
Cannot convert value "a" to type "System.Int32". Error: "Input string was not in a correct format."
  • [string] 投射到操作中也可以在这里工作:
@{n="Size";e={[string]($_.Capacity / 1Gb)+'GB'}}
  • 使用-join 运算符,对于这个用例来说非常不正统,但可以工作
@{n="Size";e={-join (($_.Capacity / 1Gb), 'GB')}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-14
    • 2019-06-15
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多