Sign in Start free

EngineeringFree course

PowerShell Scripting

Automate Windows, Microsoft 365 and Azure with the object pipeline: discovery, advanced functions, error handling, remoting and PowerShell's own security controls.

  • Level Junior → Mid
  • Time 240 min
  • Modules 11
  • Exercises 22 with worked solutions
  • Includes Lab, 5-question quiz, references

What you'll learn

  • Discover commands and properties with Get-Command, Get-Help and Get-Member
  • Filter, sort and export objects in the pipeline
  • Write an advanced function with validated parameters
  • Run remote administration safely
  • Configure logging, signing and constrained language

Each lesson is tagged Junior, Mid or Expert, so you can start where you are. Finish with the lab and the quiz; a score of 4 out of 5 marks the course complete in this browser.

The lessons below are in English for now, because they quote technical names, commands and log fields. An Arabic version is planned.

Course map

Each module moves from fundamentals to applied work to an expert challenge. Exercises have worked solutions: try first, then open the solution. 11 modules · 22 exercises · ~4 hours

  1. 0Start here: PowerShell, installation and the course projectJuniorMidExpert20 min · 1 exercises
  2. 1Discovering commandsJuniorMidExpert20 min · 2 exercises
  3. 2Files, folders and providersJuniorMidExpert20 min · 3 exercises
  4. 3Objects and the pipelineJuniorMidExpert25 min · 2 exercises
  5. 4Variables, types and operatorsJuniorMidExpert25 min · 2 exercises
  6. 5Control flow: decisions and loopsJuniorMidExpert25 min · 3 exercises
  7. 6Functions, scripts and modulesJuniorMidExpert25 min · 2 exercises
  8. 7Errors, safe changes and debuggingJuniorMidExpert20 min · 1 exercises
  9. 8Text, regular expressions and data formatsJuniorMidExpert20 min · 3 exercises
  10. 9Windows administration, event logs and remoting (Windows lab)JuniorMidExpert25 min · 1 exercises
  11. 10Cheat sheet, assessment and expert challengeJuniorMidExpert15 min · 2 exercises

No prior experience is needed. Module 0 covers the architecture, installation and configuration, and sets up the project you extend in every module. Each command is labelled with its impact (read-only, changes files, changes the system, uses the network). Work on a computer or virtual machine you control.

0

Start here: PowerShell, installation and the course project

Goal: Understand how PowerShell works and why it passes objects, install PowerShell 7, read a command line, and set up the project.

20 min

PowerShell and the object pipeline

PowerShell is Microsoft's command-line shell and scripting language, built on .NET. Commands are called cmdlets and named Verb-Noun: Get-Service, Stop-Process, Export-Csv. PowerShell 7 (pwsh) runs on Windows, Linux and macOS; Windows PowerShell 5.1 is the older version built into Windows.

PowerShell is the primary automation interface for Windows Server, Active Directory, Microsoft 365, Entra ID and Azure, and much Windows security tooling (event logs, Defender, AppLocker) exposes cmdlets. Bulk administration, compliance checks and evidence collection across many hosts are therefore usually written in PowerShell. Attackers use it too, which is why defenders must read it fluently.

Unlike text-based shells such as Bash, PowerShell passes .NET objects between commands. Each object has named, typed properties, so later commands filter and sort by property name instead of cutting text by position.

Youtype Verb-Noun commandsPowerShell 7 (pwsh)parses commands, binds parameters, runs the pipeline.NET runtimeevery result is a .NET object with properties and methodsProvidersfile system, registry, environment, certificates as drivesWindows / Linux / macOSservices, processes, event logs, networkModulesActiveDirectory, Az,Microsoft.Graph, Pester
Text pipeline (Bash)Object pipeline (PowerShell)'rana IT True 2026-12-01'one line of text: cut it by positionawk '{print $2}' → breaks if a column movesNameranaDepartmentITEnabledTrueLastLogon2026-12-01Where-Object Department -eq 'IT' → by name
PowerShellwhat you will learnDiscover and navigateGet-Command, Get-Help, Get-Memberproviders, items, -WhatIfObjects and the pipelineWhere, Select, Sort, Groupformat lastVariables and typesstrings, arrays, hashtablescasting, calculated propertiesControl flow and functionsif, switch, foreachadvanced functions, modulesErrors and datatry/catch, -ErrorActionregex, CSV, JSON, HTMLWindows administrationservices, event logs (4625)remoting, scheduled tasks

Quick check: Which name follows the PowerShell convention?

SymptomLikely causeFix
two different PowerShell windows on WindowsWindows PowerShell 5.1 and PowerShell 7 are separate programsuse PowerShell 7 (pwsh) for this course

Install PowerShell 7 and an editor

Install PowerShell 7 and Visual Studio Code with its PowerShell extension.

Several lessons use version 7 features; the editor highlights mistakes, shows parameter hints and runs or debugs scripts with F5.

Windows Terminal or Windows PowerShell
winget install --id Microsoft.PowerShell --source winget

Open Windows Terminal and choose the 'PowerShell' profile (7.x). Module 9 needs Windows: a Windows 10/11 or Windows Server virtual machine is ideal.

$PSVersionTableShow the PowerShell version (an automatic variable).Read-only
Syntax$PSVersionTable.PSVersion
Example
powershell
$PSVersionTable.PSVersion.ToString()
Output
Expected output
7.5.4
Verify

Any 7.x version is fine.

SymptomLikely causeFix
'pwsh' is not recognizedthe terminal was opened before installingopen a new terminal
'running scripts is disabled on this system'Windows execution policySet-ExecutionPolicy -Scope CurrentUser RemoteSigned (module 6 explains it)

Reading a command line

A command line has a prompt, a cmdlet, parameters (names starting with -) with their values, and optionally a pipeline | to further cmdlets.

Documentation, scripts and incident reports are written in this form. Recognising the parts lets you read unfamiliar commands and look up the right parameter.

Parameter names are case-insensitive and can be shortened while unambiguous (-Filt for -Filter), but scripts should use full names. Some parameters are positional: the name may be omitted.

1
Prompt. PS and the current location (Windows: PS C:\Users\rana>).
2
Cmdlet. Verb-Noun: get the child items (files and folders) of a location.
5
Pipeline. Passes the file objects to the next cmdlet.
terminal
PS /home/rana/ps-lab> Get-ChildItem -Path . -Filter *.csv | Select-Object Name, Length
3
Parameter names.
4
Parameter values. . is the current folder; *.csv is a wildcard.
6
Property names to keep from each object.
Expected output
Name      Length
----      ------
users.csv    168

Quick check: In Get-Service -Name W32Time, what is W32Time?

Exercise 1Junior

A colleague's note says gci . *.log. Rewrite it with the full cmdlet and parameter names.

Worked solution
powershell
Get-ChildItem -Path . -Filter *.log

gci is an alias; the two values are positional (Path first, then Filter). Full names make scripts readable and portable.

The course project: an account-audit toolkit

You will build tools that audit Rimal Logistics' user accounts and login logs: find stale accounts, summarise failed logins, change accounts safely and produce reports.

Account hygiene, disabling accounts that are no longer used, is one of the most effective security controls, and auditors check it. PowerShell is how Windows teams do it at scale.

Paste step 0 into PowerShell to create ~/ps-lab with users.csv and auth.log. @' … '@ is a here-string (multi-line text); you will understand every line by module 4.

Steps 1-2explore, organiseSteps 3-4filter, DaysIdleStep 5classify accountsSteps 6-7script, module, -WhatIfStep 8CSV, JSON, HTMLStep 9Windows + schedule
powershell · project step 0 (paste once)
New-Item -ItemType Directory -Force ~/ps-lab | Out-Null
Set-Location ~/ps-lab
@'
Name,Department,Enabled,LastLogon
rana,IT,True,2026-12-01
omar,Finance,True,2026-08-15
sara,IT,False,2026-06-30
svc_backup,IT,True,2026-12-02
khalid,HR,True,2025-11-20
'@ | Set-Content users.csv
@'
Dec  3 08:01:12 web01 sshd[1201]: Failed password for root from 203.0.113.5 port 52144 ssh2
Dec  3 08:01:15 web01 sshd[1201]: Failed password for root from 203.0.113.5 port 52144 ssh2
Dec  3 08:02:40 web01 sshd[1210]: Accepted publickey for deploy from 198.51.100.7 port 40022 ssh2
Dec  3 08:05:03 web01 sshd[1222]: Failed password for invalid user admin from 192.0.2.44 port 61001 ssh2
Dec  3 08:05:09 web01 sshd[1222]: Failed password for invalid user oracle from 192.0.2.44 port 61001 ssh2
Dec  3 08:09:51 web01 sshd[1240]: Failed password for root from 203.0.113.5 port 52190 ssh2
'@ | Set-Content auth.log
Get-ChildItem | Select-Object Name, Length
Expected output on Linux and macOS (Windows line endings add 1 byte per line: 591 and 174)
Name      Length
----      ------
auth.log     585
users.csv    168
SymptomLikely causeFix
'>>' continuation promptthe here-string was not closed'@ must be at the very start of its line; press Ctrl+C and paste again
1

Discovering commands

Goal: Find any command, read its help and syntax, and inspect what it returns.

20 min

Free account Create a free account or sign in to continue this course.

2

Files, folders and providers

Goal: Navigate and manage files with safety switches, read and write text, and browse other data stores as drives.

20 min

Free account Create a free account or sign in to continue this course.

3

Objects and the pipeline

Goal: Turn data into objects, then filter, sort, shape, group and count them in a pipeline.

25 min

Free account Create a free account or sign in to continue this course.

4

Variables, types and operators

Goal: Store values, build strings, use arrays and hashtables, convert types and add calculated properties.

25 min

Free account Create a free account or sign in to continue this course.

5

Control flow: decisions and loops

Goal: Make scripts decide with if and switch, and repeat with foreach, ForEach-Object and while.

25 min

Free account Create a free account or sign in to continue this course.

6

Functions, scripts and modules

Goal: Package logic as advanced functions that behave like cmdlets, save them as scripts, and share them as a module.

25 min

Free account Create a free account or sign in to continue this course.

7

Errors, safe changes and debugging

Goal: Handle failures deliberately, make changes that support -WhatIf, and find bugs quickly.

20 min

Free account Create a free account or sign in to continue this course.

8

Text, regular expressions and data formats

Goal: Search logs with regular expressions, extract fields, and move data between CSV, JSON and HTML.

20 min

Free account Create a free account or sign in to continue this course.

9

Windows administration, event logs and remoting (Windows lab)

Goal: Query services, processes and security events, run commands on many machines, and schedule the audit.

25 min

Free account Create a free account or sign in to continue this course.

10

Cheat sheet, assessment and expert challenge

Goal: Consolidate the syntax on one page, then build and use the finished audit tool on your own.

15 min

Free account Create a free account or sign in to continue this course.

Quick reference (the cheat-sheet lessons and the PDF content)
1

Three commands that teach you the rest

Junior
powershell · discovery
Get-Command *service*              # find commands
Get-Command -Noun EventLog -Module Microsoft*
Get-Help Get-WinEvent -Examples     # usage examples
Update-Help -Scope CurrentUser      # once, as admin or user
Get-Service | Get-Member            # what properties exist?
(Get-Item C:\Windows).LastWriteTime

Naming you can guess

  • Verb-Noun: Get-, Set-, New-, Remove-, Start-, Stop-
  • Approved verbs: Get-Verb
  • Parameters tab-complete; aliases (ls, gci) are for the console, not scripts
  • -WhatIf previews a change; -Confirm asks first
  • Version check: $PSVersionTable
2

The object pipeline

Junior
Bash passes text. PowerShell passes objects with properties, so you filter on fields instead of parsing strings.Get-Process[Process] objectsWhere-ObjectCPU -gt 100Sort-ObjectCPU -DescendingSelect-ObjectName, Id, CPUExport-Csvor ConvertTo-JsonGet-Process | Where-Object CPU -gt 100 | Sort-Object CPU -Descending | Select-Object Name,Id,CPU -First 5
3

Everyday syntax

JuniorMid
TaskPowerShell
Variable and string$name = 'web01'; "host: $name"
Array and hashtable$hosts = @('a','b'); $cfg = @{ Port = 443; Tls = $true }
Custom object[pscustomobject]@{ Host = $h; Up = $ok }
Comparison-eq -ne -gt -lt -like 'web*' -match '^\d+$' -in -contains
Loop over itemsforeach ($h in $hosts) { Test-Connection $h -Count 1 }
Pipeline loop$hosts | ForEach-Object { $_.ToUpper() }
Parallel (7+)$hosts | ForEach-Object -Parallel { Test-Connection $_ -Count 1 } -ThrottleLimit 8
Read JSON / CSVGet-Content x.json -Raw | ConvertFrom-Json; Import-Csv users.csv
Splatting$p = @{ Path = $f; Encoding = 'utf8' }; Set-Content @p -Value $t
4

An advanced function: the unit of reuse

Mid
powershell · Get-FailedLogon.ps1
function Get-FailedLogon {
    [CmdletBinding()]
    param(
        [Parameter(ValueFromPipeline)]
        [string[]] $ComputerName = $env:COMPUTERNAME,
        [ValidateRange(1, 720)] [int] $Hours = 24
    )
    process {
        foreach ($c in $ComputerName) {
            $filter = @{ LogName = 'Security'; Id = 4625
                         StartTime = (Get-Date).AddHours(-$Hours) }
            try {
                Get-WinEvent -ComputerName $c -FilterHashtable $filter -ErrorAction Stop |
                  ForEach-Object {
                    [pscustomobject]@{
                      Computer = $c; Time = $_.TimeCreated
                      User = $_.Properties[5].Value
                      Source = $_.Properties[19].Value }
                  }
            } catch [System.Exception] {
                Write-Warning "$c : $($_.Exception.Message)"
            }
        }
    }
}
Get-FailedLogon -Hours 4 | Group-Object Source | Sort-Object Count -Desc

Why this shape

  • [CmdletBinding()] gives -Verbose, -ErrorAction for free
  • Typed, validated parameters reject bad input early
  • process {} streams pipeline input
  • -FilterHashtable filters on the server, fast
  • Returns objects, so callers can sort, group or export
  • -ErrorAction Stop makes errors catchable
5

Error handling

Mid
SettingEffect
$ErrorActionPreference = 'Stop'Treat errors as terminating in the script
-ErrorAction SilentlyContinueSuppress: use rarely, and log why
try / catch / finallyHandle terminating errors; clean up in finally
$LASTEXITCODEExit code of native tools (git, robocopy)
Set-StrictMode -Version LatestUninitialized variables become errors
powershell · retry pattern
$tries = 0
do {
  try { Invoke-RestMethod $uri -TimeoutSec 15; break }
  catch {
    if (++$tries -ge 4) { throw }
    Start-Sleep -Seconds ([math]::Pow(2, $tries))
  }
} while ($true)
6

Remote administration

MidExpert
powershell · remoting
# one-off command on many servers
Invoke-Command -ComputerName (Get-Content servers.txt) -ScriptBlock {
  Get-Service -Name W32Time | Select-Object Status
} -ThrottleLimit 16

# interactive session
Enter-PSSession -ComputerName dc01

# PowerShell 7 over SSH (also Linux)
Invoke-Command -HostName web01 -UserName ops { uname -a }

Remoting the safe way

  • WinRM over HTTPS (5986) or SSH; avoid HTTP with Basic auth
  • Use Just Enough Administration (JEA) endpoints for helpdesk tasks
  • Never pass passwords as strings: Get-Credential or the SecretManagement module
  • Avoid CredSSP: it exposes credentials to the remote host
  • Log remoting with Script Block Logging
7

Admin tasks cookbook

JuniorMid
TaskCommand
Local adminsGet-LocalGroupMember -Group Administrators
New services installed (event 7045)Get-WinEvent -FilterHashtable @{LogName='System';Id=7045} -MaxEvents 20
Listening ports with processGet-NetTCPConnection -State Listen | Select LocalPort,OwningProcess
Scheduled tasks not from MicrosoftGet-ScheduledTask | ? TaskPath -notlike '\Microsoft\*'
File hashGet-FileHash .\tool.exe -Algorithm SHA256
Disabled AD users (RSAT)Search-ADAccount -AccountDisabled -UsersOnly
Stale computers (90 days)Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 90.00:00:00
Microsoft Graph sign-insConnect-MgGraph -Scopes AuditLog.Read.All; Get-MgAuditLogSignIn -Top 50
8

Security controls for PowerShell itself

MidExpert
Execution policyA safety belt, not a security boundary: use AllSigned or RemoteSignedguardrailCode signingSign internal scripts; trust only your publisher certificateintegrityConstrained modeApp Control (WDAC) or AppLocker forces ConstrainedLanguagestrongLoggingScript Block (4104), Module (4103), transcription to a sharevisibilityAMSIScans script content at run time, including deobfuscated codedetectionRemove v2Remove the PowerShell 2.0 engine where still present (downgrade)hardening

What the SOC watches

  • -EncodedCommand or -enc with long base64
  • IEX with DownloadString or Invoke-WebRequest
  • -ExecutionPolicy Bypass -WindowStyle Hidden
  • AMSI bypass strings in event 4104
  • powershell.exe -Version 2
Habit Run Invoke-ScriptAnalyzer -Path . -Recurse (PSScriptAnalyzer) in CI and test functions with Pester before you share them.

Key terms

Cmdlet
A PowerShell command named Verb-Noun, such as Get-Process.
Object pipeline
Commands pass .NET objects with properties, not plain text.
Advanced function
A function with [CmdletBinding()] that behaves like a built-in cmdlet.
Splatting
Passing parameters from a hashtable with @params for readable calls.
JEA
Just Enough Administration: remoting endpoints that allow only specific commands.
Script Block Logging
Event 4104: records the script content PowerShell actually runs.

Hands-on lab

Free account Create a free account or sign in to continue this course.

Knowledge check

Answer all five questions, then check your answers. Each answer comes with a short explanation.

1What does a PowerShell pipeline pass between commands?
2Is the execution policy a security boundary?
3Which makes errors catchable in try/catch?
4Which event ID records script block content?
5Why avoid CredSSP for remoting?

Further reading

Put it into practice

Use these ThreatAI tools to apply what you learned to your own environment.