Simplify Math with Administrative Constants

1. Problem

You want to work with common administrative numbers (that is, kilobytes, megabytes, and gigabytes) without having to remember or calculate those numbers.

2. Solution

Use PowerShell’s administrative constants (KB, MB, and GB) to help work with these common numbers.

Calculate the download time (in seconds) of a 10.18 megabyte file over a connection that gets 215 kilobytes per second:

        PS >10.18mb / 215kb
        48.4852093023256


3. Discussion

PowerShell’s administrative constants are based on powers of two, since those are the kind most commonly used when working with computers. Each is 1,024 times bigger than the one before it:

        1kb = 1024
        1mb = 1024 * 1 kb
        1gb = 1024 * 1 mb

Some (such as hard drive manufacturers) prefer to call numbers based on powers of two “kibibytes,” “mebibytes,” and “gibibytes.” They use the terms “kilobytes,” “megabytes,” and “gigabytes” to mean numbers that are 1,000 times bigger than the one before it—numbers based on powers of 10.

Although not represented by administrative constants, PowerShell still makes it easy to work with these numbers in powers of 10—for example, to figure out how big a “300 GB” hard drive is when reported by Windows:

        PS >$kilobyte = [Math]::Pow(10,3)
        PS >$kilobyte
        1000
        PS >$megabyte = [Math]::Pow(10,6)
        PS >$megabyte
        1000000
        PS >$gigabyte = [Math]::Pow(10,9)
        PS >$gigabyte
        1000000000
        PS >(300 * $gigabyte) / 1GB
        279.396772384644
Tags: , , ,