Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate string to integer inside of Get-WmiObject table - PowerShell

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
like image 701
Boogershut Avatar asked May 18 '26 18:05

Boogershut


1 Answers

You have many options for this:

  • String Formatting
@{n="Size";e={'{0}GB' -f ($_.Capacity / 1Gb)}}
  • Subexpression operator $( )
@{n="Size";e={"$($_.Capacity / 1Gb)GB"}}
  • String Concatenation with + Operator
@{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')}}
like image 130
Santiago Squarzon Avatar answered May 21 '26 07:05

Santiago Squarzon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!