Command Dispatcher Pattern
1# CommandDispatcher.ps1
2param(
3 [Parameter(Mandatory=$true, Position=0)]
4 [string]$Command,
5
6 [Parameter(ValueFromRemainingArguments=$true)]
7 $Arguments
8)
9
10switch ($Command) {
11 "start" {
12 Write-Host "Starting service..."
13 # Your start logic here
14 }
15 "stop" {
16 Write-Host "Stopping service..."
17 # Your stop logic here
18 }
19 "restart" {
20 & $PSCommandPath stop
21 & $PSCommandPath start
22 }
23 "status" {
24 Write-Host "Checking status..."
25 # Your status logic here
26 }
27 "deploy" {
28 $env = $Arguments[0]
29 Write-Host "Deploying to $env..."
30 # Your deploy logic here
31 }
32 default {
33 Write-Host "Usage: .\script.ps1 {start|stop|restart|status|deploy <env>}"
34 exit 1
35 }
36}
Useful Cmdlets
File Operations
1# Get files modified in last 7 days
2Get-ChildItem -Recurse | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-7)}
3
4# Find and delete old files
5Get-ChildItem -Recurse | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} | Remove-Item
6
7# Find large files (>100MB)
8Get-ChildItem -Recurse | Where-Object {$_.Length -gt 100MB} | Sort-Object Length -Descending
9
10# Copy with progress
11Copy-Item -Path "source\*" -Destination "dest\" -Recurse -Verbose
12
13# Create directory structure
14New-Item -ItemType Directory -Path "path\to\nested\directories" -Force
15
16# Get folder sizes
17Get-ChildItem | ForEach-Object {
18 $size = (Get-ChildItem $_.FullName -Recurse | Measure-Object -Property Length -Sum).Sum / 1MB
19 [PSCustomObject]@{
20 Name = $_.Name
21 SizeMB = [math]::Round($size, 2)
22 }
23} | Sort-Object SizeMB -Descending
24
25# Find largest files
26Get-ChildItem -Recurse -File | Sort-Object Length -Descending | Select-Object -First 10 FullName, @{Name="SizeMB";Expression={[math]::Round($_.Length/1MB,2)}}
Text Processing
1# Read file
2Get-Content file.txt
3
4# Read specific lines
5Get-Content file.txt | Select-Object -First 10
6Get-Content file.txt | Select-Object -Last 10
7Get-Content file.txt | Select-Object -Skip 5 -First 10
8
9# Search in files
10Select-String -Path "*.txt" -Pattern "error"
11
12# Replace text
13(Get-Content file.txt) -replace 'old', 'new' | Set-Content file.txt
14
15# Count lines
16(Get-Content file.txt).Count
17
18# Remove duplicates
19Get-Content file.txt | Select-Object -Unique
20
21# Sort and export
22Get-Content file.txt | Sort-Object | Set-Content sorted.txt
23
24# CSV operations
25Import-Csv data.csv | Where-Object {$_.Age -gt 30} | Export-Csv filtered.csv -NoTypeInformation
Process Management
1# Get processes
2Get-Process
3
4# Find process by name
5Get-Process | Where-Object {$_.Name -like "*chrome*"}
6
7# Kill process
8Stop-Process -Name "notepad" -Force
9
10# Kill process by ID
11Stop-Process -Id 1234
12
13# Kill process by port
14Get-NetTCPConnection -LocalPort 8080 | ForEach-Object {Stop-Process -Id $_.OwningProcess -Force}
15
16# Start process
17Start-Process "notepad.exe"
18
19# Run as administrator
20Start-Process powershell -Verb RunAs
21
22# Run and wait
23Start-Process "setup.exe" -Wait
24
25# Background job
26Start-Job -ScriptBlock { Get-Process }
27Get-Job
28Receive-Job -Id 1
Network Commands
1# Test connection
2Test-NetConnection google.com -Port 443
3
4# Download file
5Invoke-WebRequest -Uri "https://example.com/file.zip" -OutFile "file.zip"
6
7# POST JSON
8$body = @{key="value"} | ConvertTo-Json
9Invoke-RestMethod -Uri "https://api.example.com" -Method Post -Body $body -ContentType "application/json"
10
11# GET request
12Invoke-RestMethod -Uri "https://api.example.com/data"
13
14# Test DNS
15Resolve-DnsName example.com
16
17# Get IP configuration
18Get-NetIPConfiguration
19
20# Show listening ports
21Get-NetTCPConnection -State Listen
22
23# Ping sweep
241..254 | ForEach-Object {Test-Connection -ComputerName "192.168.1.$_" -Count 1 -Quiet}
1# Computer info
2Get-ComputerInfo
3
4# OS version
5Get-CimInstance Win32_OperatingSystem
6
7# CPU info
8Get-CimInstance Win32_Processor
9
10# Memory info
11Get-CimInstance Win32_PhysicalMemory
12
13# Disk info
14Get-Disk
15Get-Volume
16
17# Installed software
18Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion
19
20# Windows features
21Get-WindowsOptionalFeature -Online
22
23# Services
24Get-Service
25Get-Service | Where-Object {$_.Status -eq "Running"}
26
27# Event logs
28Get-EventLog -LogName System -Newest 10
29Get-WinEvent -LogName Application -MaxEvents 10
Scripting Techniques
Error Handling
1# Stop on error
2$ErrorActionPreference = "Stop"
3
4# Try-catch
5try {
6 Get-Content "nonexistent.txt"
7} catch {
8 Write-Error "An error occurred: $_"
9}
10
11# Finally block
12try {
13 # Code
14} catch {
15 # Handle error
16} finally {
17 # Cleanup
18}
19
20# Check command exists
21if (Get-Command git -ErrorAction SilentlyContinue) {
22 Write-Host "Git is installed"
23}
Parameters
1param(
2 [Parameter(Mandatory=$true)]
3 [string]$Name,
4
5 [Parameter(Mandatory=$false)]
6 [int]$Age = 0,
7
8 [switch]$Verbose,
9
10 [ValidateSet("Dev","Test","Prod")]
11 [string]$Environment = "Dev"
12)
13
14Write-Host "Name: $Name, Age: $Age, Env: $Environment"
15if ($Verbose) {
16 Write-Host "Verbose mode enabled"
17}
Functions
1function Get-Timestamp {
2 return Get-Date -Format "yyyyMMdd_HHmmss"
3}
4
5function Backup-File {
6 param(
7 [Parameter(Mandatory=$true)]
8 [string]$FilePath,
9
10 [Parameter(Mandatory=$true)]
11 [string]$BackupDir
12 )
13
14 if (-not (Test-Path $FilePath)) {
15 Write-Error "File not found: $FilePath"
16 return
17 }
18
19 $timestamp = Get-Timestamp
20 $fileName = Split-Path $FilePath -Leaf
21 $backupPath = Join-Path $BackupDir "$fileName.$timestamp"
22
23 Copy-Item $FilePath $backupPath
24 Write-Host "Backed up to: $backupPath"
25}
26
27# Advanced function with pipeline support
28function Get-LargeFiles {
29 [CmdletBinding()]
30 param(
31 [Parameter(ValueFromPipeline=$true)]
32 [string]$Path = ".",
33
34 [int]$SizeMB = 100
35 )
36
37 process {
38 Get-ChildItem -Path $Path -Recurse -File |
39 Where-Object {$_.Length -gt ($SizeMB * 1MB)} |
40 Select-Object FullName, @{Name="SizeMB";Expression={[math]::Round($_.Length/1MB,2)}}
41 }
42}
Arrays and Hash Tables
1# Arrays
2$array = @("item1", "item2", "item3")
3$array += "item4"
4$array.Count
5$array[0]
6
7# Iterate
8foreach ($item in $array) {
9 Write-Host $item
10}
11
12# Hash tables (dictionaries)
13$config = @{
14 Host = "localhost"
15 Port = 8080
16 Enabled = $true
17}
18
19$config["Host"]
20$config.Port
21
22# Add/remove
23$config["NewKey"] = "value"
24$config.Remove("NewKey")
25
26# Iterate
27foreach ($key in $config.Keys) {
28 Write-Host "$key = $($config[$key])"
29}
String Operations
1# String length
2$str = "hello"
3$str.Length
4
5# Substring
6$str.Substring(0, 2) # "he"
7
8# Replace
9$str.Replace("l", "L") # "heLLo"
10
11# Split
12$str.Split("l")
13
14# Join
15$array -join ","
16
17# Format
18"Name: {0}, Age: {1}" -f "John", 30
19
20# Contains
21$str.Contains("ell")
22
23# Case conversion
24$str.ToUpper()
25$str.ToLower()
26
27# Trim
28" text ".Trim()
Conditionals
1# File tests
2if (Test-Path "file.txt") {
3 Write-Host "File exists"
4}
5
6# String comparison
7if ($str -eq "value") {
8 Write-Host "Match"
9}
10
11# Numeric comparison
12if ($num -gt 10) {
13 Write-Host "Greater than 10"
14}
15
16# Logical operators
17if ((Test-Path "file.txt") -and (Test-Path "file2.txt")) {
18 Write-Host "Both files exist"
19}
20
21# Pattern matching
22if ($str -like "*pattern*") {
23 Write-Host "Pattern found"
24}
25
26# Regex
27if ($str -match "\d+") {
28 Write-Host "Contains digits"
29}
Loops
1# For loop
2for ($i = 0; $i -lt 10; $i++) {
3 Write-Host $i
4}
5
6# ForEach loop
7foreach ($item in $array) {
8 Write-Host $item
9}
10
11# ForEach-Object (pipeline)
121..10 | ForEach-Object {
13 Write-Host $_
14}
15
16# While loop
17$i = 0
18while ($i -lt 10) {
19 Write-Host $i
20 $i++
21}
22
23# Do-While
24do {
25 Write-Host $i
26 $i++
27} while ($i -lt 10)
One-Liners
1# Backup with timestamp
2Copy-Item file.txt "file.txt.$(Get-Date -Format 'yyyyMMdd_HHmmss')"
3
4# Find and archive
5Compress-Archive -Path (Get-ChildItem -Filter "*.log") -DestinationPath "logs.zip"
6
7# Monitor file changes
8Get-Content -Path "log.txt" -Wait -Tail 10
9
10# Parallel execution
111..10 | ForEach-Object -Parallel { Start-Sleep 1; $_ } -ThrottleLimit 5
12
13# Generate random string
14-join ((65..90) + (97..122) | Get-Random -Count 16 | ForEach-Object {[char]$_})
15
16# Check if admin
17([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
18
19# Quick HTTP server
20Start-Process "python" "-m http.server 8000"
Further Reading
Related Snippets