Skip to content

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.

Terminal window
# Run a script
.\deploy.ps1
# Run with parameters
.\deploy.ps1 -Environment "prod" -Version "2.1.0"
# Check/change execution policy
Get-ExecutionPolicy
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
Terminal window
#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 here
Terminal window
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:

Terminal window
function ConvertTo-UpperCase {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline)]
[string]$Text
)
process {
$Text.ToUpper()
}
}
# Use in pipeline
"hello", "world" | ConvertTo-UpperCase
Terminal window
# If/ElseIf/Else
$score = 85
if ($score -ge 90) {
"A"
} elseif ($score -ge 80) {
"B"
} else {
"C"
}
# Switch
switch ($Environment) {
"dev" { $url = "http://localhost:5000" }
"staging" { $url = "https://staging.example.com" }
"prod" { $url = "https://example.com" }
default { throw "Unknown environment: $Environment" }
}
# For loop
for ($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 = 0
while ($attempt -lt 3) {
$attempt++
Write-Host "Attempt $attempt"
}
OperatorMeaningExample
-eqEqual$a -eq $b
-neNot equal$a -ne $b
-gtGreater than$a -gt 10
-ltLess than$a -lt 10
-geGreater or equal$a -ge 5
-leLess or equal$a -le 5
-likeWildcard match$s -like "*.txt"
-matchRegex match$s -match "^\d+"
-containsArray contains$arr -contains "item"
-andLogical AND$a -gt 0 -and $b -gt 0
-orLogical OR$a -eq 1 -or $b -eq 1
-notLogical NOT-not $flag
Terminal window
# Try/Catch/Finally
try {
$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 succeeded
if ($LASTEXITCODE -ne 0) {
throw "Command failed with exit code $LASTEXITCODE"
}
Terminal window
# 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"
Terminal window
[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