Lesson 2 of 8
Variables & Types
Learn how PowerShell work and the types you will use most: numbers, , and hashtables. A variable can hold any .NET type, including objects returned by cmdlets.
# Variable types — PowerShell infers the type
$integer = 42
$float = 3.14
$string = "Hello"
$boolean = $true # $true and $false (not true/false)
$null = $null # null value
# Strongly typed variables
[int]$count = 10
[string]$name = "Alice"
[datetime]$now = Get-Date
[bool]$flag = $true
# Check type
$x = 42
$x.GetType() # System.Int32
$x.GetType().Name # Int32
# Type conversion
$n = [int]"42" # string to int
$s = [string]42 # int to string
$d = [double]"3.14" # string to double
# String operations
$str = "Hello, World!"
$str.Length # 13
$str.ToUpper() # HELLO, WORLD!
$str.ToLower() # hello, world!
$str.Contains("World") # True
$str.Replace("World", "PowerShell") # Hello, PowerShell!
$str.Split(",") # @("Hello", " World!")
$str.Trim() # remove whitespace
$str.Substring(7, 5) # World
# Multi-line string (here-string)
$multiline = @"
This is line one.
This is line two.
Name: $name
"@
Write-Output $multiline# Arrays
$fruits = @("apple", "banana", "cherry")
$fruits[0] # apple
$fruits[-1] # cherry (last element)
$fruits[1..2] # slice: banana, cherry
$fruits.Count # 3
$fruits += "date" # add element (creates new array)
$fruits -contains "apple" # True
# ArrayList — mutable, better for adding/removing
$list = [System.Collections.ArrayList]@(1, 2, 3)
$list.Add(4)
$list.Remove(2)
$list.Count # 3
# Hashtable (like a dictionary)
$person = @{
Name = "Alice"
Age = 30
City = "Paris"
}
$person["Name"] # Alice
$person.Age # 30 (dot notation also works)
$person["Email"] = "alice@example.com" # add key
$person.Remove("City") # remove key
$person.Keys # Name, Age, Email
$person.Values # Alice, 30, alice@...
$person.ContainsKey("Name") # True
# Ordered hashtable (preserves insertion order)
$ordered = [ordered]@{
First = 1
Second = 2
Third = 3
}Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.