Round a number in PowerShell one-liner

Josiah picture Josiah · Oct 14, 2014 · Viewed 8.5k times · Source

I'm using VMWare's PowerCLI to run this command to output an inventory of sorts from vCenter.

Get-VM | Select-Object Name,MemoryGB,NumCpu,UsedSpaceGB,@{n="TotalHDSizeGB"; e={(Get-HardDisk -VM $_ |Measure-Object -Sum CapacityGB).Sum}},@n="Network"; e={(Get-NetworkAdapter -VM $_ |Select -unique -expand NetworkName)}}Sort-Object Network|Export-Csv -Path vms.csv

I'd like to round the UsedSpaceGB and list all of the NetworkName values, not just one. I've seen how to use [Math]::Round() to round numbers in scripts, but I haven't been able to find an example on the command line and my attempts have failed to accomplish the desired results. How do I do that?

Answer

Hunter Eidson picture Hunter Eidson · Oct 14, 2014

Try using the following instead of UsedSpaceGB:

@{ n="SpaceUsedGB"; e={[math]::round( $_.UsedSpaceGB, 3 )}}

That'll round UsedSpaceGB to 3 decimal places and give the field the name SpaceUsedGB. To round to the nearest whole number, either change the 3 to a 0, or just use:

@{ n="SpaceUsedGB"; e={[math]::round( $_.UsedSpaceGB )}}

If you don't want to return the NetworkNames as an array, but just as a sorted string, you could change that expression to something like:

@{n="Network"; e={(Get-NetworkAdapter -VM $_ | sort-object NetworkName | Select -unique -expand NetworkName) -join ', '}}

Because my TotalHDSizeGB had a bunch of decimal places in some cases as well, my final version of the command looks like:

get-vm | Select-Object Name, MemoryGB, NumCpu, @{ n="DiskUsedGB"; e={[math]::round( $_.UsedSpaceGB )}}, @{ n="TotalHDSizeGB"; e={[math]::round((Get-HardDisk -vm $_ | Measure-Object -Sum CapacityGB).Sum)}}, @{n="Network"; e={(Get-NetworkAdapter -VM $_ | sort-object NetworkName | Select -unique -expand NetworkName) -join ', '}} | Export-Csv -Path vms.csv