PowerShell Scripting Basics
PowerShell scripts are plain text files with a .ps1 extension. They can automate repetitive tasks, manage systems, and build CI/CD pipelines.
Running Scripts
Section titled “Running Scripts”# Run a script.\deploy.ps1
# Run with parameters.\deploy.ps1 -Environment "prod" -Version "2.1.0"
# Check/change execution policyGet-ExecutionPolicySet-ExecutionPolicy RemoteSigned -Scope CurrentUserScript Structure
Section titled “Script Structure”#Requires -Version 7.0<#.SYNOPSIS Deploy application to an environment..PARAMETER Environment Target environment: dev, staging, prod.EXAMPLE .\deploy.ps1 -Environment staging#>
[CmdletBinding()]param( [Parameter(Mandatory)] [ValidateSet("dev", "staging", "prod")] [string]$Environment,
[string]$Version = "latest",
[switch]$DryRun)
# Script body starts hereFunctions
Section titled “Functions”function Get-FileSize { param( [Parameter(Mandatory)] [string]$Path )
$bytes = (Get-Item $Path).Length switch ($bytes) { { $_ -ge 1GB } { "{0:N2} GB" -f ($_ / 1GB); break } { $_ -ge 1MB } { "{0:N2} MB" -f ($_ / 1MB); break } { $_ -ge 1KB } { "{0:N2} KB" -f ($_ / 1KB); break } default { "$_ bytes" } }}
Get-FileSize -Path "C:\Windows\System32\ntoskrnl.exe"Advanced function with pipeline support:
function ConvertTo-UpperCase { [CmdletBinding()] param( [Parameter(ValueFromPipeline)] [string]$Text )
process { $Text.ToUpper() }}
# Use in pipeline"hello", "world" | ConvertTo-UpperCaseControl Flow
Section titled “Control Flow”# If/ElseIf/Else$score = 85if ($score -ge 90) { "A"} elseif ($score -ge 80) { "B"} else { "C"}
# Switchswitch ($Environment) { "dev" { $url = "http://localhost:5000" } "staging" { $url = "https://staging.example.com" } "prod" { $url = "https://example.com" } default { throw "Unknown environment: $Environment" }}
# For loopfor ($i = 0; $i -lt 5; $i++) { Write-Host "Iteration $i"}
# ForEach$servers = @("web01", "web02", "db01")foreach ($server in $servers) { Write-Host "Checking $server..."}
# While$attempt = 0while ($attempt -lt 3) { $attempt++ Write-Host "Attempt $attempt"}Comparison Operators
Section titled “Comparison Operators”| Operator | Meaning | Example |
|---|---|---|
-eq | Equal | $a -eq $b |
-ne | Not equal | $a -ne $b |
-gt | Greater than | $a -gt 10 |
-lt | Less than | $a -lt 10 |
-ge | Greater or equal | $a -ge 5 |
-le | Less or equal | $a -le 5 |
-like | Wildcard match | $s -like "*.txt" |
-match | Regex match | $s -match "^\d+" |
-contains | Array contains | $arr -contains "item" |
-and | Logical AND | $a -gt 0 -and $b -gt 0 |
-or | Logical OR | $a -eq 1 -or $b -eq 1 |
-not | Logical NOT | -not $flag |
Error Handling
Section titled “Error Handling”# Try/Catch/Finallytry { $content = Get-Content "nonexistent.txt" -ErrorAction Stop} catch [System.IO.FileNotFoundException] { Write-Error "File not found: $_"} catch { Write-Error "Unexpected error: $_"} finally { Write-Host "Cleanup complete"}
# ErrorAction preference$ErrorActionPreference = "Stop" # treat all errors as terminating
# Test if command succeededif ($LASTEXITCODE -ne 0) { throw "Command failed with exit code $LASTEXITCODE"}Working with JSON and APIs
Section titled “Working with JSON and APIs”# Call a REST API$response = Invoke-RestMethod -Uri "https://api.github.com/repos/PowerShell/PowerShell" -Method GET$response.stargazers_count
# POST with body$body = @{ title = "New Issue" body = "Description"} | ConvertTo-Json
Invoke-RestMethod -Uri "https://api.example.com/issues" ` -Method POST ` -ContentType "application/json" ` -Body $body ` -Headers @{ Authorization = "Bearer $token" }
# Read/write JSON files$config = Get-Content "config.json" | ConvertFrom-Json$config.version = "2.0.0"$config | ConvertTo-Json | Out-File "config.json"Practical Example: Deployment Script
Section titled “Practical Example: Deployment Script”[CmdletBinding()]param( [Parameter(Mandatory)] [string]$Environment, [switch]$DryRun)
$ErrorActionPreference = "Stop"
function Write-Step { param([string]$Message) Write-Host "`n► $Message" -ForegroundColor Cyan}
function Invoke-Step { param([string]$Command) if ($DryRun) { Write-Host " [DRY RUN] $Command" -ForegroundColor Yellow } else { Invoke-Expression $Command if ($LASTEXITCODE -ne 0) { throw "Command failed: $Command" } }}
Write-Step "Building application"Invoke-Step "npm run build"
Write-Step "Running tests"Invoke-Step "npm test"
Write-Step "Deploying to $Environment"Invoke-Step "az staticwebapp deploy --environment $Environment"
Write-Host "`n✓ Deployment complete" -ForegroundColor Green