Skip to content

PowerShell Cheatsheet

Overview

PowerShell is a cross-platform task automation solution made up of a command-line shell, a scripting language, and a configuration management framework.

Basic Commands

Getting Help

powershell
# Get help for a command
Get-Help Get-Process
Get-Help Get-Process -Examples
Get-Help Get-Process -Full

# Update help files
Update-Help

# Get command syntax
Get-Command Get-Process -Syntax
powershell
# Current location
Get-Location
pwd

# Change directory
Set-Location C:\Windows
cd C:\Windows

# List directory contents
Get-ChildItem
ls
dir

# Go back to previous directory
cd ..

File Operations

powershell
# Create new file
New-Item -ItemType File -Name "test.txt"
ni test.txt -ItemType File

# Create new directory
New-Item -ItemType Directory -Name "TestFolder"
mkdir TestFolder

# Copy files
Copy-Item source.txt destination.txt
cp source.txt destination.txt

# Move files
Move-Item oldname.txt newname.txt
mv oldname.txt newname.txt

# Remove files
Remove-Item test.txt
rm test.txt

# Get file content
Get-Content file.txt
cat file.txt

# Set file content
Set-Content -Path file.txt -Value "Hello World"
"Hello World" | Out-File file.txt

Variables and Data Types

Variables

powershell
# Declare variables
$name = "John"
$age = 30
$isActive = $true

# Array
$colors = @("red", "green", "blue")
$numbers = 1,2,3,4,5

# Hash table
$person = @{
    Name = "John"
    Age = 30
    City = "New York"
}

# Access hash table values
$person.Name
$person["Age"]

Data Types

powershell
# String
$text = "Hello World"
$multiline = @"
This is a
multi-line string
"@

# Numbers
$integer = 42
$decimal = 3.14

# Boolean
$isTrue = $true
$isFalse = $false

# Date
$today = Get-Date
$specificDate = [DateTime]"2023-12-25"

Control Structures

Conditional Statements

powershell
# If statement
if ($age -gt 18) {
    Write-Host "Adult"
} elseif ($age -eq 18) {
    Write-Host "Just turned adult"
} else {
    Write-Host "Minor"
}

# Switch statement
switch ($day) {
    "Monday" { "Start of work week" }
    "Friday" { "TGIF!" }
    "Saturday" { "Weekend!" }
    "Sunday" { "Weekend!" }
    default { "Regular day" }
}

Loops

powershell
# For loop
for ($i = 1; $i -le 10; $i++) {
    Write-Host $i
}

# ForEach loop
$colors = @("red", "green", "blue")
foreach ($color in $colors) {
    Write-Host $color
}

# While loop
$i = 1
while ($i -le 5) {
    Write-Host $i
    $i++
}

# Do-While loop
do {
    $input = Read-Host "Enter 'quit' to exit"
} while ($input -ne "quit")

Functions

Basic Functions

powershell
# Simple function
function Say-Hello {
    Write-Host "Hello World!"
}

# Function with parameters
function Say-HelloTo {
    param(
        [string]$Name
    )
    Write-Host "Hello, $Name!"
}

# Function with return value
function Add-Numbers {
    param(
        [int]$a,
        [int]$b
    )
    return $a + $b
}

# Call functions
Say-Hello
Say-HelloTo -Name "John"
$result = Add-Numbers -a 5 -b 3

Advanced Functions

powershell
function Get-SystemInfo {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]$ComputerName,
        
        [Parameter()]
        [switch]$IncludeServices
    )
    
    $info = Get-ComputerInfo -ComputerName $ComputerName
    
    if ($IncludeServices) {
        $services = Get-Service -ComputerName $ComputerName
        $info | Add-Member -NotePropertyName Services -NotePropertyValue $services
    }
    
    return $info
}

Pipeline and Objects

Pipeline Basics

powershell
# Basic pipeline
Get-Process | Where-Object {$_.CPU -gt 100} | Sort-Object CPU -Descending

# Select specific properties
Get-Process | Select-Object Name, CPU, WorkingSet

# Format output
Get-Process | Format-Table Name, CPU, WorkingSet
Get-Process | Format-List Name, CPU, WorkingSet

Object Manipulation

powershell
# Create custom objects
$person = [PSCustomObject]@{
    Name = "John"
    Age = 30
    City = "New York"
}

# Add properties
$person | Add-Member -NotePropertyName Email -NotePropertyValue "john@email.com"

# Filter objects
Get-Process | Where-Object {$_.ProcessName -like "chrome*"}

# Group objects
Get-Process | Group-Object ProcessName

# Measure objects
Get-Process | Measure-Object WorkingSet -Sum -Average -Maximum

File and Text Processing

File Operations

powershell
# Read file line by line
Get-Content file.txt | ForEach-Object {
    Write-Host "Line: $_"
}

# Search in files
Select-String -Path "*.txt" -Pattern "error"

# Replace text in files
(Get-Content file.txt) -replace "old", "new" | Set-Content file.txt

# Get file information
Get-ItemProperty file.txt
Get-ChildItem *.txt | Select-Object Name, Length, LastWriteTime

Text Processing

powershell
# String operations
$text = "Hello World"
$text.ToUpper()
$text.ToLower()
$text.Replace("World", "PowerShell")
$text.Split(" ")
$text.Substring(0, 5)

# Regular expressions
$text = "Phone: 123-456-7890"
if ($text -match "\d{3}-\d{3}-\d{4}") {
    Write-Host "Phone number found: $($matches[0])"
}

System Administration

Process Management

powershell
# Get processes
Get-Process
Get-Process -Name "notepad"
Get-Process | Where-Object {$_.CPU -gt 100}

# Start process
Start-Process notepad
Start-Process -FilePath "C:\Program Files\App\app.exe" -ArgumentList "/silent"

# Stop process
Stop-Process -Name "notepad"
Stop-Process -Id 1234

Service Management

powershell
# Get services
Get-Service
Get-Service -Name "Spooler"
Get-Service | Where-Object {$_.Status -eq "Running"}

# Start/Stop services
Start-Service -Name "Spooler"
Stop-Service -Name "Spooler"
Restart-Service -Name "Spooler"

# Set service startup type
Set-Service -Name "Spooler" -StartupType Automatic

Registry Operations

powershell
# Navigate registry
Set-Location HKLM:\SOFTWARE

# Get registry values
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion"

# Set registry values
Set-ItemProperty -Path "HKCU:\Software\MyApp" -Name "Setting" -Value "Value"

# Create registry keys
New-Item -Path "HKCU:\Software\MyApp"

Network Operations

Network Commands

powershell
# Test network connectivity
Test-Connection google.com
Test-NetConnection google.com -Port 80

# Get network configuration
Get-NetIPConfiguration
Get-NetAdapter

# DNS operations
Resolve-DnsName google.com
Clear-DnsClientCache

Web Requests

powershell
# Simple web request
Invoke-WebRequest -Uri "https://api.github.com/users/octocat"

# REST API calls
$response = Invoke-RestMethod -Uri "https://api.github.com/users/octocat"
$response.name

# Download files
Invoke-WebRequest -Uri "https://example.com/file.zip" -OutFile "file.zip"

Error Handling

Try-Catch-Finally

powershell
try {
    $result = 10 / 0
} catch [System.DivideByZeroException] {
    Write-Host "Cannot divide by zero!"
} catch {
    Write-Host "An error occurred: $($_.Exception.Message)"
} finally {
    Write-Host "Cleanup code here"
}

Error Variables

powershell
# Check last error
$Error[0]

# Clear errors
$Error.Clear()

# Error action preference
$ErrorActionPreference = "Stop"  # Stop, Continue, SilentlyContinue

Modules and Snap-ins

Module Management

powershell
# List available modules
Get-Module -ListAvailable

# Import module
Import-Module ActiveDirectory

# Get module commands
Get-Command -Module ActiveDirectory

# Install module from PowerShell Gallery
Install-Module -Name Az

Creating Modules

powershell
# Create module file (MyModule.psm1)
function Get-Greeting {
    param([string]$Name)
    return "Hello, $Name!"
}

Export-ModuleMember -Function Get-Greeting

# Import custom module
Import-Module .\MyModule.psm1

Scripting Best Practices

Script Structure

powershell
#Requires -Version 5.1
#Requires -Modules ActiveDirectory

<#
.SYNOPSIS
    Brief description of script
.DESCRIPTION
    Detailed description
.PARAMETER Name
    Description of parameter
.EXAMPLE
    Example usage
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [string]$Name
)

# Script logic here
Write-Verbose "Processing $Name"

Parameter Validation

powershell
param(
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$Name,
    
    [Parameter()]
    [ValidateRange(1,100)]
    [int]$Age,
    
    [Parameter()]
    [ValidateSet("Red","Green","Blue")]
    [string]$Color
)

Advanced Features

Jobs

powershell
# Start background job
$job = Start-Job -ScriptBlock { Get-Process }

# Get job status
Get-Job

# Receive job results
Receive-Job $job

# Remove job
Remove-Job $job

Remoting

powershell
# Enable remoting
Enable-PSRemoting -Force

# Create session
$session = New-PSSession -ComputerName "Server01"

# Run commands remotely
Invoke-Command -Session $session -ScriptBlock { Get-Process }

# Enter interactive session
Enter-PSSession -Session $session

# Close session
Remove-PSSession $session

Desired State Configuration (DSC)

powershell
Configuration WebServer {
    Node "WebServer01" {
        WindowsFeature IIS {
            Ensure = "Present"
            Name = "Web-Server"
        }
        
        File WebContent {
            Ensure = "Present"
            DestinationPath = "C:\inetpub\wwwroot\index.html"
            Contents = "<html><body>Hello World</body></html>"
        }
    }
}

# Compile configuration
WebServer -OutputPath "C:\DSC"

# Apply configuration
Start-DscConfiguration -Path "C:\DSC" -Wait -Verbose

Common Operators

Comparison Operators

powershell
-eq    # Equal
-ne    # Not equal
-gt    # Greater than
-ge    # Greater than or equal
-lt    # Less than
-le    # Less than or equal
-like  # Wildcard comparison
-match # Regular expression match
-contains # Collection contains value
-in    # Value in collection

Logical Operators

powershell
-and   # Logical AND
-or    # Logical OR
-not   # Logical NOT
!      # Logical NOT (alternative)

Useful Cmdlets

Information Gathering

powershell
Get-ComputerInfo
Get-HotFix
Get-EventLog -LogName System -Newest 10
Get-WmiObject -Class Win32_OperatingSystem
Get-CimInstance -ClassName Win32_ComputerSystem

Performance Monitoring

powershell
Get-Counter "\Processor(_Total)\% Processor Time"
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10
Measure-Command { Get-Process }

Resources