Numbers

PowerShell offers several options for interacting with numbers and numeric data.

Simple Assignment

To define a variable that holds numeric data, simply assign it as you would other variables. PowerShell automatically stores your data in a format that is sufficient to accurately hold it.

$myInt = 10

$myInt gets the value of 10, as a (32-bit) integer.

$myDouble = 3.14

$myDouble gets the value of 3.14, as a (53-bit, 9 bits of precision) double.

$To explicitly assign a number as a long (64-bit) integer or decimal (96-bit, 96 bits of precision), use the long and decimal suffixes:

myLong = 0.999L

$myLong gets the value of 1, as a long integer.

$myDecimal = 0.999D

$myDecimal gets the value of 0.999.

PowerShell also supports scientific notation:

$myPi = 3141592653e-9

$myPi gets 3.141592653.

The datatypes in PowerShell (integer, long integer, double, and decimal) are built upon the .NET datatypes of the same name.

Administrative Numeric Constants

Since computer administrators rarely get the chance to work with numbers in even powers of ten, PowerShell offers the numeric constants of gb, mb, and kb to represent gigabytes, megabytes, and kilobytes, respectively:

$downloadTime = (1gb + 250mb) / 120kb

Hexadecimal and Other Number Bases

To directly enter a hexadecimal number, use the hexadecimal prefix 0x:

$myErrorCode = 0xFE4A

$myErrorCode gets the integer value 65098.

The PowerShell scripting language does not natively support other number bases, but its support for interaction with the .NET framework enables conversion to and from binary, octal, decimal, and hexadecimal:

$myBinary = [Convert]::ToInt32("101101010101", 2)

$myBinary gets the integer value of 2901.

$myOctal = [Convert]::ToInt32("1234567", 8)

$myOctal gets the integer value of 342391.

$myHexString = [Convert]::ToString(65098, 16)

$myHexString gets the string value of “fe4a”

$myBinaryString = [Convert]::ToString(12345, 2)

$myBinaryString gets the string value of “11000000111001”

Note

See the section “Working with the .NET Framework” to learn more about using PowerShell to interact with the .NET Framework.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.209.8