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
- 0Start here: PowerShell, installation and the course projectJuniorMidExpert20 min · 1 exercises
- 1Discovering commandsJuniorMidExpert20 min · 2 exercises
- 2Files, folders and providersJuniorMidExpert20 min · 3 exercises
- 3Objects and the pipelineJuniorMidExpert25 min · 2 exercises
- 4Variables, types and operatorsJuniorMidExpert25 min · 2 exercises
- 5Control flow: decisions and loopsJuniorMidExpert25 min · 3 exercises
- 6Functions, scripts and modulesJuniorMidExpert25 min · 2 exercises
- 7Errors, safe changes and debuggingJuniorMidExpert20 min · 1 exercises
- 8Text, regular expressions and data formatsJuniorMidExpert20 min · 3 exercises
- 9Windows administration, event logs and remoting (Windows lab)JuniorMidExpert25 min · 1 exercises
- 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.
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.
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.
Quick check: Which name follows the PowerShell convention?
An approved verb, a dash, then a singular noun. Get-Verb lists the approved verbs.
| Symptom | Likely cause | Fix |
|---|---|---|
| two different PowerShell windows on Windows | Windows PowerShell 5.1 and PowerShell 7 are separate programs | use 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.
winget install --id Microsoft.PowerShell --source wingetOpen Windows Terminal and choose the 'PowerShell' profile (7.x). Module 9 needs Windows: a Windows 10/11 or Windows Server virtual machine is ideal.
brew install --cask powershell
pwshFollow Microsoft's 'Install PowerShell on Linux' page for your distribution (Ubuntu: the Microsoft package repository, or sudo snap install powershell --classic). Start it with pwsh.
$PSVersionTableShow the PowerShell version (an automatic variable).Read-only$PSVersionTable.PSVersion$PSVersionTable.PSVersion.ToString()7.5.4
Any 7.x version is fine.
| Symptom | Likely cause | Fix |
|---|---|---|
| 'pwsh' is not recognized | the terminal was opened before installing | open a new terminal |
| 'running scripts is disabled on this system' | Windows execution policy | Set-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.
PS C:\Users\rana>).PS /home/rana/ps-lab> Get-ChildItem -Path . -Filter *.csv | Select-Object Name, Length. is the current folder; *.csv is a wildcard.Name Length ---- ------ users.csv 168
Quick check: In Get-Service -Name W32Time, what is W32Time?
-Name is the parameter; W32Time is its value.
Exercise 1Junior
A colleague's note says gci . *.log. Rewrite it with the full cmdlet and parameter names.
Worked solution
Get-ChildItem -Path . -Filter *.loggci 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.
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, LengthName Length ---- ------ auth.log 585 users.csv 168
| Symptom | Likely cause | Fix |
|---|---|---|
| '>>' continuation prompt | the here-string was not closed | '@ must be at the very start of its line; press Ctrl+C and paste again |
Discovering commands
Goal: Find any command, read its help and syntax, and inspect what it returns.
Free account Create a free account or sign in to continue this course.
Files, folders and providers
Goal: Navigate and manage files with safety switches, read and write text, and browse other data stores as drives.
Free account Create a free account or sign in to continue this course.
Objects and the pipeline
Goal: Turn data into objects, then filter, sort, shape, group and count them in a pipeline.
Free account Create a free account or sign in to continue this course.
Variables, types and operators
Goal: Store values, build strings, use arrays and hashtables, convert types and add calculated properties.
Free account Create a free account or sign in to continue this course.
Control flow: decisions and loops
Goal: Make scripts decide with if and switch, and repeat with foreach, ForEach-Object and while.
Free account Create a free account or sign in to continue this course.
Functions, scripts and modules
Goal: Package logic as advanced functions that behave like cmdlets, save them as scripts, and share them as a module.
Free account Create a free account or sign in to continue this course.
Errors, safe changes and debugging
Goal: Handle failures deliberately, make changes that support -WhatIf, and find bugs quickly.
Free account Create a free account or sign in to continue this course.
Text, regular expressions and data formats
Goal: Search logs with regular expressions, extract fields, and move data between CSV, JSON and HTML.
Free account Create a free account or sign in to continue this course.
Windows administration, event logs and remoting (Windows lab)
Goal: Query services, processes and security events, run commands on many machines, and schedule the audit.
Free account Create a free account or sign in to continue this course.
Cheat sheet, assessment and expert challenge
Goal: Consolidate the syntax on one page, then build and use the finished audit tool on your own.
Free account Create a free account or sign in to continue this course.
Quick reference (the cheat-sheet lessons and the PDF content)
Three commands that teach you the rest
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).LastWriteTimeNaming 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 -WhatIfpreviews a change;-Confirmasks first- Version check:
$PSVersionTable
The object pipeline
Everyday syntax
| Task | PowerShell |
|---|---|
| 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 items | foreach ($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 / CSV | Get-Content x.json -Raw | ConvertFrom-Json; Import-Csv users.csv |
| Splatting | $p = @{ Path = $f; Encoding = 'utf8' }; Set-Content @p -Value $t |
An advanced function: the unit of reuse
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 -DescWhy this shape
[CmdletBinding()]gives-Verbose,-ErrorActionfor free- Typed, validated parameters reject bad input early
process {}streams pipeline input-FilterHashtablefilters on the server, fast- Returns objects, so callers can sort, group or export
-ErrorAction Stopmakes errors catchable
Error handling
| Setting | Effect |
|---|---|
$ErrorActionPreference = 'Stop' | Treat errors as terminating in the script |
-ErrorAction SilentlyContinue | Suppress: use rarely, and log why |
try / catch / finally | Handle terminating errors; clean up in finally |
$LASTEXITCODE | Exit code of native tools (git, robocopy) |
Set-StrictMode -Version Latest | Uninitialized variables become errors |
$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)Remote administration
# 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-Credentialor the SecretManagement module - Avoid CredSSP: it exposes credentials to the remote host
- Log remoting with Script Block Logging
Admin tasks cookbook
| Task | Command |
|---|---|
| Local admins | Get-LocalGroupMember -Group Administrators |
| New services installed (event 7045) | Get-WinEvent -FilterHashtable @{LogName='System';Id=7045} -MaxEvents 20 |
| Listening ports with process | Get-NetTCPConnection -State Listen | Select LocalPort,OwningProcess |
| Scheduled tasks not from Microsoft | Get-ScheduledTask | ? TaskPath -notlike '\Microsoft\*' |
| File hash | Get-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-ins | Connect-MgGraph -Scopes AuditLog.Read.All; Get-MgAuditLogSignIn -Top 50 |
Security controls for PowerShell itself
What the SOC watches
-EncodedCommandor-encwith long base64IEXwithDownloadStringorInvoke-WebRequest-ExecutionPolicy Bypass -WindowStyle Hidden- AMSI bypass strings in event 4104
powershell.exe -Version 2
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.
Further reading
- PowerShell documentation learn.microsoft.com
- PSScriptAnalyzer learn.microsoft.com
- Just Enough Administration learn.microsoft.com
Put it into practice
Use these ThreatAI tools to apply what you learned to your own environment.