Microsoft PowerShell
Updated: May 22, 2026Categories: Command Line, Windows
Printed from:
Microsoft PowerShell Cheatsheet
1. PowerShell Basics and Concepts
Cmdlets
- Cmdlets are lightweight commands with a Verb-Noun naming convention
- Examples:
PowerShell
123Get-Process # List running processes Stop-Service # Stop a Windows service
Objects and Pipeline
- PowerShell works with .NET objects, not just text
- Pipeline (|) passes objects between commands
PowerShell
12345Get-Process | Where-Object { $_.CPU -gt 10 } | Sort-Object CPU # Parallel pipeline processing (PowerShell 7+) 1..10 | ForEach-Object -Parallel { "Processing $_"; Start-Sleep 1 } -ThrottleLimit 5
Pipeline Chain Operators (PowerShell 7+)
PowerShell
123456# Run next command only if previous succeeded Test-Path file.txt && Get-Content file.txt # Run next command only if previous failed Test-Path file.txt || New-Item file.txt
2. Getting Help and Discovering Commands
Help Commands
PowerShell
123456789101112131415161718192021# Get help for a specific cmdlet Get-Help Get-Process # Get detailed help with examples Get-Help Get-Process -Detailed Get-Help Get-Process -Examples Get-Help Get-Process -Online # Open online docs in browser # Update local help content (run elevated) Update-Help # List all commands Get-Command # Find commands by verb or noun Get-Command -Verb Get Get-Command -Noun Process # Discover object properties and methods Get-Process | Get-Member
3. Variables and Data Types
Variable Declaration
PowerShell
123456789101112131415161718192021222324252627# Basic variables $name = "John Doe" $age = 30 $isActive = $true # Arrays $fruits = @("Apple", "Banana", "Cherry") # Hashtables (Dictionaries) $person = @{ Name = "John" Age = 30 City = "New York" } # Ordered hashtable (preserves insertion order) $ordered = [ordered]@{ First = 1; Second = 2; Third = 3 } # Type casting [int]$number = "42" [string]$text = 123 # Null-coalescing and null-conditional (PowerShell 7+) $value = $null ?? "default" # Returns "default" $user?.Address?.City # Safe member access $cache ??= (Get-ExpensiveData) # Assign if null
4. Operators
Arithmetic Operators
PowerShell
12345678$a = 10 $b = 3 $sum = $a + $b # Addition $diff = $a - $b # Subtraction $prod = $a * $b # Multiplication $div = $a / $b # Division $mod = $a % $b # Modulus
Comparison Operators
PowerShell
12345678910-eq # Equal -ne # Not equal -gt # Greater than -ge # Greater than or equal -lt # Less than -le # Less than or equal # Example if ($a -gt $b) { "A is greater than B" }
Logical Operators
PowerShell
1234567891011-and # Logical AND -or # Logical OR -not # Logical NOT -xor # Logical XOR # Example if (($x -gt 10) -and ($x -lt 20)) { "x is between 10 and 20" } # Ternary operator (PowerShell 7+) $status = ($age -ge 18) ? "Adult" : "Minor"
5. Control Structures
If/Else
PowerShell
12345678if ($condition) { # Code if true } elseif ($another_condition) { # Alternative condition } else { # Default action }
Switch Statement
PowerShell
123456789101112switch ($value) { 1 { "One" } 2 { "Two" } default { "Other" } } # Switch with regex and wildcard switch -Regex ($input) { '^\d+$' { "Number" } '^[a-z]+' { "Lowercase word" } }
Loops
PowerShell
123456789101112131415161718192021# For Loop for ($i = 0; $i -lt 10; $i++) { Write-Host $i } # Foreach Loop $fruits = @("Apple", "Banana", "Cherry") foreach ($fruit in $fruits) { Write-Host $fruit } # While Loop $count = 0 while ($count -lt 5) { Write-Host $count $count++ } # Do-While / Do-Until do { $n = Read-Host "Enter Q to quit" } until ($n -eq 'Q')
6. Functions and Advanced Functions
Basic Function
PowerShell
1234567function Greet { param($name) return "Hello, $name!" } Greet -name "John"
Advanced Function with Pipeline Support
PowerShell
1234567891011121314151617function Process-Items { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] $InputObject ) begin { # one-time setup } process { # Process each pipeline item $InputObject | ForEach-Object { # Do something with $_ } } end { # one-time cleanup } }
7. File and Folder Operations
PowerShell
12345678910111213141516171819# List files and folders Get-ChildItem C:\ # Copy item Copy-Item source.txt destination.txt # Move item Move-Item old_location new_location # Remove item Remove-Item file.txt # Create directory New-Item -ItemType Directory -Path "C:\NewFolder" # Compress / expand archives Compress-Archive -Path C:\Logs\*.log -DestinationPath C:\logs.zip Expand-Archive -Path C:\logs.zip -DestinationPath C:\Extracted
8. Text Processing and String Manipulation
PowerShell
12345678910111213141516$text = "Hello, World!" $text.ToUpper() # Uppercase $text.ToLower() # Lowercase $text.Contains("World") # Check substring $text.Replace("World", "PowerShell") # Split and Join $words = "one two three".Split() $joined = $words -join "," # Here-strings for multi-line text $multi = @" Line 1 Line 2 "@
9. Working with Objects and Properties
PowerShell
1234567$process = Get-Process chrome $process.Name # Access object property $process | Select-Object Name, CPU, Id # Select specific properties # Build custom objects [pscustomobject]@{ Name = "John"; Age = 30 }
10. Pipeline Operations and Filtering
PowerShell
123456789101112131415# Filter processes Get-Process | Where-Object { $_.CPU -gt 10 } # Simplified Where syntax (PowerShell 3+) Get-Process | Where-Object CPU -gt 10 # Select top 5 processes by CPU Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 # Group objects Get-Process | Group-Object Company # Parallel filtering (PowerShell 7+) $servers | ForEach-Object -Parallel { Test-Connection $_ -Count 1 -Quiet } -ThrottleLimit 10
11. Error Handling
PowerShell
123456789101112131415161718192021try { # Risky operation $result = Invoke-WebRequest -Uri "https://example.com" } catch [System.Net.WebException] { Write-Host "Web error: $($_.Exception.Message)" } catch { Write-Host "An error occurred: $_" } finally { # Cleanup code } # Suppress errors Get-ChildItem -ErrorAction SilentlyContinue # Get the last error $Error[0] | Format-List -Force # Pretty error view (PowerShell 7+) $ErrorView = 'ConciseView' # or 'NormalView', 'CategoryView', 'DetailedView' Get-Error # Detailed inspection of last error
12. Remote PowerShell
PowerShell
1234567891011121314151617# Connect to remote computer (WinRM) Enter-PSSession -ComputerName RemoteServer # Run command on remote computer Invoke-Command -ComputerName RemoteServer -ScriptBlock { Get-Process } # SSH-based remoting (cross-platform, PowerShell 7+) Enter-PSSession -HostName user@linuxhost -SSHTransport Invoke-Command -HostName server01,server02 -SSHTransport -ScriptBlock { uptime } # Persistent sessions $s = New-PSSession -ComputerName RemoteServer Invoke-Command -Session $s -ScriptBlock { Get-Service } Remove-PSSession $s
13. PowerShell Modules
PowerShell
1234567891011121314151617181920# List installed modules Get-Module -ListAvailable # Import a module Import-Module ActiveDirectory # Install a module from the PowerShell Gallery Install-Module PSReadLine -Scope CurrentUser # Find modules Find-Module -Name *Azure* # Update modules Update-Module PSReadLine # Microsoft.PowerShell.PSResourceGet (modern replacement for PowerShellGet, ships with PS 7.4+) Install-PSResource Microsoft.Graph Find-PSResource Az Update-PSResource PSReadLine
14. Services and Processes
PowerShell
123456789101112131415# List services Get-Service # Start/Stop service Start-Service -Name "wuauserv" Stop-Service -Name "wuauserv" # List processes Get-Process # Stop a process Stop-Process -Name notepad # Note: Get-EventLog is deprecated; use Get-WinEvent (see section 16)
15. Registry Operations
PowerShell
12345678910# Read registry key Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion" # Set registry value Set-ItemProperty -Path "HKCU:\Path\To\Key" -Name "ValueName" -Value "NewValue" # Create a new key / value New-Item -Path "HKCU:\Software\MyApp" -Force New-ItemProperty -Path "HKCU:\Software\MyApp" -Name "Version" -Value "1.0" -PropertyType String
16. Event Log Management
PowerShell
123456# Modern, cross-architecture cmdlet (preferred) Get-WinEvent -LogName System -MaxEvents 10 Get-WinEvent -FilterHashtable @{ LogName='Application'; Level=2; StartTime=(Get-Date).AddHours(-1) } # Legacy cmdlets (Get-EventLog / Clear-EventLog) are deprecated and unavailable in PowerShell 7+
17. Active Directory Operations
PowerShell
12345# Requires the ActiveDirectory module (RSAT) Get-ADUser -Filter * Get-ADUser -Identity jdoe -Properties MemberOf New-ADUser -Name "John Doe" -SamAccountName jdoe -AccountPassword (Read-Host -AsSecureString) -Enabled $true
18. Data Formats (CSV, JSON, XML)
PowerShell
1234567891011121314# CSV Import-Csv file.csv Get-Process | Export-Csv output.csv -NoTypeInformation # JSON ConvertTo-Json @{ name="John"; age=30 } -Depth 5 ConvertFrom-Json '{"name":"John","age":30}' # JSON with comments / trailing commas (PowerShell 7+) '{ "x": 1, /* comment */ }' | ConvertFrom-Json -AsHashtable # XML [xml]$xml = Get-Content file.xml
19. Scheduled Tasks and Automation
PowerShell
1234567# Create scheduled task (Windows) $action = New-ScheduledTaskAction -Execute "notepad.exe" $trigger = New-ScheduledTaskTrigger -Daily -At 9am Register-ScheduledTask -TaskName "DailyNotepad" -Action $action -Trigger $trigger # On Linux/macOS use cron, systemd timers, or launchd with pwsh
20. Editor Tips (VS Code / PowerShell ISE)
- VS Code with the PowerShell extension is the recommended editor; the ISE is in maintenance mode and is not supported in PowerShell 7+
Ctrl+Spacefor IntelliSense / auto-completionF8runs the current selection or line in the integrated terminal- Use
PSScriptAnalyzer(bundled with the extension) for linting Invoke-Formatterreformats code perPSScriptAnalyzerrules
21. Security and Execution Policies
PowerShell
123456789101112131415# Check current execution policy Get-ExecutionPolicy -List # Set execution policy Set-ExecutionPolicy RemoteSigned -Scope CurrentUser # Run unsigned script (one-off) pwsh -ExecutionPolicy Bypass -File script.ps1 # Secret management (Microsoft.PowerShell.SecretManagement) Install-Module Microsoft.PowerShell.SecretManagement, Microsoft.PowerShell.SecretStore Register-SecretVault -Name LocalStore -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault Set-Secret -Name ApiKey -Secret "supersecret" Get-Secret -Name ApiKey -AsPlainText
22. Performance and Best Practices
- Use
[ValidateNotNullOrEmpty()],[ValidateSet()],[ValidateRange()]for parameter validation - Prefer the
foreachstatement overForEach-Objectfor in-memory collections; useForEach-Object -Parallel(PowerShell 7+) for I/O-bound work - Use
Begin,Process,Endblocks in advanced functions - Avoid
Write-Hostfor data output; emit objects so they flow through the pipeline - Lint scripts with
Invoke-ScriptAnalyzerand prefer approved verbs (Get-Verb) - Use
#Requires -Version 7.4and#Requires -Modules <name>to declare prerequisites
23. Common Administrative Tasks
PowerShell
1234567891011# Disk management Get-Disk Get-Partition Get-Volume # Network troubleshooting Test-Connection google.com -Count 2 Test-NetConnection google.com -Port 443 Get-NetIPConfiguration Resolve-DnsName example.com
24. Troubleshooting and Debugging
PowerShell
123456789101112131415161718# Verbose / debug output $VerbosePreference = 'Continue' $DebugPreference = 'Continue' # Step-debug a script Set-PSBreakpoint -Script .\myscript.ps1 -Line 10 Set-PSBreakpoint -Command Get-Process # Trace script execution Set-PSDebug -Trace 1 # Capture a session transcript Start-Transcript -Path .\session.log Stop-Transcript # Inspect the most recent error in detail (PowerShell 7+) Get-Error
25. Cross-Platform and Web
PowerShell
12345678910111213# Detect host OS (automatic variables available in PowerShell 6+) if ($IsWindows) { "Windows" } elseif ($IsLinux) { "Linux" } elseif ($IsMacOS) { "macOS" } # Modern web requests (HTTP/2 supported on PS 7.2+) Invoke-RestMethod -Uri 'https://api.github.com/repos/PowerShell/PowerShell' -Method Get Invoke-WebRequest -Uri 'https://example.com' -OutFile page.html # JSON Web Token style auth header $headers = @{ Authorization = "Bearer $token" } Invoke-RestMethod -Uri $url -Headers $headers
Compatibility Notes
- Windows PowerShell 5.1: Ships with Windows; built on .NET Framework; in maintenance mode — no new features, security fixes only
- PowerShell 7.x (current LTS: 7.4 on .NET 8; current stable: 7.5 on .NET 9): cross-platform (Windows, Linux, macOS), open-source, installed side-by-side as
pwsh - PowerShell 7.0–7.2 have reached end of support; upgrade to 7.4 LTS or 7.5
- Use the
WindowsCompatibility/ implicit remoting features when a module is only available on Windows PowerShell 5.1
Pro Tips:
- Always use
-?orGet-Help <cmd> -Onlinefor the latest command details - Inspect
$PSVersionTablefor version, edition, and OS information - Keep PowerShell and modules updated (
winget upgrade Microsoft.PowerShell,Update-PSResource) - Enable predictive IntelliSense in PSReadLine:
Set-PSReadLineOption -PredictionSource HistoryAndPlugin -PredictionViewStyle ListView
Happy scripting!
Continue Learning
Discover more cheatsheets to boost your productivity