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.

This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s