beginner

PowerShell and Scripting for Support Technicians

Stop doing the same click-path fifty times: PowerShell basics (cmdlets, the pipeline, objects, filtering and exporting), common support one-liners, reading and writing small scripts safely with -WhatIf and error handling, bulk tasks from CSV files, and the habits that stop automation from causing damage. Practise the logic of an onboarding script in Python.

55 min

Why scripting belongs in a support skill set

Support work is full of repetition: reset the same cache on twelve PCs, list which machines are low on disk space, create twenty accounts for a new intake, export every user in a group. Doing it by hand is slow and error-prone. A few lines of script do it consistently, document exactly what was done, and free you for harder problems. You do not need to be a programmer; you need a small toolkit and good safety habits.

PowerShell is Microsoft’s shell and scripting language. It ships with Windows (and runs on Linux and macOS as PowerShell 7), and it manages almost everything Microsoft: files, services, the registry, Active Directory, Microsoft 365, Azure. Learning it is one of the best investments for a Windows-focused technician. (The Network Automation and Backend courses cover Python and Bash; the ideas carry across.)

Starting out

Open Windows Terminal or PowerShell (not as administrator unless a task needs it). Two essential helpers:

Get-Help Get-Service -Examples      # built-in help with examples (Update-Help downloads the latest)
Get-Command *service*                # find commands by name
Get-Service | Get-Member            # what properties and methods do these objects have?

Cmdlets: Verb-Noun

Commands are called cmdlets and follow Verb-Noun: Get-Process, Stop-Service, New-Item, Remove-Item, Set-ExecutionPolicy. Common verbs: Get (read), Set (change), New, Remove, Start/Stop/Restart, Enable/Disable, Import/Export. Parameters start with a dash: Get-Service -Name Spooler. Many have aliases (ls, cd, cat, ps, gci) for interactive use; in scripts, write the full name for readability.

Objects and the pipeline

The pipeline (|) sends the objects from one command to the next. Because they are objects with properties, you filter and sort on properties, not on text:

Get-Service | Where-Object Status -eq 'Running' | Sort-Object DisplayName | Select-Object Name, DisplayName, Status

Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 Name, CPU, WorkingSet

Get-ChildItem C:\Users -Recurse -File -ErrorAction SilentlyContinue |
    Where-Object Length -gt 500MB |
    Sort-Object Length -Descending |
    Select-Object FullName, @{Name='SizeGB'; Expression={[math]::Round($_.Length/1GB,2)}}

Key cmdlets for shaping output: Where-Object (filter), Select-Object (choose properties, first N), Sort-Object, Group-Object, Measure-Object (count, sum, average), ForEach-Object (do something with each), and formatting with Format-Table and Format-List (use these last, for display only).

Variables, comparisons and loops

$computer = $env:COMPUTERNAME           # variable
$disks = Get-PSDrive -PSProvider FileSystem
$disks | ForEach-Object { "{0}: {1:N1} GB free" -f $_.Name, ($_.Free/1GB) }

if ((Get-Service Spooler).Status -ne 'Running') { Start-Service Spooler }

foreach ($name in 'PC01','PC02','PC03') {
    Test-Connection -ComputerName $name -Count 1 -Quiet
}

Comparison operators are words: -eq, -ne, -gt, -lt, -like (wildcards), -match (regex), -contains, -in.

Support one-liners worth knowing

# System information
Get-ComputerInfo | Select-Object CsName, WindowsProductName, OsVersion, CsTotalPhysicalMemory
Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | Select-Object DeviceID, @{n='FreeGB';e={[math]::Round($_.FreeSpace/1GB,1)}}, @{n='SizeGB';e={[math]::Round($_.Size/1GB,1)}}
(Get-CimInstance Win32_OperatingSystem).LastBootUpTime        # uptime

# Services and processes
Restart-Service Spooler
Get-Process chrome | Stop-Process -WhatIf                      # preview first

# Network
Test-NetConnection server.corp.example.com -Port 445
Get-NetIPConfiguration
Resolve-DnsName example.com
ipconfig /flushdns                                              # native commands work too

# Event logs
Get-WinEvent -FilterHashtable @{LogName='System'; Level=2; StartTime=(Get-Date).AddDays(-1)} -MaxEvents 20

# Updates and software
Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 10
Get-Package | Select-Object Name, Version

# Files
Get-ChildItem C:\Temp -File | Where-Object LastWriteTime -lt (Get-Date).AddDays(-30) | Remove-Item -WhatIf

Safety habits (the important part)

  1. Preview with -WhatIf (and -Confirm) on commands that change things (Remove-Item, Stop-Process, Set-ADUser).
  2. Select first, then act. Run the selection part of the pipeline alone and read what it returns before adding the action (... | Remove-Item).
  3. Test on one or a few items, or on a test OU or machine, before the real run.
  4. Use the least privilege needed; avoid running everything as an administrator.
  5. Never hard-code passwords or secrets in scripts. Use Read-Host -AsSecureString, Windows Credential Manager, or a secrets vault (SecretManagement module); avoid putting credentials in command history.
  6. Handle errors: scripts should fail loudly, not carry on blindly (below).
  7. Log what you did: Start-Transcript, or write results to a log file with timestamps.
  8. Read scripts you did not write before running them, especially anything from the internet. Be suspicious of obfuscated code, Invoke-Expression/iex, and downloads piped into execution.
  9. Understand the execution policy: Get-ExecutionPolicy controls whether scripts may run (Restricted, RemoteSigned, AllSigned). It is a safety feature, not a security boundary; organisations often manage it and require signed scripts. Do not weaken policy to run an untrusted script.
  10. Keep scripts in version control (Git) with comments, and share good ones with the team.

From commands to scripts

A script is a text file with the extension .ps1. A small, safe, reusable example that reports low disk space on this PC:

<#
.SYNOPSIS
    Reports drives with less free space than a threshold.
.PARAMETER ThresholdGB
    Warn when free space is below this many gigabytes.
#>
param(
    [int]$ThresholdGB = 20
)

$ErrorActionPreference = 'Stop'

try {
    $low = Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" |
        Where-Object { ($_.FreeSpace / 1GB) -lt $ThresholdGB } |
        Select-Object DeviceID,
            @{n='FreeGB'; e={[math]::Round($_.FreeSpace/1GB,1)}},
            @{n='SizeGB'; e={[math]::Round($_.Size/1GB,1)}}

    if ($low) { $low | Format-Table -AutoSize; exit 1 }
    else      { Write-Output "All drives have at least $ThresholdGB GB free."; exit 0 }
}
catch {
    Write-Error "Could not read disk information: $($_.Exception.Message)"
    exit 2
}

Parts to notice: a comment-based help block; a parameter with a default (so the script is reusable); $ErrorActionPreference = 'Stop' plus try/catch so errors do not pass silently; and exit codes so tools that run the script can tell success from failure.

Functions and modules

Wrap repeated logic in functions, and collect them in a module (.psm1) your team shares:

function Get-StaleFiles {
    [CmdletBinding()]
    param([string]$Path, [int]$Days = 30)
    Get-ChildItem $Path -File -Recurse -ErrorAction SilentlyContinue |
        Where-Object LastWriteTime -lt (Get-Date).AddDays(-$Days)
}

Importing and exporting data (CSV)

Support work is full of lists. PowerShell reads and writes CSV easily:

Get-ADUser -Filter {Enabled -eq $true} -Properties Department, LastLogonDate |
    Select-Object Name, SamAccountName, Department, LastLogonDate |
    Export-Csv users.csv -NoTypeInformation

Import-Csv new-starters.csv | ForEach-Object {
    "{0} {1} starts on {2}" -f $_.FirstName, $_.LastName, $_.StartDate
}

Bulk creation with a dry run

# new-starters.csv: FirstName,LastName,Department
Import-Csv .\new-starters.csv | ForEach-Object {
    $sam = ("{0}.{1}" -f $_.FirstName, $_.LastName).ToLower() -replace "[^a-z.]", ""
    New-ADUser -Name "$($_.FirstName) $($_.LastName)" `
               -SamAccountName $sam `
               -UserPrincipalName "$sam@corp.example.com" `
               -Department $_.Department `
               -Path "OU=Staff,DC=corp,DC=example,DC=com" `
               -AccountPassword (ConvertTo-SecureString (New-Guid).Guid -AsPlainText -Force) `
               -ChangePasswordAtLogon $true -Enabled $true -WhatIf
}

-WhatIf lets you check the usernames, the OU and the count before creating anything. Real scripts also check for duplicates (below), log results, and send the temporary password to the manager through a secure channel instead of printing it.

Remote management

Invoke-Command -ComputerName PC01, PC02 -ScriptBlock { Get-Service Spooler }     # run on remote PCs (PowerShell remoting / WinRM)
Enter-PSSession -ComputerName PC01                                              # interactive remote shell

Remoting needs it to be enabled and allowed by policy, and uses your credentials: use it on managed machines inside the organisation, with approved accounts.

Other tools in the same family

  • Command Prompt and batch files (.bat/.cmd) for simple legacy tasks (ipconfig, net use).
  • Bash on Linux and macOS (see the next lesson) and Python for logic-heavy or cross-platform jobs (and for the exercise below).
  • Microsoft Graph PowerShell and the Microsoft 365 modules manage the cloud suite; Azure CLI/PowerShell manage Azure.
  • Task Scheduler and RMM or Intune run scripts on a schedule or push them to fleets, with logs and reporting.
  • No-code options (Power Automate, Zapier) suit simple workflows between SaaS tools.

Habits for good scripts

  • Name things clearly, comment the why, and keep scripts short.
  • Validate input (does the CSV have the expected columns? Is the user real?) before acting.
  • Be idempotent where possible: running twice should not duplicate or break things (check whether the account exists before creating it).
  • Make output useful: a summary of successes and failures at the end.
  • Test in a lab or a non-production OU and keep a rollback plan.
  • Share and document: put the script and a short README in your team’s repository, with who owns it.

Lab: the logic of an onboarding script (in Python)

The browser lab uses Python, but the logic is exactly what you would write in PowerShell. Given a list of new starters and the set of usernames that already exist, create usernames and email addresses:

  • make_username(first, last, existing): lower-case first.last, keeping only letters from each name (remove spaces, apostrophes and hyphens). If that name is already in existing, add a number starting at 2 (ada.obrien2, then ada.obrien3) until it is unique. Do not modify existing inside this function.
  • onboard(names, existing, domain): process the people in order, add each new username to existing (so later duplicates are caught), and return a list of (username, email) pairs, where the email is username@domain.
Generate unique usernames — Python 3
YOUR CODE (edit here, then press Run)
Ctrl/⌘ + Enter
OUTPUT
You need to remove all files older than 90 days from a shared temp folder on a file server. Describe how you would do this safely with PowerShell.

First list what would be affected: Get-ChildItem with a Where-Object LastWriteTime -lt (Get-Date).AddDays(-90) filter, reviewing the count, sizes and paths (and confirming you are in the right folder and not a parent). Then pipe to Remove-Item -WhatIf to preview, test on a small sub-folder, make sure a backup or recycle strategy exists and get the owner’s agreement, and finally run it without -WhatIf with logging (Start-Transcript or a log file). Schedule it only after it has been proven, and review the log regularly.

Can You Explain It?

Close the lesson and answer these without looking back. The goal isn't the wording — it's whether you've formed a usable mental model.

  • Explain the PowerShell pipeline and why passing objects is more powerful than passing text.
  • List five safety habits for running scripts that change many things at once.
  • Describe how you would turn a list of new starters in a CSV into accounts, including duplicate checks and a dry run.

🧪 Want to practise this on your own computer? See how to set up your lab →

🤖

Need clarification? Ask GT

Hi, I'm GT — your AI tutor for PowerShell and Scripting for Support Technicians. What would you like to know?
📝

Knowledge Check

1 of 4

How are PowerShell cmdlets named?

Report a problem

About: /lessons/powershell-and-scripting-for-support