IanB
IanB

Reputation: 271

add string to calculated output in PowerShell

I am using a line of PowerShell to check RAM on a machine and it works great but I need to add a string to the output:

Get-CimInstance -class Win32_PhysicalMemory |
  Measure-Object -Property capacity -Sum |
    % {[Math]::Round(($_.sum / 1GB),2)}

This produces a result based on how much memory the machine has but I need to add "GB" to the end so the output is 16GB not just 16.

I have tried various things, none has worked. I guess I am struggling to understand how to add a string to the output of a calculated property.

Upvotes: 0

Views: 819

Answers (2)

mklement0
mklement0

Reputation: 437110

(a) Use an expandable string (string interpolation):

Get-CimInstance -class Win32_PhysicalMemory | 
  Measure-Object -Property capacity -Sum | 
    % { "$([Math]::Round($_.sum / 1GB,2))GB" }

You can use $(...), the subexpression operator, to embed expressions and even multiple statements in a double-quoted string.


(b) Alternatively, use .NET string formatting via the -f operator:

Get-CimInstance -class Win32_PhysicalMemory | 
  Measure-Object -Property capacity -Sum | 
    % { '{0:G2}GB' -f ($_.sum / 1GB) }

The format string on the LHS must contain a placeholder for each RHS argument, starting with {0}; optionally, formatting instructions can be embedded in each placeholder, which in this case performs the desired rounding and displays up to 2 decimal places (G2).
The -f operator uses .NET's String.Format() method behind the scenes.


Important:

  • Method (a) always uses the invariant culture, in which . is the decimal mark.

  • Method (b) is culture-sensitive, so it uses the current culture's decimal mark (use Get-Culture to determine the current culture).

Upvotes: 1

Saggie Haim
Saggie Haim

Reputation: 344

You can use the .ToString() Method and then add the GB

(Get-CimInstance -class Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | % {[Math]::Round(($_.sum / 1GB),2)}).ToString() + " GB"

hope its helps

Upvotes: 0

Related Questions