Learn › PowerShell

PowerShell Variables, Loops and Conditions

Store values in variables, make decisions with if and switch, and repeat work with foreach – the building blocks for turning one-liners into real admin scripts.

Beginner 10 min read
By Gopinath Karthikeyan

One-liners are great, but real tasks need memory (“remember this list of servers”), decisions (“only if the disk is low”) and repetition (“for each server”). That’s what variables, conditions and loops give you.

Variables

A variable starts with $ and holds anything – text, numbers, objects, lists:

$server   = 'SRV01'
$days     = 30
$services = Get-Service | Where-Object Status -eq 'Running'
$services.Count

Use clear names: $staleUsers beats $x.

Strings: double quotes expand variables, single quotes don’t:

"Checking $server"      # Checking SRV01
'Checking $server'      # Checking $server
"Free: $($disk.FreeGB) GB"   # use $( ) for properties and expressions

Arrays and hashtables

An array is a list:

$servers = 'SRV01', 'SRV02', 'SRV03'
$servers[0]        # first item
$servers.Count
$servers += 'SRV04'

Read a list from a file:

$servers = Get-Content C:\Temp\servers.txt

A hashtable stores key = value pairs:

$owners = @{ SRV01 = 'Finance team'; SRV02 = 'HR team' }
$owners['SRV01']

Conditions: if / elseif / else

$freePct = 8
if ($freePct -lt 10) {
    Write-Warning "Disk critically low: $freePct%"
} elseif ($freePct -lt 20) {
    Write-Host "Disk getting low: $freePct%"
} else {
    Write-Host 'Disk OK'
}

Combine tests with -and, -or, -not:

if ((Test-Path C:\Temp) -and -not (Test-Path C:\Temp\lock.txt)) { 'Safe to run' }

switch – many choices

switch ($env:COMPUTERNAME) {
    { $_ -like 'WEB*' } { 'Web server' }
    { $_ -like 'SQL*' } { 'Database server' }
    default             { 'Other' }
}

Loops

foreach – the one you’ll use most

foreach ($s in $servers) {
    $ok = Test-Connection -ComputerName $s -Count 1 -Quiet
    "{0,-10} {1}" -f $s, $(if ($ok) { 'UP' } else { 'DOWN' })
}

ForEach-Object – in the pipeline

Get-ChildItem C:\Logs -Filter *.log | ForEach-Object {
    "$($_.Name) is $([math]::Round($_.Length/1MB,1)) MB"
}

while – repeat until something changes

while ((Get-Service Spooler).Status -ne 'Running') {
    Start-Sleep -Seconds 5
}
'Spooler is running'

Always make sure a while loop can end – add a time limit for anything that waits on a server.

Collect results as objects

Instead of printing text, build objects – then you can sort, filter and export them:

$report = foreach ($s in $servers) {
    [pscustomobject]@{
        Server = $s
        Online = Test-Connection -ComputerName $s -Count 1 -Quiet
        Time   = Get-Date
    }
}
$report | Where-Object { -not $_.Online } | Export-Csv C:\Temp\offline.csv -NoTypeInformation

This pattern – loop, build [pscustomobject], then export – is behind most good admin reports.

FAQ

foreach or ForEach-Object? foreach is faster when you already have the list in a variable. ForEach-Object streams items through the pipeline and uses less memory for huge lists.

What’s next

Next: Write reusable scripts and functions.

Practise this topic

Test yourself with free questions on this topic – instant answers and explanations.

Start practice questions

PowerShellBeginnerScripting

Gopinath Karthikeyan

Gopinath Karthikeyan – Windows Site Reliability Engineer with about 12 years in enterprise Windows Server infrastructure, and founder of WinOps Academy. YouTube · LinkedIn

More in PowerShell