Microsoft PowerShell
Updated: September 10, 2025Categories: 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
12Get-Process | Where-Object { $_.CPU -gt 10 } | Sort-Object CPU
2. Getting Help and Discovering Commands
Help Commands
PowerShell
1234567891011121314151617# 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 # 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
12345678910111213141516171819# Basic variables $name = "John Doe" $age = 30 $isActive = $true # Arrays $fruits = @("Apple", "Banana", "Cherry") # Hashtables (Dictionaries) $person = @{ Name = "John" Age = 30 City = "New York" } # Type casting [int]$number = "42" [string]$text = 123
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
1234567-and # Logical AND -or # Logical OR -not # Logical NOT # Example if (($x -gt 10) -and ($x -lt 20)) { "x is between 10 and 20" }
5. Control Structures
If/Else
PowerShell
12345678if ($condition) { # Code if true } elseif ($another_condition) { # Alternative condition } else { # Default action }
Switch Statement
PowerShell
123456switch ($value) { 1 { "One" } 2 { "Two" } default { "Other" } }
Loops
PowerShell
123456789101112131415161718# 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++ }
6. Functions and Advanced Functions
Basic Function
PowerShell
1234567function Greet { param($name) return "Hello, $name!" } Greet -name "John"
Advanced Function with Pipeline Support
PowerShell
1234567891011121314function Process-Items { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] $InputObject ) process { # Process each pipeline item $InputObject | ForEach-Object { # Do something with $_ } } }
7. File and Folder Operations
PowerShell
123456789101112131415# 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"
8. Text Processing and String Manipulation
PowerShell
12345678910$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 ","
9. Working with Objects and Properties
PowerShell
1234$process = Get-Process chrome $process.Name # Access object property $process | Select-Object Name, CPU, Id # Select specific properties
10. Pipeline Operations and Filtering
PowerShell
123456789# Filter processes 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
11. Error Handling
PowerShell
123456789101112try { # Risky operation $result = Invoke-WebRequest -Uri "http://example.com" } catch { Write-Host "An error occurred: $_" } finally { # Cleanup code } # Suppress errors Get-ChildItem -ErrorAction SilentlyContinue
12. Remote PowerShell
PowerShell
12345678# Connect to remote computer Enter-PSSession -ComputerName RemoteServer # Run command on remote computer Invoke-Command -ComputerName RemoteServer -ScriptBlock { Get-Process }
13. PowerShell Modules
PowerShell
123456789101112# List installed modules Get-Module # Import a module Import-Module ActiveDirectory # Install a module Install-Module PSReadLine # Find modules Find-Module -Name *Azure*
14. Services and Processes
PowerShell
12345678910111213# 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
15. Registry Operations
PowerShell
123456# Read registry key Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion" # Set registry value Set-ItemProperty -Path "HKCU:\Path\To\Key" -Name "ValueName" -Value "NewValue"
16. Event Log Management
PowerShell
123456# View system event log Get-EventLog -LogName System -Newest 10 # Clear event log Clear-EventLog -LogName Application
17. Active Directory Operations
PowerShell
1234# Requires ActiveDirectory module Get-ADUser -Filter * New-ADUser -Name "John Doe" -SamAccountName jdoe
18. Data Formats (CSV, JSON, XML)
PowerShell
1234567891011# CSV Import-Csv file.csv Export-Csv output.csv # JSON ConvertTo-Json @{name="John"; age=30} ConvertFrom-Json '{"name":"John","age":30}' # XML [xml]$xml = Get-Content file.xml
19. Scheduled Tasks and Automation
PowerShell
12345# Create scheduled task $action = New-ScheduledTaskAction -Execute "notepad.exe" $trigger = New-ScheduledTaskTrigger -Daily -At 9am Register-ScheduledTask -TaskName "DailyNotepad" -Action $action -Trigger $trigger
20. PowerShell ISE and VS Code Tips
- Use
Ctrl+Jfor IntelliSense - Use
Ctrl+Spacefor auto-completion - Use integrated terminal for quick scripts
21. Security and Execution Policies
PowerShell
123456789# Check current execution policy Get-ExecutionPolicy # Set execution policy Set-ExecutionPolicy RemoteSigned # Run unsigned script PowerShell.exe -ExecutionPolicy Bypass -File script.ps1
22. Performance and Best Practices
- Use
[ValidateNotNullOrEmpty()]for parameter validation - Prefer
foreachoverForEach-Objectfor better performance - Use
Begin,Process,Endblocks in advanced functions - Avoid unnecessary pipeline operations
23. Common Administrative Tasks
PowerShell
123456789# Disk management Get-Disk Get-Partition Get-Volume # Network troubleshooting Test-Connection google.com Get-NetIPConfiguration
24. Troubleshooting and Debugging
PowerShell
12345678910# Verbose output $VerbosePreference = 'Continue' # Trace script execution Set-PSDebug -Trace 1 # Log errors $ErrorActionPreference = 'Continue' Start-Transcript log.txt
Compatibility Notes
- Windows PowerShell 5.1: Comes pre-installed on Windows
- PowerShell 7+: Cross-platform, open-source, .NET Core-based
Pro Tips:
- Always use
-?orGet-Helpfor command details - Explore
$PSVersionTablefor version information - Keep PowerShell and modules updated
Happy scripting!
Continue Learning
Discover more cheatsheets to boost your productivity