← PowerShell course
2

Variables, Types, Arrays & Hashtables

25 min

Master PowerShell variables, common data types, arrays, and hashtables — the building blocks you'll use in every real script.

By the end you can
  • Declare and assign variables, and understand common types like string, int, datetime, and bool
  • Build and manipulate arrays with @(), indexing, .Count, and +=
  • Create hashtables with @{} and access values by key or dot notation
  • Use string interpolation and subexpressions to build dynamic messages and paths

Variables

A variable in PowerShell starts with $. Assignment is simple:

$serverName = 'WEB01'
$port       = 443
$isOnline   = $true
$patchDate  = [datetime]'2026-06-01'

PowerShell infers the type from the value, but you can cast explicitly:

$retryCount = [int]'3'      # string '3' becomes integer 3
$hostname   = [string]$env:COMPUTERNAME

Common Types

TypeExampleNotes
string'WEB01'Text. Use single quotes for literals.
int44332-bit integer.
bool$true / $falseLogical flag.
datetime[datetime]'2026-06-01'Rich date/time object.

Check a variable's type with .GetType():

$port.GetType().Name   # Int32

Arrays

Use @() to create an array. Elements are comma-separated:

$servers = @('WEB01', 'WEB02', 'DC01', 'FILE01')

Key operations:

$servers.Count        # 4
$servers[0]           # 'WEB01'  (zero-based index)
$servers[-1]          # 'FILE01' (last element)
$servers += 'SQL01'   # append an element

Iterate with foreach:

foreach ($s in $servers) {
    Write-Host "Pinging $s..."
}

Hashtables

A hashtable maps keys to values — ideal for structured data like a server record:

$server = @{
    Name = 'DC01'
    Role = 'Domain Controller'
    IP   = '10.0.0.1'
}

Access values two ways:

$server.Name       # 'DC01'
$server['Role']    # 'Domain Controller'

Add or update a key:

$server.OS = 'Windows Server 2022'
$server['IP'] = '10.0.0.2'

Iterate over key/value pairs:

foreach ($key in $server.Keys) {
    Write-Host "$key : $($server[$key])"
}

String Interpolation

Double-quoted strings expand variables. Single-quoted strings do not.

$name = 'WEB01'
"Server is $name"          # Server is WEB01
'Server is $name'          # Server is $name  (literal)

To embed an expression or property access inside a string, use $():

$server = @{ Name = 'DC01'; IP = '10.0.0.1' }
"Connecting to $($server.Name) at $($server.IP)"
# Connecting to DC01 at 10.0.0.1

Build a UNC path dynamically:

$fileServer = 'FILE01'
$share      = 'Logs'
$uncPath    = "\\$fileServer\$share"
# \\FILE01\Logs