Round a number in PowerShell one-liner
Asked Answered
E

1

7

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?

Essen answered 13/10, 2014 at 22:42 Comment(0)
K
9

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
Knuckleduster answered 13/10, 2014 at 23:13 Comment(1)
Thank you Hunter. I was sooo close in my attempts in the first one, but didn't have it quite right. On the second, I had no idea. You saved me a lot more fumbling around. I need to remember that -join stuff. I'm sure I could have used it in the past.Essen

© 2022 - 2024 — McMap. All rights reserved.