If you read system information like the free disk space via WMI, PowerShell will display the result in bytes. The same applies to Get-ChildItem (the counterpart to dir in cmd.exe), which also displays file sizes in bytes. In the case of big values, this is not really what you want. However, it is relatively easy to convert megabytes to gigabytes with PowerShell.

For example, if you want to determine the size of a disk, you can run this command:

(gwmi win32_logicaldisk)[0]|select model, size

Convert into GB ^

In this case, the result shows the size of the first disk as a long number. However, you probably will only want to know the size in GB. You can get this easily by dividing the bytes by the predefined constant 1GB:

(gwmi win32_logicaldisk)[0]|select model, @{Name="GB";Expression={$_.size/1GB}}
Converting bytes into GB

Converting bytes into GB

This command uses a so-called calculated property because you can't just divide the Size property in the Select expression. The conversion to KB or MB works the same way.

Truncate and round decimal places ^

If you want to trim the slew of decimal places, you can truncate them entirely with the method truncate(), or you can round them with round():

Subscribe to 4sysops newsletter!

(gwmi Win32_DiskDrive)[0]|select model, @{Name="GB"; Expression={[math]::round($_.size/1GB, 2)}}

The truncate() call follows the same pattern, only you have to omit the second parameter, that is, truncate($_.size/1GB).

  1. HK 3 years ago

    Thank you. That helped me complete my script!

  2. S.G. 2 years ago

    hi! thanks for all, i have a question that i need to resolve. When you use the expression " Expression={[math]::round($_.size/1GB, 2)" Is it alway in the Select field? you can use this kind of expression in Write-output? i tried but it didn't work for me!


  3. Jonathan 7 months ago

    I was using script for memory. I was scratching my head as to why it was showing 4 GB twice. It then occurred to me, I have 8 gigs. The darn thing is giving me per stick. Sometime you have to really think out of the box when these things happen.

  4. Sameer 2 months ago

    This command worked like a charm. For those of you who want to get size of multiple vhdx files, Below command will help.
    Thank you

    Get-VM | Get-SCVirtualHardDisk | select name,location,@{Name=”Size”; Expression={[math]::round($_.Maximumsize/1GB, 2)}}

  5. Surender Kumar 2 months ago

    Excellent information.
    I know this is an old post but for new readers I would like to mention that
    Get-WmiObject (or gwmi alias) command has now been replaced by Get-CimInstance (or gcim alias), which produces the same output by the way.


Leave a reply

Your email address will not be published.


© 4sysops 2006 - 2022


Please ask IT administration questions in the forums. Any other messages are welcome.


Log in with your credentials


Forgot your details?

Create Account