PSPowerShell · Lesson 2 of 8

Variables & Types

PowerShell variables can hold any .NET type. Numbers, strings, arrays, hashtables, or entire objects returned by cmdlets.

PowerShell
# 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
PowerShell
# 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
}
◆ Note
In PowerShell, $true and $false (not true and false) are the boolean literals. $null (not null or None) is the null value. These are case-insensitive in practice, but lowercase is conventional.