Basics
Commands & Help
Get-Help Get-Process # show help for cmdlet Get-Help Get-Process -Online # open online docs Get-Command *service* # find commands by name Get-Alias ls # show alias target
Common Aliases
ls → Get-ChildItemList files and directories
cd → Set-LocationChange directory
cp → Copy-ItemCopy file or directory
mv → Move-ItemMove or rename
rm → Remove-ItemDelete file or directory
cat → Get-ContentRead file contents
echo → Write-OutputPrint to pipeline
cls → Clear-HostClear console
Variables
Variable Basics
$name = "Alice" # string $count = 42 # integer $pi = 3.14 # double $list = @(1, 2, 3) # array $hash = @{a=1; b=2} # hashtable
Automatic Variables
$_Current pipeline object
$PSVersionTablePowerShell version info
$HOMEUser's home directory
$PWDCurrent directory
$nullNull value
$true / $falseBoolean constants
$ErrorArray of recent errors
$LASTEXITCODEExit code of last native command
Environment Variables
$env:PATH # read env var $env:MY_VAR = "value" # set env var Get-ChildItem Env: # list all env vars
Operators
Comparison Operators
-eq -neEqual / not equal
-gt -ltGreater / less than
-ge -leGreater/less or equal
-like -notlikeWildcard match (*, ?)
-match -notmatchRegex match
-containsCollection contains value
-in -notinValue in collection
Logical & Other Operators
-and -or -notLogical operators
!Logical NOT (alias)
-replaceRegex replace: 'hi' -replace 'h','b'
-split -joinSplit / join strings
..Range: 1..5 → 1,2,3,4,5
?:Ternary (v7+): $x ? 'yes' : 'no'
Control Flow
if / elseif / else
if ($age -ge 18) { "Adult" } elseif ($age -ge 13) { "Teen" } else { "Child" }
switch
switch ($color) { "red" { "Stop" } "green" { "Go" } default { "Unknown" } }
Loops
foreach ($item in $list) { $item } for ($i=0; $i -lt 5; $i++) { $i } while ($x -lt 10) { $x++ } 1..5 | ForEach-Object { $_ * 2 }
Functions
Defining Functions
function Get-Greeting { param([string]$Name = "World") "Hello, $Name!" } Get-Greeting -Name "Alice"
Advanced Parameters
function Copy-SafeFile { [CmdletBinding()] param( [Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$Dest ) Copy-Item $Path $Dest -WhatIf:$WhatIfPreference }
Objects & Pipeline
Pipeline Basics
Get-Process | Sort-Object CPU -Desc | Select-Object -First 5 Get-Service | Where-Object Status -eq "Running" Get-ChildItem | Measure-Object -Property Length -Sum
Key Pipeline Cmdlets
Where-ObjectFilter objects: | Where {$_.CPU -gt 10}
Select-ObjectPick properties: | Select Name, CPU
Sort-ObjectSort: | Sort CPU -Desc
ForEach-ObjectTransform each: | ForEach {$_.Name}
Measure-ObjectCount, sum, average, min, max
Group-ObjectGroup by property value
Format-TableDisplay as table: | ft -Auto
Export-CsvExport to CSV: | Export-Csv out.csv
Files
File Operations
Get-Content log.txt # read file Set-Content out.txt "hello" # write (overwrite) Add-Content out.txt "more" # append Get-Content log.txt | Select-String "error" # grep
Path & File Cmdlets
Test-Path $pathCheck if file/dir exists
New-Item -Type FileCreate file
New-Item -Type DirectoryCreate directory
Resolve-PathGet absolute path
Join-PathCombine path segments
Split-PathGet parent or leaf
Get-ItemPropertyFile attributes and metadata
Remove-Item -RecurseDelete directory recursively
Strings
String Basics
"Hello, $name" # interpolation (double quotes) 'Hello, $name' # literal (single quotes) "Length: $($list.Count)" # expression in string @" Multi-line here-string with $name "@
String Methods
.ToUpper() / .ToLower()Change case
.Trim()Remove leading/trailing whitespace
.Split(',')Split into array
.Replace('a','b')Replace substring
.StartsWith() / .EndsWith()Check prefix / suffix
.Substring(0,5)Extract substring
.Contains('text')Check if contains
-f operator'{0} is {1}' -f 'sky','blue'
Modules
Module Management
Get-Module -ListAvailable # installed modules Find-Module -Name Az* # search gallery Install-Module -Name Pester # install from gallery Import-Module ActiveDirectory # load module
Module Commands
Get-ModuleList loaded modules
Import-ModuleLoad module into session
Remove-ModuleUnload module from session
Update-ModuleUpdate installed module
Get-Command -Module XList commands in module
$env:PSModulePathModule search paths
Common Patterns
Error Handling
try { Get-Item "C:\missing" -ErrorAction Stop } catch { "Error: $_" } finally { "Cleanup here" }
Execution Policy & Remoting
Get-ExecutionPolicyShow current script policy
Set-ExecutionPolicy RemoteSignedAllow local scripts
Enter-PSSession -Computer SRV1Interactive remote session
Invoke-Command -Computer SRV1 -Script {}Run script block remotely
Start-Job { long-task }Run background job
Receive-Job -Id 1Get background job output