PowerShell scripting basics: functions, errors, APIs
A PowerShell script is a text file with a .ps1 extension that runs the same commands you type at the prompt, plus parameters, functions, loops and error handling. Scripts are how PowerShell earns its keep: deployment steps, nightly clean-ups, user provisioning, CI build steps and anything else you would otherwise do by hand twice.
This page follows one invented example through every section: a Publish-OrdersPortal.ps1 script that builds, tests and deploys an OrdersPortal web app to an environment. It assumes you know the pipeline and the basic symbols from the PowerShell introduction.
PowerShell was not available in the environment used to write this page, so the samples were not run here. They target PowerShell 7.6 and each cmdlet, parameter and behavior was checked against the PowerShell 7.6 reference on Microsoft Learn; outputs shown are the documented results.
Topics on this page
Section titled “Topics on this page”| Topic | What it covers |
|---|---|
| Running scripts | How to start a script, execution policy, #Requires and comment-based help. |
| Parameters and functions | param(), validation attributes, advanced functions with [CmdletBinding()], pipeline input and -WhatIf. |
| Control flow and operators | if, switch, loops and the comparison operators. |
| Error handling | Terminating and non-terminating errors, try/catch, and failing on native command exit codes. |
| JSON and REST APIs | Invoke-RestMethod, ConvertTo-Json, ConvertFrom-Json and secrets. |
Running scripts
Section titled “Running scripts”Run a script by path: .\Publish-OrdersPortal.ps1 on Windows or ./Publish-OrdersPortal.ps1 elsewhere. PowerShell never runs a script from the current folder by bare name, which protects you from a planted file named like a common command. From another shell or a CI job, use pwsh -File ./Publish-OrdersPortal.ps1 -Environment staging.
On Windows, the execution policy decides whether scripts may run at all. Client editions default to Restricted (no scripts) and Windows Server defaults to RemoteSigned (local scripts run; downloaded scripts must be signed). Set-ExecutionPolicy RemoteSigned -Scope CurrentUser is the usual developer setting. The execution policy is a safety guard against running scripts by accident, not a security boundary; on Linux and macOS it is always Unrestricted and cannot be changed.
Start every script with #Requires lines, which stop the script before it runs if the version or modules are missing, and with comment-based help so Get-Help .\Publish-OrdersPortal.ps1 works like it does for cmdlets.
#Requires -Version 7.4<#.SYNOPSIS Builds, tests and deploys OrdersPortal to one environment..PARAMETER Environment Target environment: dev, staging or prod..PARAMETER Version Version label to stamp on the build. Defaults to the date..EXAMPLE ./Publish-OrdersPortal.ps1 -Environment staging -WhatIf#>[CmdletBinding(SupportsShouldProcess)]param( [Parameter(Mandatory)] [ValidateSet('dev', 'staging', 'prod')] [string] $Environment,
[ValidatePattern('^\d+\.\d+\.\d+$')] [string] $Version = (Get-Date -Format 'yyyy.M.d'))
Set-StrictMode -Version Latest$ErrorActionPreference = 'Stop'Pitfalls:
- Running a script with
.instead of&.. ./script.ps1(dot-sourcing) runs it in your current scope, so its variables and functions leak into your session;& ./script.ps1or a plain path runs it in its own scope. - Treating execution policy as security. Anyone can bypass it with
pwsh -ExecutionPolicy Bypass. Use code signing and application control for real enforcement.
Parameters and functions
Section titled “Parameters and functions”A param() block declares a script’s or function’s inputs. Types ([string], [int], [datetime], [switch]) convert and check values, and validation attributes reject bad input before your code runs: [Parameter(Mandatory)], [ValidateSet()], [ValidateRange()], [ValidatePattern()], [ValidateNotNullOrEmpty()] and [ValidateScript()]. A [switch] parameter is a flag such as -Force that is true when present.
Adding [CmdletBinding()] turns a function into an advanced function that behaves like a compiled cmdlet: it gets the common parameters (-Verbose, -ErrorAction, -WhatIf when you declare SupportsShouldProcess), and $PSCmdlet becomes available. Pipeline input comes from ValueFromPipeline or ValueFromPipelineByPropertyName parameters processed in a process block, which runs once per input object. Name functions with an approved verb and a singular noun. Return objects, not formatted text, so callers can keep piping.
function Get-OrderTotal { [CmdletBinding()] param( [Parameter(Mandatory, ValueFromPipeline)] [pscustomobject] $Order,
[ValidateRange(0, 50)] [int] $DiscountPercent = 0 ) process { $subtotal = ($Order.Lines | Measure-Object -Property LineTotal -Sum).Sum [pscustomobject]@{ OrderId = $Order.Id Total = [math]::Round($subtotal * (100 - $DiscountPercent) / 100, 2) } }}
function Remove-OldBuild { [CmdletBinding(SupportsShouldProcess)] param([Parameter(Mandatory)] [string] $Path, [int] $KeepDays = 14)
Get-ChildItem -Path $Path -Directory | Where-Object LastWriteTime -lt (Get-Date).AddDays(-$KeepDays) | ForEach-Object { if ($PSCmdlet.ShouldProcess($_.FullName, 'Delete build folder')) { Remove-Item -Path $_.FullName -Recurse } }}
$orders = @( [pscustomobject]@{ Id = 1001; Lines = @([pscustomobject]@{ LineTotal = 99.98 }, [pscustomobject]@{ LineTotal = 28.50 }) } [pscustomobject]@{ Id = 1002; Lines = @([pscustomobject]@{ LineTotal = 189.00 }) })$orders | Get-OrderTotal -DiscountPercent 10Remove-OldBuild -Path ./artifacts -WhatIf # lists what would be deleted, deletes nothingGet-OrderTotal emits one object per order (1001 with total 115.63, 1002 with total 170.1), which PowerShell displays as a table.
Pitfalls:
- Using
returnorWrite-Hostfor output. Every uncaptured value in a function is output, so stray expressions ($list.Add($x)returns an index) pollute the result; assign them to$null.Write-Hostwrites to the console only and cannot be piped or captured. - Plural nouns and unapproved verbs.
Get-OrdersorFetch-Ordertrigger warnings when you import a module; useGet-Orderand checkGet-Verb.
Control flow and operators
Section titled “Control flow and operators”PowerShell has the usual statements: if/elseif/else, switch, for, foreach, while, do/until, plus break and continue. switch is more powerful than in C-like languages: it can match wildcards (-Wildcard), regular expressions (-Regex) or script-block conditions, and it loops over every element when given an array. The foreach statement loads the whole collection first and is fast; the ForEach-Object cmdlet streams one item at a time through the pipeline and uses less memory for large inputs.
Comparison operators are words: -eq, -ne, -gt, -ge, -lt, -le, -like (wildcards), -match (regex, fills $Matches), -contains and -in (collection membership), plus -and, -or, -not. String comparisons are case-insensitive by default; prefix with c for case-sensitive (-ceq, -cmatch).
$baseUrl = switch ($Environment) { 'dev' { 'http://localhost:5123' } 'staging' { 'https://staging.ordersportal.example.test' } 'prod' { 'https://ordersportal.example.test' }}
foreach ($attempt in 1..3) { $status = (Invoke-WebRequest -Uri "$baseUrl/health" -SkipHttpErrorCheck).StatusCode if ($status -eq 200) { Write-Verbose "Healthy after $attempt attempt(s)"; break } Start-Sleep -Seconds (2 * $attempt)}
'ORD-1001' -match '^ORD-(\d+)$' # True; $Matches[1] is '1001''Report.CSV' -like '*.csv' # True (case-insensitive)'Report.CSV' -clike '*.csv' # False'prod' -in @('dev', 'staging') # FalsePitfalls:
-containswith a substring.'OrdersPortal' -contains 'Orders'is false:-containstests collection membership. Use-like '*Orders*'or.Contains().- Collection on the left of a comparison.
@(1, 2, 3) -eq 2returns the matching elements (2), not true or false; with$null, put$nullon the left:$null -eq $value.
Error handling
Section titled “Error handling”PowerShell has two kinds of errors. A non-terminating error (a missing file in Get-ChildItem, one failed item out of many) is written to the error stream and the command keeps going. A terminating error stops the statement or script and can be caught with try/catch. -ErrorAction Stop on a command, or $ErrorActionPreference = 'Stop' for the script, promotes non-terminating errors to terminating ones, which is what most automation scripts want. catch blocks can filter on exception type; the error record is in $_ and its exception in $_.Exception.
Native programs (dotnet, git, az, npm) do not take part in this system: they only set $LASTEXITCODE. Since PowerShell 7.4, setting $PSNativeCommandUseErrorActionPreference = $true makes a non-zero exit code raise an error that follows $ErrorActionPreference, so a failing dotnet test stops a script with Stop set. Before 7.4, or for tools that use non-zero codes for success (such as robocopy), check $LASTEXITCODE yourself.
$ErrorActionPreference = 'Stop'$PSNativeCommandUseErrorActionPreference = $true
try { $settings = Get-Content -Path "./deploy/$Environment.json" -Raw | ConvertFrom-Json dotnet build ./src/OrdersPortal.sln -c Release dotnet test ./tests/OrdersPortal.Tests -c Release --no-build}catch [System.Management.Automation.ItemNotFoundException] { Write-Error "No settings file for '$Environment': $($_.Exception.Message)" exit 2}catch [System.Management.Automation.NativeCommandExitException] { Write-Error "Build or tests failed: $($_.Exception.Message)" exit 1}finally { Write-Verbose 'Build step finished'}Get-Content on a missing path raises ItemNotFoundException, not .NET’s FileNotFoundException, so a catch [System.IO.FileNotFoundException] block would never run.
Pitfalls:
try/catchthat never catches. A non-terminating error does not entercatch; add-ErrorAction Stopor set the preference.- Trusting
$?after a pipeline.$?reflects only the last command. Check$LASTEXITCODEimmediately after the native command, before running anything else. Invoke-Expressionon built strings. It runs any text as code, which invites injection and quoting bugs. Call commands directly or with&and an argument array.
JSON and REST APIs
Section titled “JSON and REST APIs”Invoke-RestMethod sends an HTTP request and converts a JSON (or XML) response into objects you can use straight away; Invoke-WebRequest returns the raw response with status code and headers. ConvertTo-Json and ConvertFrom-Json handle files and request bodies. ConvertTo-Json only serializes two levels deep by default and warns when it truncates, so pass -Depth for nested data. Build parameters with a hash table and splat them with @ to keep long calls readable.
Never put tokens in scripts. Read them from the environment ($env:ORDERSPORTAL_API_TOKEN, populated by the CI system’s secret store) or from the SecretManagement module, and pass them with -Authentication Bearer -Token, which takes a SecureString and refuses to send it over plain HTTP.
$token = ConvertTo-SecureString $env:ORDERSPORTAL_API_TOKEN -AsPlainText
$release = @{ version = $Version environment = $Environment components = @(@{ name = 'api'; image = "ordersportal-api:$Version" })}
$request = @{ Uri = "$baseUrl/api/releases" Method = 'Post' ContentType = 'application/json' Body = $release | ConvertTo-Json -Depth 5 Authentication = 'Bearer' Token = $token}
if ($PSCmdlet.ShouldProcess($Environment, "Register release $Version")) { $created = Invoke-RestMethod @request Write-Output "Release $($created.id) registered for $Environment"}
# Update a JSON settings file in place$path = "./deploy/$Environment.json"$config = Get-Content -Path $path -Raw | ConvertFrom-Json$config.version = $Version$config | ConvertTo-Json -Depth 10 | Set-Content -Path $pathPitfalls:
- Silent truncation. Without
-Depth, nested arrays and objects become type names in the output JSON. - Reading JSON line by line.
Get-Contentreturns an array of lines; pass-RawbeforeConvertFrom-Jsonso it receives one string.
Choosing between them
Section titled “Choosing between them”- Use a script for one job run from a scheduler, CI pipeline or a person; use functions in a module (
.psm1with a manifest) for commands that several scripts share. - Use
$ErrorActionPreference = 'Stop'plustry/catchfor automation that must not continue after a failure; keep the defaultContinuefor interactive exploration. - Use
Invoke-RestMethodwhen you want the data,Invoke-WebRequestwhen you need status codes or headers.
Interview questions
Section titled “Interview questions”What is the difference between a terminating and a non-terminating error?
A non-terminating error is reported and the command continues with the next item; a terminating error stops the statement or script and can be caught. -ErrorAction Stop or $ErrorActionPreference = 'Stop' turns the first into the second.
How do you make a script fail when a native tool such as dotnet test fails?
In PowerShell 7.4 and later, set $PSNativeCommandUseErrorActionPreference = $true together with $ErrorActionPreference = 'Stop'. Otherwise check $LASTEXITCODE right after the call and throw when it is non-zero.
What does [CmdletBinding(SupportsShouldProcess)] give you?
The -WhatIf and -Confirm common parameters, and $PSCmdlet.ShouldProcess() to guard each change, so callers can preview destructive actions safely. Cmdlets called inside honor the same preference.
Why does a function sometimes return more values than expected?
Every uncaptured expression is written to the output stream, not just the value after return. Methods that return values (ArrayList.Add, StringBuilder.Append) add extra items; assign them to $null or cast to [void].
Senior scenario: a release script works on a developer laptop but fails randomly in CI. How do you make it reliable?
Pin the runtime (#Requires -Version 7.4, a fixed pwsh version in the pipeline image), add Set-StrictMode -Version Latest, $ErrorActionPreference = 'Stop' and native-command error handling so the first failure stops the run, remove dependence on the current folder by building paths from $PSScriptRoot, read secrets only from the CI secret store, make each step idempotent so reruns are safe, and log with Write-Verbose or a transcript. Then cover the functions with Pester tests that run in the same pipeline.
Related pages
Section titled “Related pages”- PowerShell introduction
- Testing overview: the same ideas apply to Pester tests for PowerShell modules.