PowerShell and rounding. Math is hard!

I had a student question regarding a function he wrote.  The function basically displayed disk info (disk size, free disk space and percent free), but we couldn’t get it to round the numbers.  In this first example, the numbers are not rounded:

Function Get-DiskInfo
    {        
    param ($System =".")
    $display = @{Label = "Drive" ; Expression={$_.DeviceID}},`
    @{Label = "File System"; Expression={$_.FileSystem}},`
    @{Label = "Size(GB)"; Expression={ $_.Size / 1gb }},`
    @{Label = "Free Space(GB)"; Expression={$_.FreeSpace / 1gb}},`
    @{Label = "% Free"; Expression = { ($_.FreeSpace / $_.Size) * 100}}
    Get-WmiObject -Class win32_LogicalDisk -Filter "DriveType = '3'" -ComputerName $System | Format-Table $display -auto
    }

We then tried to use the {N:02} way of rounding, but it didn’t show any results.  Example using the {N:02} on the Size(GB) column:

Function Get-DiskInfo
    {        
    param ($System =".")
    $display = @{Label = "Drive" ; Expression={$_.DeviceID}},`
    @{Label = "File System"; Expression={$_.FileSystem}},`
    @{Label = "Size(GB)"; Expression={ "{N:02}" -f $_.Size / 1gb }},`
    @{Label = "Free Space(GB)"; Expression={$_.FreeSpace / 1gb}},`
    @{Label = "% Free"; Expression = { ($_.FreeSpace / $_.Size) * 100}}
    Get-WmiObject -Class win32_LogicalDisk -Filter "DriveType = '3'" -ComputerName $System | Format-Table $display -auto
    }

After a bit of Googling I discovered the [MATH]::round function. 

Function Get-DiskInfo
    {       
    param ($System =".")
    $display = @{Label = "Drive" ; Expression={$_.DeviceID}},`
    @{Label = "File System"; Expression={$_.FileSystem}},`
    @{Label = "Size(GB)"; Expression={ [Math]::Round($_.Size / 1gb,2)}},`
    @{Label = "Free Space(GB)"; Expression={[Math]::Round($_.FreeSpace / 1gb,2)}},`
    @{Label = "% Free"; Expression = {[Math]::Round($_.FreeSpace / $_.Size * 100,2)}}
    Get-WmiObject -Class win32_LogicalDisk -Filter "DriveType = '3'" -ComputerName $System | Format-Table $display -auto
    }

Leave a Reply

Your email address will not be published. Required fields are marked *