PowerShell

PowerShell Data Types Cheat Sheet: String, Char, DateTime, Bool, Array, Hashtable, PSObject, Void, Math, TimeSpan

This blog posts is all about PowerShell data types. What is a PowerShell data type? Data Types define what you can do with a PowerShell object. For example, a datetime object supports adding years, with a bool object you can figure out whether something is true or false.

The aim is not to explain each data type individually, but only to provide the data types as a cheat sheet and furthermore I will cover the most common data types used in PowerShell. I will also give you an example for each data type to spark some ideas on working with data types.

Here is the list with some examples to play with.


### String ###

$string='Patrick Gruenauer'

# Determine the length of the string ...

$string.Length

# Grab the first two letters ...

$first2=$string.Substring(0,2)

### Character ###

$char=[char]0x263a

### Byte ###

$byte=[byte]('0x'+'FE')

### DateTime ###

$birthday=[datetime]'03.23.1976'

# Calculate your time on earth ...

$timeonearth=(Get-Date) - $birthday

### Boolean ###

# Is it there or is it not there? Yes it is there! ==> True

$path=[bool](Get-ChildItem -Path C:\Windows -ErrorAction SilentlyContinue)

### Array ###

$array=[array]('Peter','Margit')

# Retrieve the first item in array

$array[0]

### Hashtable ###

$hash=[hashtable]@{Arnold = '1';Alex= '9'}

# Add an object to the hash table

$hash.Add('Markus','10')

### PSObject ###

# Declaring as an array ...

$o=@()

# Creating ordered hash tables ...

$obj=[ordered]@{
firstname = 'Patrick'
lastname = 'Gruenauer'
age = '43'
}

$obj2=[ordered]@{
firstname = 'Arnold'
lastname = 'Schwarzenburger'
age = '71'
}

# Adding hash tables to $o and creating an object

$o += New-Object -Type PSObject -Property $obj
$o += New-Object -Type PSObject -Property $obj2

### Void ###

# Send output to null

$none=[void]

### Math ###

# Round to 5 decimals ...

$math=[math]::Round('12.221349876',5)

### TimeSpan ###

# How many hours has a year?

[TimeSpan]::FromDays(365).Totalhours

Copy this code into your PowerShell ISE (ise.exe) session and discover the values. For instance, $o shows Arnold and me!

Unbenannt.PNG

See you next time with PowerShell!

Categories: PowerShell

Tagged as: ,

3 replies »

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.