PowerShell Data Types


The following are the most common used data types in powerShell.
 [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 boolean values. There is also [void] casting an expression to the void datatype will effectively discard it (like out-null or redirecting to $null). It is very important to know these data type, because we're going to do a lot of casting variables. 

Casting is very important when reading in data supplied by users with 'Read-Host'. Normally 'Read-Host' will return a string type even when user enters 987, look this example.

$a = Read-Host 'Enter a'
$b = Read-Host 'Enter b'
$c = $a + $b
Write-Host 'a + b = ' $c

Unwanted result happen when you run the script.

Enter a: 123
Enter b: 456
a + b = 123456

So instead of it, we should've done this.

[int]$a = Read-Host 'Enter a'
[int]$b = Read-Host 'Enter b'
$c = $a + $b
Write-Host 'a + b = ' $c

Subscribe to receive free email updates:

0 Response to "PowerShell Data Types"

Post a Comment