How-to: Define PowerShell Data Types

The most common DataTypes (type accelerators) used in PowerShell are listed below.

 [string]    Fixed-length string of Unicode characters
 [char]      A Unicode 16-bit character
 [byte]      An 8-bit unsigned character

 [int]       32-bit signed integer
 [long]      64-bit signed integer
 [bool]      Boolean True/False value

 [decimal]   A 128-bit decimal value
 [single]    Single-precision 32-bit floating point number
 [double]    Double-precision 64-bit floating point number
 [DateTime]  Date and Time

 [xml]       Xml object
 [array]     An array of values
 [hashtable] Hashtable object

PowerShell has two built in variables $true and $false for displaying the true and false boolean values.
Casting an expression to [void] will effectively discard it (like out-null or redirecting to $null)

Hexadecimal literals are prefixed with 0x to distinguish them from decimal numbers.
Binary literals are prefixed with 0b to distinguish them from decimal numbers.

PowerShell integer rounding is directly inherited from .Net which uses so-called 'Rounding half to even' (following the IEEE 754 recommendation).
So [Int]$x = 7 / 2 gives $x = 4
(since 7/2 == 3.5, not 3)

Multiplier Suffix

These can be used for real and integer numbers:

Suffix Meaning
d decimal data type
kb kibibyte multiplier
mb mebibyte multiplier
gb gibibyte multiplier
tb tebibyte multiplier
pb pebibyte multiplier

So 10mb will evaluate as 10485760 and 1.2kb will evaluate to 1228.8
The suffixes used by PowerShell should be Power of 10 numbers according to IEC 60027-2, but they actually evaluate as Power of 2.

PowerShell 6.2 also adds several type suffixes for signed/unsigned byte/short/big integer values.

Unicode

To encode a Unicode character in a PowerShell string, prefix the hex value of the unicode with 0x and then cast it to System.Char:

PS > [char]0x263a

Casting

To force a conversion to a specific datatype, prefix the value or variable with the type in square brackets, this is known as a Cast Operator and forces the chosen datatype:

PS C:\> [int]"0064"
64

PS C:\> [int]$false
0

Notice that this does not perform any type checking so you can do:

PS C:\> [string]$num = 7
PS C:\> $num + 2
72

Casting is particularly important when reading in data supplied by a user (with read-host) casting to [string] will return a String even if the user enters 123

PS C:\> [datetime]$appointment = '2022-July-02'
PS C:\> $appointment
02 July 2022

::ParseExact can also be used to ensure dates are parsed in a known format, in this example the $dateAsString must match the date format of the second parameter:

PS C:\> $dateAsString = '2022-07-02T14:27'
PS C:\> $appointment = [datetime]::parseexact($dateAsString, 'yyyy-MM-ddTHH:mm', $null)
PS C:\> $appointment
02 July 2022 14:27:00

When assigning a value to a variable, you can cast either side of the expression:

$v1 = [int]0123
[int]$v1 = 0123
[int]$v1 = [int]0123

Some expressions will be implicitly converted before you even cast them:

PS C:\> [string]$var = [string]0123
PS C:\> $var
123

PS C:\> [string]$var = [string]"0123"
PS C:\> $var
0123

Hex numbers

Prefixing a string value with '0x' indicates a hex number.
You can invoke a conversion to [int] or [byte] by casting it:

PS C:\> [byte]('0x' + 'FF')
255

PS C:\> $hexnum = 'fa00'
PS C:\> [int]"0x$hexnum"
64000

Arrays

Cast an array variable:

[int32[]]$stronglytypedArray = @()

[int32[][]]$multiDimensionalArray = @()

When a value is cast to a particular datatype, it is a one time thing.
When a variable is cast to a particular datatype, it will stick just like DIM Variable As DataType in other languages.
The variable's datatype will not change again unless you explicitly recast the variable to a different data type, or remove the variable completely (with Remove-Variable) and re-create it.
Get-Member and GetType() will display the current datatype but do not indicate if it is static or variant.

[int]$test = 0123
$test = [string]"00456"
# at this point, which data type do we end up with?
$test.GetType().FullName

If you cast a fractional value to an integer, PowerShell will Round() the result, to strip off all decimals behind the decimal point, use Truncate() from the .NET Math library.

Casting a string into [DateTime]will by default accept USA format dates MM/DD/YYYY or ISO 8601 YYYY-MM-DD. You can override this by using ::ParseExact to specify the exact format of the date string you are supplying.

For example to cast a date string "08-12-2012" that’s in UK format:

PS C:\> [DateTime]::ParseExact("08-12-2012","dd-MM-yyyy",[System.Globalization.CultureInfo]::InvariantCulture) 
Saturday, December 08, 2012 00:00:00

Cast a date string "09-Jun-2012" that’s in UK format and then display it as "yyyy-MM-dd"

PS C:\> [DateTime]::ParseExact("09-Jun-2012","dd-MMM-yyyy",[System.Globalization.CultureInfo]::InvariantCulture).ToString("yyyy-MM-dd")
2012-06-09

Testing DataTypes

To test the datatype of a value use a comparison operator:

PS C:\> 32 -is [int]
True PS C:\> $true -is [bool]
True

If you are going to cast a variable into a new datatype it is a good idea to first test if the value will cast sucessfully using -as, if the conversion fails, it will return a NULL, which can be used to either avoid the conversion or to raise an error:

[string]$var = "64a"
if( ($var -as [double]) -ne $null ) {
   [double]$var = $var
}
$var.GetType().FullName

“Character is what we do when no one's looking” ~ Bill Hybels

Related PowerShell Cmdlets

Variables and Operators - Create, add, subtract, divide.
Enum - Create and use PowerShell enums.
[math]::Round - Round a number to any given number of decimal places.
DateTime formats
Format-Hex - Display a file or other input as hex.
Get-Item variable:
Get-Variable


 
Copyright © 1999-2024 SS64.com
Some rights reserved