DevOps
PowerShell
Practical Examples

Practical PowerShell Examples

This section contains "ready-to-use" PowerShell snippets for common DevOps automation tasks.

1. System Monitoring: High CPU Alert

This script finds the top 5 processes consuming the most CPU.

# Get top 5 CPU consuming processes
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 Name, CPU, WorkingSet
 
# Output as a table
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 | Format-Table

2. File Management: Old Log Cleanup

A classic DevOps task: delete logs older than 30 days.

$path = "C:\Logs\App"
$days = 30
 
# Find and remove old files
Get-ChildItem -Path $path -Filter "*.log" | 
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$days) } | 
    Remove-Item -Confirm:$false
 
Write-Host "Cleanup completed." -ForegroundColor Green

3. Automation: Checking Website Status

Using Invoke-WebRequest to monitor a production URL.

$url = "https://example.com/health"
 
try {
    $response = Invoke-WebRequest -Uri $url -UseBasicParsing
    if ($response.StatusCode -eq 200) {
        Write-Host "Site is healthy!" -ForegroundColor Green
    }
} catch {
    Write-Host "ALERT: Site is down or unreachable!" -ForegroundColor Red
}

4. API Interaction: Parsing JSON

PowerShell makes working with JSON APIs incredibly easy thanks to its object nature.

$api = "https://api.github.com/repos/microsoft/powershell"
$data = Invoke-RestMethod -Uri $api
 
# $data is already a PowerShell object! No parsing needed.
echo "Repository Name: $($data.name)"
echo "Stars: $($data.stargazers_count)"
echo "Description: $($data.description)"

Summary Workflow

ConceptBash EquivalentPowerShell Cmdlet
List FileslsGet-ChildItem
Search TextgrepSelect-String
Get DatedateGet-Date
Process Infops auxGet-Process
HTTP GetcurlInvoke-RestMethod

[!TIP] Use Full Names in Scripts While aliases like ls work, it's a best practice to use the full cmdlet name (Get-ChildItem) in scripts for better readability and cross-version compatibility.