Categories

Common mistakes–size constants

I can’t count the number of times I’ve seen something like this:

Get-WmiObject -Class Win32_LogicalDisk -Filter {DriveType = 3} |
select @{N='Capacity'; E={[math]::Round(($_.Size / 1073741824), 2)}}

What’s wrong this?

The use of 1073741824 – in case you don’t recognise the number its 1 gigabyte.

Wouldn’t you prefer to do this

Get-WmiObject -Class Win32_LogicalDisk -Filter {DriveType = 3} |
select @{N='Capacity'; E={[math]::Round(($_.Size / 1gb), 2)}}

That’s right divide by 1 gigabyte.

PowerShell recognises the main sizes you’ll be using – from KB to PB (petabyte)

1kb, 1mb, 1gb, 1tb, 1pb |
foreach {
"{0,16}" -f $psitem
}

                        1024
                  1048576
            1073741824
      1099511627776
1125899906842624

 

Which would you prefer to type 1pb or 1125899906842624 ?

Using the size constants is less prone to error and also reminds you of what you are trying to achieve.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>