0

I'm trying to put together an expression that returns a bare value, without a table or name of the expression included.

For example, I have this line from another solution:

gwmi win32_logicaldisk -Filter "DeviceID = 'C:'" |
  Format-Table @{n="Size";e={[math]::Round($_.Size/1GB,2)}}

This returns:

 Size
 ----
475.33

How can I grab just the 475.33?

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    `gwmi win32_logicaldisk -Filter "DeviceID = 'C:'" | Select-Object -Property @{n="Size";e={[math]::Round($_.Size/1GB,2)}} | Select-Object -ExpandProperty Size` – Olaf Jan 30 '20 at 23:18

3 Answers3

0

Use Select-Object instead of Format-Table:

$DiskC = gwmi win32_logicaldisk -Filter "DeviceID = 'C:'" | Select-Object @{n="Size";e={[math]::Round($_.Size/1GB,2)}}

$DiskC.Size
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
0
  • Format-* cmdlets return objects whose sole purpose is to provide formatting instructions to PowerShell's output-formatting system - see this answer. In short: only ever use Format-* cmdlets to format data for display, never for subsequent programmatic processing.

  • gwmi is the built-in alias for the Get-WmiObject cmdlet, which is obsolete. The CIM cmdlets (e.g., Get-CimInstance) superseded the WMI cmdlets in PowerShell v3 (released in September 2012). Therefore, the WMI cmdlets should be avoided, not least because PowerShell [Core] v6+, where all future effort will go, doesn't even have them anymore. For more information, see this answer.

  • If you simply want to calculate a value derived from (each of) your input object(s), use the ForEach-Object cmdlet.

Therefore:

Get-CimInstance win32_logicaldisk -Filter "DeviceID = 'C:'" | ForEach-Object {
  [math]::Round($_.Size / 1gb, 2)
}

Or, more simply, using an expression:

[math]::Round(
  (Get-CimInstance win32_logicaldisk -Filter "DeviceID = 'C:'").Size / 1gb, 2
)
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

If you use your first line:

gwmi win32_logicaldisk -Filter "DeviceID = 'C:'" | Format-Table @{n="Size";e={[math]::Round($_.Size/1GB,2)}}

But Pipe it trough Select-object instead of format table then pipe it again to select object expanding the property (or just .size)

  gwmi win32_logicaldisk -Filter "DeviceID = 'C:'" | Select @{n="Size";e={[math]::Round($_.Size/1GB,2)}} | select -ExpandProperty Size