Home > database >  Concatenate string to integer inside of Get-WmiObject table - PowerShell
Concatenate string to integer inside of Get-WmiObject table - PowerShell

Time:10-29

I want to add "GB" to each instance of "Size" so each output shows "8GB". I'm not sure how to add or concatenate a string to the integer within the table...

I have tried simply adding "GB", assigning "GB" to a variable then adding $GB. But get back Select-Object : A positional parameter cannot be found that accepts argument 'System.Object[]'.

Input:

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

Output:

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

CodePudding user response:

You have many options for this:

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

Note here is needed to call the .ToString() method as suggested by Abraham in his comment or you would end up with an empty property or even worst:

PS \> 1 'a'
Cannot convert value "a" to type "System.Int32". Error: "Input string was not in a correct format."
  • Casting [string] to the operation also works here:
@{n="Size";e={[string]($_.Capacity / 1Gb) 'GB'}}
  • Using the -join Operator, pretty unorthodox for this use case but works
@{n="Size";e={-join(($_.Capacity / 1Gb),'GB')}}
  • Related