Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 34 ยท Practice and Review

PowerShell Cheat Sheet

A one-page PowerShell cheat sheet: syntax, operators, quoting, collections, common cmdlets, errors, remoting and a table of the pitfalls that catch everyone.

This page packs the whole course into compact tables: the syntax you type every day, the operators, the cmdlets worth knowing by heart, and a list of pitfalls that catch almost everyone once. Keep it open while you write scripts, while you work through the practice exercises, or right before an interview.

Everything here is real PowerShell and is read-only: PowerShell cannot run on this site. Two small JavaScript stand-ins at the end (a command finder and a model of -like and -f) let you try ideas. Items that only exist in PowerShell 7 say so; everything else works in Windows PowerShell 5.1 and PowerShell 7.

Five habits that prevent most bugs

Discover Get-Command, Get-Help, Get-Member.
Filter early Where-Object first, Format last.
Preview -WhatIf before anything destructive.
Stop on error -ErrorAction Stop inside try.

Spell out cmdlet names in scripts; aliases are for the prompt.

1 / 2

Not sure what a command does? Get-Help <name> -Examples shows usage, Get-Command *keyword* finds commands and <object> | Get-Member lists what an object can do. See Getting Help.

Discover and get help

Command What it does
Get-Command *service* Find commands by name pattern (-Noun, -Verb, -Module narrow it).
Get-Help Get-Process -Examples Examples; -Full shows everything, -Online opens the web page.
Update-Help Download current help files (run as administrator on Windows).
Get-Member Properties and methods of the objects that come in through the pipeline.
Get-Verb The approved verbs for command names.
Get-Alias / Get-Alias -Definition Get-ChildItem List aliases, or find the aliases of a command.
$PSVersionTable Edition and version of the running PowerShell.
Get-Module -ListAvailable Modules installed on this machine.
Show-Command Get-Process A small form for a command's parameters.

Variables, types and automatic variables

Syntax Meaning
$name = 'Ada' Create or assign a variable; names are case-insensitive.
[int]$count = 5 Constrain a variable to a type; later assignments are converted or fail.
[datetime]'2025-03-01' Cast (convert) a value; also [string], [double], [bool], [pscustomobject].
$x.GetType().Name The type name of a value.
$null No value. Compare as $null -eq $x.
$_ / $PSItem The current object in Where-Object, ForEach-Object and similar script blocks.
$? $true if the last command succeeded.
$LASTEXITCODE Exit code of the last native program.
$args Unnamed arguments of a function or script without a param block.
$PSScriptRoot Folder of the running script.
$PROFILE Path of your profile script.
$Error List of recent errors, newest first.
$env:PATH An environment variable.
$HOME Your home folder.
$true, $false Boolean values.
$script:x, $global:x, $using:x Scope modifiers; $using: reads a local variable inside a remote command or job.

See Variables and Types.

Strings and quoting

Syntax Meaning
'literal $x' Single quotes: no expansion. Use '' for a quote inside.
"Hi $name" Double quotes: variables expand.
"Sum: $($a + $b)" $( ) subexpression, any code inside a string.
"$($obj.Name)" Property access in a string needs a subexpression.
Backtick escape Inside double quotes the backtick is the escape character: backtick + t is a tab, backtick + n a newline, backtick + double quote a quote mark.
@' ... '@ / @" ... "@ Here-strings: multi-line, literal or expanding; the closing mark starts a line.
'{0} is {1:N2}' -f 'pi', 3.14159 Format operator (.NET composite formatting).
'a,b,c' -split ',' Split a string into an array.
'a','b' -join '-' Join an array into a string.
'abc' -replace 'b', 'X' Regex replace (case-insensitive).
[string]::IsNullOrWhiteSpace($s) True for $null, empty and blank strings.
$s.ToUpper(), .Trim(), .Contains('x') Methods of the .NET string.

See Strings, Quoting and Here-Strings.

Operators

Operator Meaning
-eq -ne -gt -ge -lt -le Equal, not equal, greater, greater or equal, less, less or equal.
-like -notlike Wildcards: * any run, ? one character, [a-c] a range.
-match -notmatch Regular expression; sets $Matches for a single string.
-contains -notcontains Collection on the left contains a value.
-in -notin Value on the left is in the collection on the right.
-and -or -xor -not (!) Logical operators.
-is -isnot -as Type test and safe conversion.
-band -bor -bxor -shl -shr Bitwise operators.
-ceq, -cne, -clike, -cmatch Case-sensitive versions (default is case-insensitive).
.. Range: 1..5.
$a ?? $b Null-coalescing (PowerShell 7): $b if $a is $null.
$a ? 'yes' : 'no' Ternary (PowerShell 7).
$a ??= 5 Assign only if $null (PowerShell 7).
&&, || Run the next pipeline only on success or failure (PowerShell 7).
&, . Call operator (run a command from a string or script block); dot-source (run in the current scope).
@( ), @{ }, $( ) Array, hashtable, subexpression.

An array on the left of -eq, -like or -match makes the operator a filter that returns the matching elements. See Operators and Comparison.

Arrays, hashtables and objects

Syntax Meaning
$a = 1, 2, 3 / @(1,2,3) / @() Array; the last form is an empty array.
$a[0], $a[-1], $a[1..2] First item, last item, a slice.
$a.Count Number of elements (also works on a single object).
$a += 4 Creates a new array: slow in loops.
$list = [System.Collections.Generic.List[string]]::new() A growable, typed list; use .Add().
$h = @{ Name = 'Ada'; Age = 36 } Hashtable; keys are case-insensitive.
$h.Name, $h['Name'] Read a value.
$h.Remove('Age'), $h.ContainsKey('Name') Edit and test.
[ordered]@{ A = 1; B = 2 } Hashtable that keeps insertion order.
[pscustomobject]@{ Name = 'Ada'; Age = 36 } Create an object (the usual way to make a record).
$params = @{ Path = '.'; Recurse = $true }; Get-ChildItem @params Splatting.
$obj | Select-Object * Show all properties of an object.
$obj | Add-Member -NotePropertyName X -NotePropertyValue 1 Add a property to an existing object.

See Arrays and Hashtables and Objects, Properties and Methods.

Pipeline cmdlets

Cmdlet Typical use
Where-Object { $_.Size -gt 1MB } Keep objects that pass a test. Short form: Where-Object Size -gt 1MB.
Select-Object Name, Size Choose properties; -First 5, -Last 5, -Unique, -ExpandProperty Name.
Select-Object @{ Name = 'MB'; Expression = { $_.Size / 1MB } } Calculated property.
Sort-Object Size -Descending Sort by one or more properties.
Group-Object Extension Group; result has Name, Count, Group.
Measure-Object Size -Sum -Average -Maximum Statistics; without -Property it counts.
ForEach-Object { $_ * 2 } Run a block for each object; -Parallel in PowerShell 7.
Tee-Object -FilePath out.txt Write to a file and keep passing objects on.
Compare-Object $a $b Differences between two collections.
Format-Table -AutoSize / Format-List * Display only; always last.
Out-File, Out-String, Out-Null Write to a file, convert to text, discard.

See The Pipeline, Where-Object, Select-Object and Sort-Object and Formatting and Output.

Control flow and functions

Syntax Meaning
if (...) { } elseif (...) { } else { } Conditional.
switch ($x) { 'a' { } default { } } Multi-branch; -Wildcard, -Regex, -CaseSensitive options.
foreach ($i in $list) { } Loop over a collection in memory.
for ($i = 0; $i -lt 10; $i++) { } Counted loop.
while (...) { } / do { } while (...) / do { } until (...) Condition loops.
break, continue, return Leave the loop, skip an iteration, leave the function.
function Get-Thing { param([string]$Name = 'x') ... } Define a function.
[CmdletBinding()] Advanced function: common parameters, strict binding.
[Parameter(Mandatory, ValueFromPipeline)] Parameter attributes.
[ValidateSet('a','b')], [ValidateRange(1,10)], [ValidateNotNullOrEmpty()] Input checks done at binding time.
begin { } process { } end { } Pipeline-aware stages.
[CmdletBinding(SupportsShouldProcess)] Adds -WhatIf and -Confirm; call $PSCmdlet.ShouldProcess(...).
. .\script.ps1 Dot-source: run in the current scope.
& .\script.ps1 -Param 1 Call operator: run in a child scope.

See Conditionals and Loops, Functions and Parameters and Advanced Functions.

Files, data and text

Command What it does
Get-ChildItem -Path . -Recurse -File -Filter *.log List files; alias dir, ls, gci.
Get-Item, Test-Path, Resolve-Path Inspect or check a path.
Join-Path $a 'b', Split-Path $p -Leaf Build and take apart paths without string tricks.
New-Item -ItemType Directory -Path x Create a folder (or -ItemType File).
Copy-Item, Move-Item, Rename-Item, Remove-Item File operations; add -WhatIf to preview, -Recurse for folders.
Get-Content file.txt, -Tail 20, -Wait, -Raw Read lines, last lines, follow, or the whole file as one string.
Set-Content, Add-Content, Out-File Write, append, write the display text. Set -Encoding yourself.
Import-Csv / Export-Csv -NoTypeInformation CSV to objects and back (every value is a string).
ConvertFrom-Json / ConvertTo-Json -Depth 5 JSON to objects and back. The default depth is 2.
Export-Clixml / Import-Clixml Save and restore full objects.
Select-String -Path *.log -Pattern 'ERROR' Search text files with regex; returns match objects.
[regex]::Matches($s, '\d+') All regex matches of a string.
Get-FileHash file -Algorithm SHA256 Checksum of a file.

See Working with Files and Folders, CSV, JSON and XML and Regular Expressions and Text Processing.

Errors

Syntax Meaning
try { } catch { } finally { } Handle terminating errors; finally always runs.
catch [System.IO.IOException] { } Catch one exception type.
$_.Exception.Message Readable error text inside catch.
-ErrorAction Stop Make a non-terminating error terminating (per command).
$ErrorActionPreference = 'Stop' The same for the whole scope.
-ErrorVariable errs Collect errors in a variable (use +errs to append).
throw 'message' Raise a terminating error.
Write-Error, Write-Warning, Write-Verbose, Write-Debug Other streams; -Verbose shows verbose output.
$Error[0] The latest error record.
if ($LASTEXITCODE -ne 0) { } Check native programs.

See Errors, try/catch and ErrorAction.

Modules, scripts, remoting and the system

Command What it does
Import-Module Name / Get-Module Load and list modules (most auto-load).
Install-Module Name -Scope CurrentUser Install from the PowerShell Gallery (PowerShellGet); Install-PSResource is the newer tool.
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser Windows only; a safety net, not a security boundary.
Get-Process, Stop-Process -Id 123 -WhatIf Processes.
Get-Service, Restart-Service -Name x Windows services.
Get-CimInstance Win32_OperatingSystem System information on Windows (replaces the older WMI cmdlets).
Enter-PSSession -ComputerName pc / Invoke-Command Interactive and one-to-many remoting.
Start-Job { ... } / Receive-Job / Wait-Job Background jobs (separate process); Start-ThreadJob in PowerShell 7.
Invoke-RestMethod -Uri $url Call a web API and get objects back from JSON.
Invoke-WebRequest -Uri $url Fetch a page with headers and status.
Start-Transcript -Path log.txt Record the session.

See Scripts and Execution Policy, Modules and Profiles, Processes, Services and the System, Remoting, Jobs and Parallelism and Web Requests and REST APIs.

Pitfalls at a glance

Pitfall What happens Do this instead
Formatting before filtering Format-Table | Export-Csv writes formatting objects. Format last; use Select-Object for data.
Imported CSV values Everything is a string; '520' sorts after '50400'. Cast to [int], [double] or [datetime].
Stray output in functions $set.Add($x) leaks True or False into the result. [void]$set.Add($x) or $null = ....
Array on the left of -eq Returns matches, not a Boolean. $null -eq $x, -contains, -in.
$a += $x in loops Copies the whole array every time. Use List[T] or collect from foreach.
ConvertTo-Json depth Nested objects are cut off at depth 2. -Depth 5 (or what you need).
Single quotes in strings 'Hi $name' prints $name. Double quotes, or -f.
"$obj.Name" Prints the object, then .Name. "$($obj.Name)".
Non-terminating errors catch never runs. -ErrorAction Stop.
Native program fails No error is raised. Check $LASTEXITCODE.
Square brackets in paths Get-Item 'file[1].txt' treats the brackets as a wildcard set. Use -LiteralPath for exact names.
Aliases in scripts Hard to read, can differ between systems. Full cmdlet and parameter names.
Invoke-Expression Runs any text as code: injection risk. Call operator &, splatting, parameters.
Deleting without a preview Wrong filter, wrong folder, data gone. Run -WhatIf first.
Execution policy as protection Easy to bypass. Permissions, signing, application control and logging.
Backslash paths Fail on Linux and macOS. Join-Path, or forward slashes.
Default encodings differ Windows PowerShell 5.1 and PowerShell 7 write different encodings. Pass -Encoding utf8 explicitly.

Two stand-ins

These small models run in your browser. They are JavaScript, not PowerShell, but they implement the rules from the tables above.

The first is a command finder. It holds a short list of common commands and aliases and searches names and descriptions, like a tiny Get-Command with Get-Help text.

JS Stand-in: a tiny command finder

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Add a command of your own to the list, then search for a word from its description.

The second models two things from the tables: -like wildcards and the -f format operator for the common , {0,8}, {0,-8} and {0:N2} forms. It is a model, not the real .NET formatter.

JS Stand-in: -like wildcards and the -f format operator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first block prints which names each wildcard keeps (note that *.txt matches both report.txt and REPORT.TXT, while -clike keeps only the lower-case one). The second block shows the aligned columns that -f produces.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which operator tests whether a value is in a collection when the collection is on the right?

    -in puts the value on the left and the collection on the right. -contains is the same test with the sides swapped.
  2. 2. What does "$obj.Name" print inside a double-quoted string?

    Only the simple variable is expanded. Use "$($obj.Name)" for a property access.
  3. 3. Which pair makes a function ready for -WhatIf?

    SupportsShouldProcess adds -WhatIf and -Confirm; ShouldProcess is where your function asks whether to act.
  4. 4. Why is ConvertTo-Json -Depth worth setting?

    Without -Depth, levels beyond 2 are flattened into text. Set the depth that matches your data.

Summary

  • Discover with Get-Command, Get-Help and Get-Member; filter early, format last.
  • Operators are words and case-insensitive; an array on the left turns -eq into a filter; -contains and -in answer yes or no.
  • Imported CSV values are strings; cast them. Functions return everything they output.
  • Make errors catchable with -ErrorAction Stop, check $LASTEXITCODE for native programs, and preview destructive commands with -WhatIf.
  • Use full cmdlet names, Join-Path and explicit encodings in scripts you share.
  • Execution policy is a safety net; real protection is permissions, logging and secret management.

You have reached the end of the PowerShell course. Revisit the practice exercises and interview questions to keep your skills sharp, or start again from What Is PowerShell?.