PowerShell Data Types
The most common DataTypes used in PowerShell are listed below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
[fusion_builder_container hundred_percent="yes" overflow="visible"][fusion_builder_row][fusion_builder_column type="1_1" background_position="left top" background_color="" border_size="" border_color="" border_style="solid" spacing="yes" background_image="" background_repeat="no-repeat" padding="" margin_top="0px" margin_bottom="0px" class="" id="" animation_type="" animation_speed="0.3" animation_direction="left" hide_on_mobile="no" center_content="no" min_height="none"][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.
There is also [void] casting an expression to the void datatype will effectively discard it (like redirecting to $null)
Unicode
To encode a Unicode character in a PowerShell string, prefix the unicode with 0x and 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
PS C:\> [byte](‚0x‘ + ‚FF‘)
255
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
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:
|
1 2 |
<span class="code">PS C:\> [DateTime]::ParseExact("08-12-2012","dd-MM-yyyy",[System.Globalization.CultureInfo]::InvariantCulture) </span> Saturday, December 08, 2012 00:00:00 |
|
1 2 |
<span class="code">PS C:\> [DateTime]::ParseExact("09-Jun-2012","dd-MMM-yyyy",[System.Globalization.CultureInfo]::InvariantCulture).ToString("yyyy-MM-dd") </span>2012-06-09 |
Testing DataTypes
To test the datatype of a value use a comparison operator:
|
1 2 3 4 5 |
PS C:\> 32 -is [int] True PS C:\> $true -is [bool] True |