PowerShell coding guidelines
Our PowerShell is scripts and tools: build and deploy scripts, database orchestrators, installers. They run on Windows PowerShell 5.1 and PowerShell 7+, are started by people and by CI, and end with an exit code someone else checks.
PowerShell looks like a shell but behaves like a language with a pipeline: every uncaptured value a function produces becomes part of its return value, errors are non-terminating by default, and native commands report failure only through $LASTEXITCODE. Most PowerShell bugs we've had come from those three facts, so they get their own rules here.
Read the general coding guidelines and general naming conventions first. Microsoft's cmdlet development guidelines apply wherever this page says nothing.
Reference implementations: debee/postgresql/debee.ps1 (orchestrator, one file) and gcp-documenthub/deploy/spfx/build-spfx.ps1 + common.ps1 (a script family with shared functions).
What's different from a typical Bliss service
| Topic | C# / Elixir service | PowerShell script |
|---|---|---|
| Runtime | Long-lived process | One run; exit code is the result |
| Layering | Folders and projects | Sections of one file, or a script family dot-sourcing a shared common.ps1 |
| Function names | PascalCase verbs | Verb-Noun with an approved verb (Get-Verb) |
| Return values | return x |
Everything not captured is returned — the pipeline |
| Errors | Exceptions | Non-terminating by default → set $ErrorActionPreference = 'Stop' |
| External tools | Libraries | Native commands: check $LASTEXITCODE after every call |
| Encoding | UTF-8 | UTF-8 with BOM (Windows PowerShell 5.1 reads BOM-less files as ANSI) |
What stays the same
- Ubiquitous Language — the same nouns as the rest of the system and as a sister implementation in another language:
Invoke-Testsandrun_tests()both implementrunTests. - DRY — patterns, key lists and defaults are script-level constants at the top; shared functions of a script family live in one dot-sourced file.
- Use only what you need — a script is not a module until a second consumer needs
Import-Module. - Restrain yourself — one message function family (
Write-Info/Write-Warning/Write-Error), one way to run psql, one way to fail. - Side layer purity — constants and helpers don't call providers or read configuration.
Script layout
#!/usr/bin/env pwsh
<#
.SYNOPSIS
One sentence.
.DESCRIPTION
What it reads, what it changes, what it needs (PowerShell version, tools on PATH).
.EXAMPLE
./build-spfx.ps1 -Environment test
#>
[CmdletBinding()]
param (
[Parameter(Mandatory)] [string]$Environment,
# One comment line per parameter that needs explaining
[switch]$SkipLibs
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version 3
#region Constants
$script:MigrationFilePattern = '^\d{3}_.*\.sql$'
#endregion
#region Helpers
function ConvertTo-PosixPath { ... }
#endregion
#region Providers
function Get-MigrationFile { ... } # files
function Invoke-Psql { ... } # psql
#endregion
#region Management
function Update-Database { ... }
#endregion
#region Main
try {
Update-Database
exit 0
}
catch {
Write-Error $_ -ErrorAction Continue
exit 1
}
#endregion
| Section | Layer | Holds | Must not |
|---|---|---|---|
Help + param |
I/O | comment-based help, parameters with types and validation attributes | contain logic |
| Constants | Side | $script: patterns, key lists, defaults |
read the environment |
| Helpers | Side | pure functions: convert a path, format a value, split text | call native commands, touch files, write output |
| Providers | Providers | one outside resource each: files, psql, npm, a REST API |
call another provider, decide the workflow |
| Management | Management | operations: which provider, in which order | parse arguments, format output |
| Main | I/O | dispatch of parameters to operations, the exit code |
contain business rules |
#region / #endregion lets editors fold the sections. A script family (several entry scripts sharing functions) puts the Side layer and shared providers into common.ps1 and dot-sources it: . (Join-Path $PSScriptRoot 'common.ps1'). A tool distributed as one file (debee) keeps everything in that file.
The pipeline: return only what you mean to
Anything a function doesn't capture is part of its output. $list.Add($x) returns an index, New-Item returns the item, a native command prints lines — and suddenly a function that "returns an array of results" returns indexes and text too (debee.ps1 1.1.x reported wrong Suites: / Files: counts because of it).
- Capture or discard everything that isn't the result:
[void]$list.Add($x),$null = New-Item ...,... | Out-Null. - Return a collection with the unary comma so a one-element or empty array stays an array:
return ,$results. - Use
[System.Collections.Generic.List[object]]for lists you append to;+=on arrays copies the whole array each time. - Models are
[pscustomobject]@{ ... }built by oneNew-<Model>function, so the shape is defined once.
Errors and exit codes
$ErrorActionPreference = 'Stop'at the top of every script: an error stops the script instead of printing red text and continuing.- Native commands don't throw. After every call:
if ($LASTEXITCODE -ne 0) { throw "psql failed ($LASTEXITCODE)" }. A failing psql that the script doesn't check looks like success. - The script ends with an explicit
exit 0/exit 1; CI reads the exit code, not the colour of the output. - Interactive prompts handle "no answer":
Read-Hostreturns$nullwithout a console (CI, a pipe) — treat that as no, never as consent. A destructive operation also accepts-Yesfor unattended runs.
Output
- Data goes to the pipeline (
Write-Output, or simply the value). - Messages for people go to
Write-Host(colour),Write-Information,Write-Warning,Write-Verbose— never into the pipeline. Wrap them once (Write-Info,Write-Success) and use the wrappers. - Never use
Write-Hostfor something a caller might capture.
Native commands, paths, encoding
- Call native commands with an argument array (
& $psql @arguments), never a string glued with spaces; each element is one argument. - Build paths with
Join-Pathand$PSScriptRoot; never rely on the current directory unless the tool is documented to run from the project folder. - Save
.ps1files as UTF-8 with BOM, LF or CRLF consistently per repo, tabs for indentation (both reference implementations use tabs). - Temp files go to
[IO.Path]::GetTempPath()and are removed infinally.
What this section covers
- Naming conventions — approved verbs and the Bliss-verb mapping, nouns, CLI operations, parameters and variables, scopes, file names, anti-patterns.
See also
- General naming conventions — the shared verb registry.
- General coding structure — the three-layer model and Side layer rules.
- Python guidelines — the sister page.