MaisTools
Guides/

PowerShell Cheat Sheet

Quick PowerShell reference: cmdlets, flags, examples and the object pipeline, organised by section with instant search.

PowerShell Cheat Sheet

Cmdlets, object pipeline and one-liners

Navigation

Get-ChildItem

Lists files and directories. Aliases ls, gci, dir. -Recurse walks the tree, -Force includes hidden.

Flags-Recurse-Force-Filter-Include-Exclude-File-Directory-Depth
Example
Get-ChildItem
Get-ChildItem -Recurse -Filter *.ts
Get-ChildItem -Force
gci -Directory
Set-Location

Changes the current directory. Alias cd. Supports - for the previous path and ~ for home.

Flags-Path-LiteralPath-PassThru
Example
Set-Location s:\MaisTools
cd ~
cd ..
Get-Location

Shows the current path. Alias pwd.

Example
Get-Location
pwd
Test-Path

Checks if a path exists. Returns $true or $false.

Flags-PathType-IsValid-NewerThan-OlderThan
Example
Test-Path .\file.txt
Test-Path .\src -PathType Container
if (Test-Path .\dir) { 'existe' }
Push-Location / Pop-Location

Pushes the current directory onto a stack (Push) and returns to it later (Pop). Handy in scripts.

Flags-Path-StackName
Example
Push-Location C:\Temp
# ...trabalho aqui...
Pop-Location
Resolve-Path

Resolves a relative path to absolute, or the inverse with -Relative.

Flags-Relative-LiteralPath
Example
Resolve-Path .\src
Resolve-Path -Relative C:\Temp\file.txt

Files

New-Item

Creates files, directories or symlinks. -ItemType sets the type. -Force on an existing file truncates it.

Flags-ItemType-Path-Force-Value
Example
New-Item -ItemType File novo.txt
New-Item -ItemType Directory -Force pasta\sub
New-Item -ItemType SymbolicLink -Path link -Target target
Copy-Item

Copies files or directories. -Recurse for trees, -Force overwrites the destination.

Flags-Recurse-Force-Filter-Include-Exclude-Destination
Example
Copy-Item a.txt b.txt
Copy-Item -Recurse src\ dest\
Copy-Item *.log -Destination archive\
Move-Item

Moves or renames files and directories.

Flags-Force-Destination-Filter
Example
Move-Item old.txt new.txt
Move-Item *.log archive\
Remove-Item

Deletes files or directories. -Recurse -Force removes without confirmation (dangerous).

Flags-Recurse-Force-Filter-Include-Confirm
Example
Remove-Item file.txt
Remove-Item -Recurse -Force node_modules
Remove-Item *.tmp
Rename-Item

Renames files. Accepts a ScriptBlock in -NewName for bulk renaming.

Flags-NewName-Force
Example
Rename-Item old.txt new.txt
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '\.txt$','.md' }
Get-Item

Gets info about an item (Length, LastWriteTime, etc). Does not read content, only metadata.

Flags-Force-Stream
Example
Get-Item .\file.txt
(Get-Item file.txt).Length
Get-Item file.txt | Select-Object Name, Length, LastWriteTime

Content

Get-Content

Reads file contents. -TotalCount like head, -Tail like tail, -Wait follows like tail -f.

Flags-TotalCount-Tail-Wait-Raw-Encoding
Example
Get-Content file.txt
Get-Content file.txt -TotalCount 10
Get-Content file.txt -Tail 20
Get-Content app.log -Wait -Tail 100
Set-Content

Writes content to a file, overwriting it. -Encoding utf8 avoids the PS 5.1 default of UTF-16 with BOM.

Flags-Value-Encoding-Force-NoNewline
Example
Set-Content out.txt 'linha'
'a','b','c' | Set-Content lista.txt -Encoding utf8
Add-Content

Appends content to an existing file. Equivalent to >> in bash.

Flags-Value-Encoding
Example
Add-Content log.txt 'nova entrada'
Get-Date | Add-Content log.txt
Out-File

Redirects output to a file. -Append appends, -Encoding controls the encoding.

Flags-FilePath-Append-Encoding-Width
Example
Get-Process | Out-File processes.txt
Get-Service | Out-File -Append -Encoding utf8 services.log
Clear-Content

Empties a file's content without deleting the file.

Flags-Path-Force
Example
Clear-Content log.txt
Clear-Content *.tmp

Pipeline

Where-Object

Filters objects in the pipeline by a condition. Aliases ? and where. Supports shorthand Property -op Value.

Flags-FilterScript-Property
Example
Get-Process | Where-Object { $_.CPU -gt 10 }
Get-Service | Where-Object Status -eq Running
gci | ? { $_.Length -gt 1MB }
Sort-Object

Sorts objects by property. -Descending reverses, -Unique removes duplicates.

Flags-Property-Descending-Unique
Example
Get-Process | Sort-Object CPU -Descending
Get-ChildItem | Sort-Object Length -Descending
'b','a','c' | Sort-Object
Select-Object

Selects N objects from the pipeline or properties from each object. -ExpandProperty extracts the value.

Flags-First-Last-Skip-Property-ExpandProperty-Unique
Example
Get-Process | Select-Object -First 5
Get-Process | Select-Object Name, CPU, WS
Get-Service | Select-Object -ExpandProperty Name
ForEach-Object

Iterates the pipeline, applying a block to each object. Aliases % and foreach. -Parallel runs in parallel (PS 7+).

Flags-Process-Begin-End-Parallel
Example
Get-ChildItem | ForEach-Object { $_.Name.ToUpper() }
1..5 | %{ $_ * 2 }
$urls | ForEach-Object -Parallel { Invoke-WebRequest $_ }
Measure-Object

Counts, sums, averages, maxes or mins a collection. -Line, -Word, -Character for text.

Flags-Property-Sum-Average-Maximum-Minimum-Line-Word-Character
Example
Get-Process | Measure-Object -Property WS -Sum -Average
Get-Content file.txt | Measure-Object -Line
Get-ChildItem | Measure-Object
Group-Object

Groups objects by property. Useful to count occurrences or build dictionaries with -AsHashTable.

Flags-Property-NoElement-AsHashTable
Example
Get-Process | Group-Object ProcessName
Get-ChildItem | Group-Object Extension -NoElement

Search

Select-String

Searches patterns in strings or files. The grep equivalent. -Pattern accepts regex, -SimpleMatch disables it.

Flags-Pattern-Path-Recurse-CaseSensitive-NotMatch-Context-SimpleMatch
Example
Select-String 'TODO' *.ts
Select-String -Path src\*.ts -Pattern 'error' -CaseSensitive
Get-ChildItem -Recurse | Select-String 'API_KEY'
Get-Command

Shows available cmdlets with filters by name, module or type. (Get-Command npm).Source returns the path.

Flags-Name-Module-CommandType-All
Example
Get-Command npm
Get-Command *process*
(Get-Command npm).Source
Get-Command -Module Microsoft.PowerShell.Utility
Get-Member

Shows properties and methods of an object. Indispensable for exploring what a type can do.

Flags-MemberType-Static-Name
Example
Get-Process | Get-Member
(Get-Date) | Get-Member -MemberType Method
'abc' | Get-Member
Get-Help

Shows help for cmdlets or about_* topics. -Examples shows examples, -Online opens the web version.

Flags-Full-Examples-Online-Detailed-Parameter
Example
Get-Help Get-ChildItem
Get-Help Get-Process -Examples
Get-Help about_Variables
Get-Help Set-Content -Online

Variables

$variable

Variables start with $ and need no declaration. Support arrays (@()) and hashtables (@{}).

Example
$nome = 'Bruno'
$idade = 30
$lista = @(1, 2, 3)
$hash = @{ a = 1; b = 2 }
$env:

Reads and sets environment variables. Get-ChildItem env: lists them all. Changes only last for the session.

Example
$env:PATH
$env:USERPROFILE
$env:DEBUG = 'true'
Get-ChildItem env:
$null

Null value. In comparisons place $null on the left ($null -eq $x) to avoid surprises with arrays.

Example
if ($null -eq $var) { 'vazio' }
$lista = @($null, 1, 2)
[string]::IsNullOrEmpty($x)
[type]

Type casting with [type]. Works for int, string, datetime, typed arrays, regex.

Example
[int]'42'
[datetime]'2026-01-15'
[int[]]$nums = 1,2,3
[regex]::Escape($pattern)
$global: / $script: / $local:

Sets variable scope: global (whole session), script (this file) or local (this function).

Example
$global:config = @{}
$script:contador = 0
function f { $local:tmp = 1 }

Strings

"$var" interpolation

Double quotes expand $var and $(expr). Single quotes are literal and expand nothing.

Example
$nome = "Bruno"
"Olá $nome"
"Caminho: $($obj.Property)"
'literal $nome'  # sem expansão
@"..."@ / @'...'@

Multi-line strings (here-strings). @"..."@ expands variables, @'...'@ is literal. Closing token must be at column 0.

Example
@"
linha 1 com $nome
linha 2
"@

@'
literal $nome
'@
-f (format)

Printf-style format operator. Supports numbers, dates and alignment ({0,5:N2}).

Example
'{0} tem {1} anos' -f $nome, $idade
'{0:N2}' -f 1234.5678  # 1,234.57
'{0:yyyy-MM-dd}' -f (Get-Date)
-replace / -split / -join

String operations: -replace uses regex, -split splits into an array, -join joins an array into a string.

Example
'abc123' -replace '\d', 'X'
'a,b,c' -split ','
@('a','b','c') -join ', '

Control

if / elseif / else

Conditional structure. Uses PowerShell operators (-eq, -lt) instead of == or <.

Example
if (Test-Path .\file) {
  'existe'
} elseif ($x -gt 0) {
  'positivo'
} else {
  'outro'
}
switch

Alternative to chained if. -Regex and -Wildcard enable patterns, -File reads lines from a file.

Flags-Regex-Wildcard-CaseSensitive-File
Example
switch ($x) {
  1 { 'um' }
  2 { 'dois' }
  default { 'outro' }
}

switch -Regex ($texto) {
  '^\d+$' { 'número' }
}
foreach / for / while

Loops over collections (foreach), with counter (for), while condition (while), or at least once (do/while).

Example
foreach ($f in Get-ChildItem) { $f.Name }
for ($i = 0; $i -lt 5; $i++) { $i }
while ($cond) { ... }
do { ... } while ($cond)
try / catch / finally

Error capture. To catch non-terminating errors use -ErrorAction Stop on the cmdlet.

Example
try {
  Cmdlet -ErrorAction Stop
} catch [System.IO.IOException] {
  Write-Error "IO: $_"
} catch {
  Write-Error $_
} finally {
  Cleanup
}
break / continue / return

break exits the loop, continue skips to the next iteration, return exits the function.

Example
foreach ($x in 1..10) {
  if ($x -eq 5) { break }
  if ($x % 2 -eq 0) { continue }
  $x
}

Operators

-eq -ne -lt -gt -le -ge

Comparison operators. There is no == in PowerShell, always use -eq, -ne, -lt, -gt, -le, -ge.

Example
$x -eq 5     # igual
$x -ne 5     # diferente
$x -lt 10    # menor
$x -gt 0     # maior
$x -le 10    # menor ou igual
$x -ge 0     # maior ou igual
-like / -match / -contains / -in

Other operators: -like uses wildcards, -match uses regex, -contains tests membership in an array, -in is the inverse.

Example
'file.txt' -like '*.txt'         # wildcards
'abc123' -match '\d+'             # regex
@(1,2,3) -contains 2              # pertença
2 -in @(1,2,3)                   # pertença (invertido)
-and / -or / -not / -xor

Logical operators. -and, -or, -not, -xor. ! is an alias for -not.

Example
($x -gt 0) -and ($x -lt 10)
($a -eq 1) -or ($b -eq 2)
-not (Test-Path .\file)
!$cond

Processes

Get-Process

Lists processes with properties (CPU, WS, Id, ProcessName). With no arguments, lists all.

Flags-Name-Id-IncludeUserName-Module
Example
Get-Process
Get-Process node, chrome
Get-Process -Id 1234
Stop-Process

Stops processes by name or Id. -Force avoids confirmation. Can receive objects from the pipeline.

Flags-Name-Id-Force-PassThru
Example
Stop-Process -Name node
Stop-Process -Id 1234 -Force
Get-Process node | Stop-Process
Start-Process

Starts a program. -Wait blocks until it finishes, -NoNewWindow runs in the current console, -Verb RunAs elevates.

Flags-FilePath-ArgumentList-WorkingDirectory-Wait-NoNewWindow-Verb
Example
Start-Process notepad
Start-Process npm -ArgumentList 'run','dev'
Start-Process pwsh -Verb RunAs
Wait-Process

Waits for a process to end. -Timeout aborts after N seconds.

Flags-Name-Id-Timeout
Example
Wait-Process -Name node
Wait-Process -Id 1234 -Timeout 30
& (call operator)

Runs a command or script. Required when the path has spaces or to call executables dynamically.

Example
& 'C:\Program Files\App\app.exe' arg1 arg2
& $cmd
& { Get-Process; Get-Service }

Data

ConvertFrom-Json

Converts JSON to PowerShell objects. -AsHashtable returns a hashtable (PS 6+) instead of PSCustomObject.

Flags-AsHashtable-Depth-NoEnumerate
Example
Get-Content pkg.json | ConvertFrom-Json
'{"a":1}' | ConvertFrom-Json
$obj.dependencies
ConvertTo-Json

Converts PowerShell objects to JSON. -Depth controls the depth (default 2, often too low).

Flags-Depth-Compress-AsArray
Example
$obj | ConvertTo-Json -Depth 10
@{a=1; b=2} | ConvertTo-Json -Compress
Get-Process | Select-Object Name,Id | ConvertTo-Json
Import-Csv

Reads a CSV into objects with properties. -Delimiter for ; or others, -Header if the file has no header row.

Flags-Path-Delimiter-Header-Encoding
Example
Import-Csv users.csv
Import-Csv data.csv -Delimiter ';' -Encoding utf8
Export-Csv

Exports objects to CSV. -NoTypeInformation removes the type line at the top (default in PS 6+).

Flags-Path-Delimiter-NoTypeInformation-Append-Encoding
Example
Get-Process | Export-Csv processes.csv -NoTypeInformation
$data | Export-Csv out.csv -Encoding utf8 -Delimiter ';'

Network

Invoke-WebRequest

Full HTTP client. Returns the response as an object with .Content, .StatusCode, .Headers. Alias iwr.

Flags-Uri-Method-Headers-Body-OutFile-UseBasicParsing
Example
Invoke-WebRequest https://example.com
iwr https://api.example.com -OutFile data.json
iwr -Uri $url -Method POST -Body $body
Invoke-RestMethod

HTTP client that automatically parses JSON or XML into objects. Most common for REST APIs. Alias irm.

Flags-Uri-Method-Headers-Body-ContentType
Example
Invoke-RestMethod https://api.github.com/users/octocat
irm $url -Method POST -Body ($obj | ConvertTo-Json) -ContentType 'application/json'
Test-NetConnection

Tests TCP connectivity to a host and port. Windows only. On Linux/macOS use Test-Connection -TcpPort (PS 7+).

Flags-ComputerName-Port-TraceRoute-CommonTCPPort
Example
Test-NetConnection google.com -Port 443
Test-NetConnection -ComputerName 8.8.8.8 -TraceRoute
Test-Connection

Ping equivalent. -Count limits packets, -Quiet returns just $true or $false.

Flags-ComputerName-Count-Quiet-Delay
Example
Test-Connection google.com -Count 4
Test-Connection 8.8.8.8 -Quiet  # bool

Modules

Get-Module

Lists modules. -ListAvailable shows everything installed, not just what is currently loaded.

Flags-ListAvailable-Name-All
Example
Get-Module
Get-Module -ListAvailable
Get-Module -Name Pester
Import-Module

Loads a module into the current session. -Force reloads it if already imported.

Flags-Name-Force-Prefix-Function
Example
Import-Module Pester
Import-Module .\MeuModulo.psm1 -Force
Install-Module

Installs modules from the PowerShell Gallery. -Scope CurrentUser avoids needing admin rights.

Flags-Name-Scope-Force-AllowClobber-RequiredVersion
Example
Install-Module Pester -Scope CurrentUser
Install-Module Az -Force -AllowClobber
Find-Module

Searches for modules available on the PowerShell Gallery.

Flags-Name-Tag-Filter
Example
Find-Module Az*
Find-Module -Tag azure

Advanced

Start-Job / Receive-Job

Runs code in the background. Receive-Job collects the results, -Wait blocks until ready.

Flags-ScriptBlock-Name-ArgumentList
Example
$j = Start-Job { Get-Process }
Receive-Job $j -Wait -AutoRemoveJob
Get-Job | Remove-Job
Start-ThreadJob

Lightweight thread-based background jobs (faster than Start-Job). Built into PS 7+, on 5.1 install via Install-Module ThreadJob.

Flags-ScriptBlock-ThrottleLimit-StreamingHost
Example
$j = Start-ThreadJob { 1..10 | %{ $_ * 2 } }
$urls | ForEach-Object -Parallel { iwr $_ } -ThrottleLimit 5
Measure-Command

Measures execution time of a block. Returns a TimeSpan with TotalSeconds, TotalMilliseconds, etc.

Flags-Expression
Example
Measure-Command { Get-ChildItem -Recurse }
(Measure-Command { ./script.ps1 }).TotalSeconds
Invoke-Command

Runs commands on a remote machine via WinRM. Supports persistent sessions with -Session.

Flags-ComputerName-ScriptBlock-Session-Credential-AsJob
Example
Invoke-Command -ComputerName server01 -ScriptBlock { Get-Service }
Invoke-Command -Session $s -ScriptBlock { hostname }
Start-Sleep

Pauses execution for N seconds or milliseconds.

Flags-Seconds-Milliseconds
Example
Start-Sleep -Seconds 5
Start-Sleep -Milliseconds 250

Reference

Object pipeline

Unlike bash, the PowerShell pipeline carries objects with properties and methods. Each cmdlet can access .Length, .Name, .CPU directly without parsing text.

Example
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5
# objectos fluem entre comandos com propriedades preservadas

Get-ChildItem | Where-Object Length -gt 1MB
# Each item retains its full type — pode aceder a .Length, .Name, etc.

Get-Service | Group-Object Status | Format-Table Name, Count
File encoding

The default encoding changed between versions. Knowing which one is active prevents BOMs and garbled characters in scripts and logs shared with other tools.

PowerShell 5.1
  • Default varies by cmdlet: Out-File uses UTF-16 LE with BOM, Set-Content uses Default (ANSI/Windows-1252).
  • Neither produces UTF-8 without -Encoding. Always pass -Encoding utf8 for files shared with Unix tools.
PowerShell 7+
  • Default: UTF-8 without BOM.
  • Behaviour aligned with the broader ecosystem. In both, -Encoding utf8 guarantees UTF-8.
Example
Set-Content file.txt 'texto' -Encoding utf8
Out-File log.txt -Encoding utf8 -InputObject $data
[System.IO.File]::WriteAllText('file.txt', 'texto', [System.Text.UTF8Encoding]::new($false))
Errors and exit codes

PowerShell distinguishes terminating from non-terminating errors. Cmdlets fail silently by default, use -ErrorAction Stop to force try/catch to catch them.

-ErrorAction
  • Continuedefault behaviour, prints the error and keeps going.
  • Stopturns it into a terminating error (catchable).
  • SilentlyContinuehides the error but $? becomes $false.
  • Ignorehides and does not record it in $Error.
Status
  • $?$true if the last command succeeded.
  • $LASTEXITCODEexit code of the last native executable.
  • $Error[0]object of the last error recorded.
Example
try {
  Get-Item .\file -ErrorAction Stop
} catch [System.IO.FileNotFoundException] {
  Write-Warning "ficheiro não encontrado"
} catch {
  Write-Error $_.Exception.Message
}

# verificar saída de processo nativo
git status
if ($LASTEXITCODE -ne 0) { throw "git falhou" }
Differences between 5.1 and 7+

Windows PowerShell 5.1 (powershell.exe) and PowerShell 7+ (pwsh.exe) have different syntax and features. These details break scripts when moving between versions.

  • A && B / A || BOperators && and || only exist in PS 7+. On 5.1 use: A; if ($?) { B }
  • $x ? a : bTernary operator ?: only exists in PS 7+. On 5.1 use if/else.
  • $x ?? yNull-coalescing operator ?? only exists in PS 7+.
  • ConvertFrom-Json -AsHashtableConvertFrom-Json -AsHashtable only exists in PS 6+.
  • ForEach-Object -ParallelForEach-Object -Parallel only exists in PS 7+.
20 essential one-liners

Common combinations for automation and administration. Each solves a specific task in a single pipeline.

  • 01.Find files larger than 100MB recursively.
    Get-ChildItem -Recurse -File | Where-Object Length -gt 100MB
  • 02.List the 10 largest files in the current directory.
    Get-ChildItem | Sort-Object Length -Descending | Select-Object -First 10
  • 03.Show the 10 processes consuming the most memory.
    Get-Process | Sort-Object WS -Descending | Select-Object -First 10
  • 04.Show the 10 processes consuming the most CPU.
    Get-Process | Sort-Object CPU -Descending | Select-Object -First 10
  • 05.Count total files recursively.
    Get-ChildItem -Recurse -File | Measure-Object | Select-Object -ExpandProperty Count
  • 06.Delete every .tmp file recursively.
    Get-ChildItem -Recurse -Filter *.tmp | Remove-Item
  • 07.Search for TODO across all TypeScript files.
    Get-ChildItem -Recurse -File | Where-Object Extension -in '.ts','.tsx' | Select-String 'TODO'
  • 08.Get the current machine's external public IP.
    (Invoke-WebRequest ifconfig.me -UseBasicParsing).Content.Trim()
  • 09.List listening TCP ports with the owning process.
    Get-NetTCPConnection -State Listen | Select-Object LocalAddress,LocalPort,OwningProcess
  • 10.Follow a log live starting from the last 100 lines.
    Get-Content app.log -Wait -Tail 100
  • 11.Get current date and time in a filename-ready format.
    Get-Date -Format 'yyyy-MM-dd_HH-mm-ss'
  • 12.Create a zip backup with the date in the filename.
    Compress-Archive -Path .\src -DestinationPath "backup-$(Get-Date -Format yyyy-MM-dd).zip"
  • 13.Format and print JSON expanded for maximum readability.
    Get-Content data.json | ConvertFrom-Json | ConvertTo-Json -Depth 10
  • 14.List all environment variables sorted by name.
    Get-ChildItem env: | Sort-Object Name
  • 15.List every service currently running.
    Get-Service | Where-Object Status -eq 'Running'
  • 16.Test whether a TCP port is open on a remote host.
    Test-NetConnection google.com -Port 443
  • 17.Show free space on every disk on the system.
    Get-Volume | Select-Object DriveLetter, SizeRemaining, Size
  • 18.Show the last 20 commands from the session history.
    Get-History | Select-Object -Last 20
  • 19.Show the full path of a command (which equivalent).
    (Get-Command npm).Source
  • 20.List files modified in the last 7 days.
    Get-ChildItem -Recurse | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) }