175 commands · 10 cheat sheets · Windows

PowerShell and Automation master quick reference

Browse 175 commands from 10 focused cheat sheets on page 1 of 1. Each example opens its matching detailed section.

PowerShell and Automation · 15 commands

PowerShell Background Jobs Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Start process job$job = Start-Job -Name 'Inventory' -ScriptBlock { Get-Process | Select-Object -First 5 }View examples
Pass explicit argumentsStart-Job -ScriptBlock { param($Path) Get-Item ` -LiteralPath $Path } -ArgumentList ` 'C:/Data/report.csv'View examples
Start thread jobStart-ThreadJob -Name 'FastRead' -ScriptBlock { Get-Date ` }View examples
List jobsGet-Job | Select-Object Id, Name, State, HasMoreData, LocationView examples
Inspect child jobs$job.ChildJobs | Select-Object Id, Name, State, Location, HasMoreDataView examples
Wait with timeoutWait-Job -Job $job -Timeout 60View examples
Wait for any jobWait-Job -Job $jobs -Any -Timeout 30View examples
Receive available outputReceive-Job -Job $jobView examples
Read output non-destructivelyReceive-Job -Job $job -KeepView examples
Wait and receiveReceive-Job -Job $job -Wait -AutoRemoveJobView examples
Start remote job$job = Invoke-Command -ComputerName ` 'server01','server02' -ScriptBlock { Get-Date } -AsJob ` -ThrottleLimit 2View examples
Find failed child jobs$job.ChildJobs | Where-Object State -eq 'Failed' | Format-List Location, JobStateInfo, ErrorView examples
Stop a running jobStop-Job -Job $jobView examples
Remove completed jobRemove-Job -Job $jobView examples
Remove finished jobsGet-Job | Where-Object State -in 'Completed','Failed','Stopped' | Remove-JobView examples

PowerShell and Automation · 16 commands

PowerShell Classes and Custom Objects Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create an ordered record$Item = [pscustomobject][ordered]@{ Name = 'api'; State ` = 'Running' }View examples
Add a semantic type name$Item.PSObject.TypeNames.Insert(0, ` 'Contoso.ServiceStatus')View examples
Declare a classclass ServiceSpec { [string] $Name; [bool] $Enabled }View examples
Invoke a constructor$Spec = [ServiceSpec]::new('api', $true)View examples
Declare an enumenum HealthState { Unknown; Healthy; Degraded; Failed }View examples
Validate a property value[ValidateSet('Dev','Test','Prod')] [string] $EnvironmentView examples
Hide an implementation memberhidden [string] $CacheKeyView examples
Call a static method[Widget]::NormalizeName(' API ')View examples
Add a calculated property$Item | Add-Member -NotePropertyName Healthy -NotePropertyValue $trueView examples
Project calculated output$Item | Select-Object Name,@{n='Label';e={"$($_.Name):$($_.State)"}}View examples
Accept typed pipeline inputparam([Parameter(ValueFromPipeline)][ServiceSpec] ` $InputObject)View examples
Document output type[OutputType([ServiceSpec])] param()View examples
Serialize with explicit depth$Item | ConvertTo-Json -Depth 5View examples
Persist PowerShell data$Item | Export-Clixml -LiteralPath '.\item.clixml'View examples
Load module types at parse timeusing module Contoso.ModelsView examples
Set default display propertiesUpdate-TypeData -TypeName Contoso.ServiceStatus ` -DefaultDisplayPropertySet Name,State -ForceView examples

PowerShell and Automation · 16 commands

PowerShell Desired State Configuration Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Inspect standalone DSCdsc --versionView examples
Inspect legacy moduleGet-Module -ListAvailable PSDesiredStateConfiguration | Select-Object Name,Version,PathView examples
List DSC 3 resourcesdsc resource listView examples
Inspect resource schemadsc resource schema --resource Microsoft.DSC.Debug/EchoView examples
Read current statedsc config get --file .\server.dsc.yamlView examples
Test desired statedsc config test --file .\server.dsc.yamlView examples
Apply desired statedsc config set --file .\server.dsc.yamlView examples
Supply parameter datadsc config --parameters-file .\prod.parameters.yaml set ` --file .\server.dsc.yamlView examples
Inspect Windows LCMGet-DscLocalConfigurationManagerView examples
Test legacy configurationTest-DscConfiguration -Path .\Compiled -DetailedView examples
Apply compiled MOFStart-DscConfiguration -Path .\Compiled -Wait -VerboseView examples
Read last LCM runGet-DscConfigurationStatus -AllView examples
Parse a configuration script$null = ` [System.Management.Automation.Language.Parser]::ParseFile('.\Config.ps1',[ref]$null,[ref]$null)View examples
Recognize WhatIf boundaryGet-Command Start-DscConfiguration | Select-Object -ExpandProperty ParametersView examples
Export discoverable statedsc config export --file .\resources.yamlView examples
Read DSC operational eventsGet-WinEvent -LogName ` 'Microsoft-Windows-DSC/Operational' -MaxEvents 50View examples

PowerShell and Automation · 17 commands

PowerShell Error Handling Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Write a non-terminating errorWrite-Error 'The record is invalid'View examples
Make a command error terminatingGet-Item -LiteralPath $Path -ErrorAction StopView examples
Hide a command errorGet-Item -LiteralPath $Path -ErrorAction ` SilentlyContinueView examples
Catch a failurecatch { Write-Warning $_.Exception.Message }View examples
Catch one exception typecatch [System.IO.FileNotFoundException] { Write-Warning ` 'Missing file' }View examples
Order specific handlers firstcatch [System.UnauthorizedAccessException] { ` Write-Warning 'Access denied' }View examples
Inspect the caught error$_.Exception.MessageView examples
Inspect the category$_.CategoryInfo.CategoryView examples
Read the newest error$Error[0]View examples
Capture command errorsGet-Item missing.txt -ErrorVariable lookupErrors ` -ErrorAction SilentlyContinueView examples
Always run cleanupfinally { $stream.Dispose() }View examples
Raise a terminating errorthrow 'Configuration is invalid'View examples
Re-throw the current errorthrowView examples
Set a scoped default action$ErrorActionPreference = 'Stop'View examples
Write a warningWrite-Warning 'Using fallback configuration'View examples
Read a native exit codeif ($LASTEXITCODE -ne 0) { throw ` "Tool failed: $LASTEXITCODE" }View examples
Inspect command successif (-not $?) { Write-Warning 'The last operation failed' ` }View examples

PowerShell and Automation · 20 commands

PowerShell Files and Directories Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Show the current locationGet-LocationView examples
List directory contentsGet-ChildItem -LiteralPath . -ForceView examples
Change directorySet-Location -LiteralPath 'C:\Projects'View examples
Move to the parentSet-Location ..View examples
Resolve an existing pathResolve-Path -LiteralPath '.\config.json'View examples
Create a directoryNew-Item -ItemType Directory -Path '.\reports'View examples
Create a text fileNew-Item -ItemType File -Path '.\notes.txt' -Value ` 'First line'View examples
Check whether a path existsTest-Path -LiteralPath '.\notes.txt' -PathType LeafView examples
Inspect one itemGet-Item -LiteralPath '.\notes.txt'View examples
Read a text fileGet-Content -LiteralPath '.\notes.txt'View examples
Read the last linesGet-Content -LiteralPath '.\app.log' -Tail 20View examples
Follow a growing logGet-Content -LiteralPath '.\app.log' -Tail 20 -WaitView examples
Copy a fileCopy-Item -LiteralPath '.\config.json' -Destination ` '.\config.backup.json'View examples
Copy a directory treeCopy-Item -LiteralPath '.\reports' -Destination ` '.\reports-backup' -RecurseView examples
Move or rename an itemMove-Item -LiteralPath '.\draft.txt' -Destination ` '.\final.txt'View examples
Find files recursivelyGet-ChildItem -Path . -Filter '*.json' -File -RecurseView examples
Filter files by sizeGet-ChildItem -Path . -File -Recurse | Where-Object Length -GT 10MBView examples
Search inside filesSelect-String -Path '.\*.log' -Pattern 'error' ` -CaseSensitive:$falseView examples
Preview file removalRemove-Item -LiteralPath '.\obsolete.txt' -WhatIfView examples
Preview recursive removalRemove-Item -LiteralPath '.\build-output' -Recurse ` -WhatIfView examples

PowerShell and Automation · 16 commands

PowerShell Modules and Repositories Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
List available module versionsGet-Module -ListAvailable Pester | Sort-Object Version -DescendingView examples
List loaded modulesGet-Module | Sort-Object Name, VersionView examples
Inspect module search paths$env:PSModulePath -split [IO.Path]::PathSeparatorView examples
List repositoriesGet-PSResourceRepository | Sort-Object Priority, NameView examples
Find exact resourceFind-PSResource -Name Pester -Version 5.6.1 -Repository ` PSGalleryView examples
List available versionsFind-PSResource -Name Pester -Version '*' -Repository PSGallery | Sort-Object Version -DescendingView examples
Stage a module packageSave-PSResource -Name Pester -Version 5.6.1 -Repository ` PSGallery -Path './staging'View examples
Validate a manifestTest-ModuleManifest -Path ` './staging/Pester/5.6.1/Pester.psd1'View examples
Inspect script signaturesGet-ChildItem './staging/Pester' -Recurse -File -Include '*.ps1','*.psm1' | Get-AuthenticodeSignatureView examples
Preview current-user installInstall-PSResource -Name Pester -Version 5.6.1 ` -Repository PSGallery -Scope CurrentUser -WhatIfView examples
List installed resourcesGet-InstalledPSResource -Name Pester | Sort-Object Version -DescendingView examples
Preview module updateUpdate-PSResource -Name Pester -WhatIfView examples
Import a pinned versionImport-Module -FullyQualifiedName @{ ModuleName = ` 'Pester'; RequiredVersion = '5.6.1' } -ErrorAction ` StopView examples
Inspect exported commandsGet-Command -Module Pester | Sort-Object NameView examples
Unload from sessionRemove-Module -Name Pester -ForceView examples
Preview uninstallUninstall-PSResource -Name Pester -Version 5.6.1 -Scope ` CurrentUser -WhatIfView examples

PowerShell and Automation · 17 commands

PowerShell Pipelines Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Inspect object membersGet-Process | Get-MemberView examples
Inspect one objectGet-Process | Select-Object -First 1 | Format-List *View examples
Filter by one propertyGet-Process | Where-Object CPU -gt 10View examples
Filter with a script blockGet-Service | Where-Object { $_.Status -eq 'Running' -and $_.CanStop }View examples
Select propertiesGet-Process | Select-Object Name, IdView examples
Take the first objectsGet-Process | Select-Object -First 5View examples
Expand one propertyGet-Process | Select-Object -ExpandProperty NameView examples
Calculate a propertyGet-Process | Select-Object Name, @{Name='MemoryMB'; Expression={[math]::Round($_.WorkingSet64 / 1MB, 1)}}View examples
Sort descendingGet-Process | Sort-Object WorkingSet64 -DescendingView examples
Transform each objectGet-Process | ForEach-Object { $_.Name.ToUpperInvariant() }View examples
Group by a propertyGet-Service | Group-Object StatusView examples
Measure numeric valuesGet-ChildItem -File | Measure-Object Length -Sum -AverageView examples
Save and continueGet-Process | Tee-Object -Variable processes | Sort-Object CPU -DescendingView examples
Export objects to CSVGet-Process | Select-Object Name, Id, CPU | Export-Csv processes.csv -NoTypeInformationView examples
Import CSV objectsImport-Csv processes.csvView examples
Format a final tableGet-Process | Sort-Object CPU -Descending | Format-Table Name, Id, CPU -AutoSizeView examples
Run an action per objectGet-ChildItem *.log | ForEach-Object { Compress-Archive -LiteralPath $_.FullName -DestinationPath ($_.FullName + '.zip') }View examples

PowerShell and Automation · 18 commands

PowerShell Registry Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
List registry drivesGet-PSDrive -PSProvider RegistryView examples
Use a full hive pathGet-Item -LiteralPath ` 'Registry::HKEY_CURRENT_USER\Software'View examples
List immediate subkeysGet-ChildItem -LiteralPath 'HKCU:\Software'View examples
Find descendant keysGet-ChildItem -LiteralPath 'HKCU:\Software\Acme' ` -RecurseView examples
Test a key pathTest-Path -LiteralPath 'HKCU:\Software\Acme'View examples
Inspect a key objectGet-Item -LiteralPath 'HKCU:\Software\Acme'View examples
Read key valuesGet-ItemProperty -LiteralPath 'HKCU:\Software\Acme'View examples
Read one raw valueGet-ItemPropertyValue -LiteralPath 'HKCU:\Software\Acme' ` -Name 'Theme'View examples
Preview key creationNew-Item -Path 'HKCU:\Software\Acme' -WhatIfView examples
Preview a string valueNew-ItemProperty -LiteralPath 'HKCU:\Software\Acme' ` -Name 'Theme' -Value 'Dark' -PropertyType String ` -WhatIfView examples
Preview a DWORD valueNew-ItemProperty -LiteralPath 'HKCU:\Software\Acme' ` -Name 'PageSize' -Value 25 -PropertyType DWord -WhatIfView examples
Preview changing a valueSet-ItemProperty -LiteralPath 'HKCU:\Software\Acme' ` -Name 'Theme' -Value 'Light' -WhatIfView examples
Preview renaming a valueRename-ItemProperty -LiteralPath 'HKCU:\Software\Acme' ` -Name 'Theme' -NewName 'ColorTheme' -WhatIfView examples
Preview clearing dataClear-ItemProperty -LiteralPath 'HKCU:\Software\Acme' ` -Name 'Theme' -WhatIfView examples
Preview removing a valueRemove-ItemProperty -LiteralPath 'HKCU:\Software\Acme' ` -Name 'Theme' -WhatIfView examples
Preview removing a keyRemove-Item -LiteralPath 'HKCU:\Software\Acme' -Recurse ` -WhatIfView examples
Export a key treereg.exe export 'HKCU\Software\Acme' '.\Acme-backup.reg' ` /yView examples
Capture selected stateGet-ItemProperty -LiteralPath 'HKCU:\Software\Acme' | Select-Object Theme, PageSizeView examples

PowerShell and Automation · 24 commands

PowerShell REST APIs and Web Requests Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Deserialize an API responseInvoke-RestMethod -Uri $Uri -Method GetView examples
Inspect an HTTP response$Response = Invoke-WebRequest -Uri $Uri -Method GetView examples
Encode GET query valuesInvoke-RestMethod -Uri $Uri -Method Get -Body @{ q = ` 'blue widget'; page = 2 }View examples
Serialize JSON deliberately$Json = @{ name = 'widget'; enabled = $true } | ConvertTo-Json -Depth 10 -CompressView examples
Post UTF-8 JSONInvoke-RestMethod -Uri $Uri -Method Post -Body $Json ` -ContentType 'application/json; charset=utf-8'View examples
Request a response media typeInvoke-RestMethod -Uri $Uri -Headers @{ Accept = ` 'application/json' }View examples
Prompt for a bearer tokenInvoke-RestMethod -Uri $Uri -Authentication Bearer ` -Token (Read-Host -AsSecureString)View examples
Capture a web sessionInvoke-WebRequest -Uri $Uri -SessionVariable ApiSessionView examples
Reuse cookies and session stateInvoke-RestMethod -Uri $Uri -WebSession $ApiSessionView examples
Use a client certificateInvoke-RestMethod -Uri $Uri -Certificate (Get-Item ` "Cert:\CurrentUser\My\$Thumbprint")View examples
Constrain the TLS protocolInvoke-RestMethod -Uri $Uri -SslProtocol Tls12View examples
Use an explicit proxyInvoke-RestMethod -Uri $Uri -Proxy ` 'https://proxy.example.com:8443'View examples
Follow bounded relation linksInvoke-RestMethod -Uri $Uri -FollowRelLink ` -MaximumFollowRelLink 5View examples
Capture status and headersInvoke-RestMethod -Uri $Uri -StatusCodeVariable Status ` -ResponseHeadersVariable HeadersView examples
Retry a bounded requestInvoke-RestMethod -Uri $Uri -MaximumRetryCount 3 ` -RetryIntervalSec 2View examples
Bound connection and idle readsInvoke-RestMethod -Uri $Uri -ConnectionTimeoutSeconds 10 ` -OperationTimeoutSeconds 30View examples
Cancel a request jobStop-Job -Job $RequestJobView examples
Download to an exact pathInvoke-WebRequest -Uri $Uri -OutFile '.\artifact.zip'View examples
Resume a partial downloadInvoke-WebRequest -Uri $Uri -OutFile ` '.\artifact.zip.part' -ResumeView examples
Calculate a SHA-256 digest(Get-FileHash -LiteralPath '.\artifact.zip' -Algorithm ` SHA256).HashView examples
Process HTTP error bodiesInvoke-RestMethod -Uri $Uri -SkipHttpErrorCheck ` -StatusCodeVariable StatusView examples
Catch request failurestry { Invoke-RestMethod -Uri $Uri -ErrorAction Stop } ` catch { Write-Error $_ }View examples
Use safe Windows PowerShell parsingInvoke-WebRequest -UseBasicParsing -Uri $UriView examples
Invoke native curl explicitlycurl.exe --fail --output artifact.zip ` https://example.com/artifact.zipView examples

PowerShell and Automation · 16 commands

Windows Scheduled Tasks PowerShell Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
List tasksGet-ScheduledTask | Sort-Object TaskPath, TaskNameView examples
Get one exact taskGet-ScheduledTask -TaskPath ` '\CmdMemo\' -TaskName 'NightlyExport'View examples
Inspect runtime informationGet-ScheduledTaskInfo -TaskPath ` '\CmdMemo\' -TaskName 'NightlyExport'View examples
Create an action$action = New-ScheduledTaskAction -Execute 'pwsh.exe' ` -Argument '-NoProfile -File C:\Scripts\Export.ps1'View examples
Create a daily trigger$trigger = New-ScheduledTaskTrigger -Daily -At '02:00'View examples
Create a startup trigger$trigger = New-ScheduledTaskTrigger -AtStartupView examples
Run as a service account$principal = New-ScheduledTaskPrincipal -UserId ` 'NT AUTHORITY\SYSTEM' -LogonType ServiceAccount ` -RunLevel HighestView examples
Set operational behavior$settings = New-ScheduledTaskSettingsSet ` -ExecutionTimeLimit (New-TimeSpan -Hours 1) ` -StartWhenAvailableView examples
Compose a task object$task = New-ScheduledTask -Action $action -Trigger ` $trigger -Settings $settings -Description ` 'Nightly export'View examples
Register a taskRegister-ScheduledTask -TaskPath ` '\CmdMemo\' -TaskName 'NightlyExport' -InputObject $taskView examples
Start on demandStart-ScheduledTask -TaskPath ` '\CmdMemo\' -TaskName 'NightlyExport'View examples
Stop a running taskStop-ScheduledTask -TaskPath ` '\CmdMemo\' -TaskName 'NightlyExport'View examples
Disable triggersDisable-ScheduledTask -TaskPath ` '\CmdMemo\' -TaskName 'NightlyExport'View examples
Enable a taskEnable-ScheduledTask -TaskPath ` '\CmdMemo\' -TaskName 'NightlyExport'View examples
Export task XMLExport-ScheduledTask -TaskPath ` '\CmdMemo\' -TaskName 'NightlyExport' | Set-Content -LiteralPath '.\NightlyExport.xml' -Encoding UnicodeView examples
Remove with confirmationUnregister-ScheduledTask -TaskPath ` '\CmdMemo\' -TaskName 'NightlyExport' -ConfirmView examples
CMDMEMO TERMINALREAD ONLY