PowerShell script best practices: functions, error handling, modules and execution policy

Most PowerShell scripts start as a few lines pasted into a console and grow from there. These are the habits that make them easier to read, debug and share once they do. Everything below works in both Windows PowerShell 5.1 and PowerShell 7.
Write advanced functions
Section titled “Write advanced functions”Wrap reusable logic in functions with [CmdletBinding()] and a typed param() block. That gets you parameter validation, tab completion, -Verbose/-Debug support and Get-Help output without extra code.
Set-StrictMode -Version Latest
function Get-AppSetting { <# .SYNOPSIS Reads one setting from a JSON config file.
.PARAMETER Path Path to the JSON config file.
.PARAMETER Name Name of the top-level setting to return.
.EXAMPLE Get-AppSetting -Path .\appsettings.json -Name LogLevel #> [CmdletBinding()] param( [Parameter(Mandatory)] [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] [string]$Path,
[Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string]$Name )
Write-Verbose "Reading $Path" try { $config = Get-Content -Path $Path -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop } catch { throw "Could not read config file '$Path': $($_.Exception.Message)" }
if (-not $config.PSObject.Properties[$Name]) { Write-Warning "Setting '$Name' not found in $Path" return }
$config.$Name}PS> Get-AppSetting -Path .\appsettings.json -Name Port -VerboseVERBOSE: Reading .\appsettings.json8080PS> Get-AppSetting -Path .\appsettings.json -Name MissingWARNING: Setting 'Missing' not found in .\appsettings.jsonWhat this shows:
- Verb-Noun names using approved verbs. Run
Get-Verbfor the list. Unapproved verbs trigger a warning when the function is imported as part of a module. - Validation attributes (
Mandatory,ValidateScript,ValidateNotNullOrEmpty,ValidateSet,ValidateRange) reject bad input before your code runs, with a consistent error message. - Comment-based help. The
<# .SYNOPSIS ... #>block is whatGet-Help Get-AppSetting -Examplesdisplays. Set-StrictMode -Version Latestturns typos such as reading an undefined variable or a non-existent property into errors instead of silent$nulls.- Output objects, not text. The function returns the value itself, so callers can pipe it, compare it, or format it however they like. Use
Write-Verbose,Write-WarningandWrite-Errorfor messages, notWrite-Host.
Avoid hard-coded values (paths, server names, credentials) in the body; make them parameters with sensible defaults.
Make try/catch actually catch
Section titled “Make try/catch actually catch”The most common PowerShell error-handling bug: catch only runs for terminating errors, and most cmdlet failures are non-terminating. They print red text and the script carries on.
try { Get-Item C:\does-not-exist } catch { "never runs" }
try { Get-Item C:\does-not-exist -ErrorAction Stop } catch { "caught: $($_.Exception.Message)" }Add -ErrorAction Stop to the calls you want to handle, as in the example above, or set $ErrorActionPreference = 'Stop' at the top of a script so every error is terminating. Inside catch, $_ is the ErrorRecord; $_.Exception.Message is usually what you want to log.
Use throw (or $PSCmdlet.ThrowTerminatingError() in advanced functions) when the caller can’t sensibly continue, and Write-Error when the failure only affects one item in a pipeline.
Debugging
Section titled “Debugging”- Use VS Code with the PowerShell extension. It has breakpoints, stepping, a variables pane and an integrated console. The Windows PowerShell ISE is still available on Windows but is no longer in active feature development and doesn’t support PowerShell 7, so Microsoft recommends VS Code instead.
Write-VerboseandWrite-Debugare silent by default. They only print when the caller passes-Verbose/-Debug(which[CmdletBinding()]enables) or sets$VerbosePreference/$DebugPreference. That makes them safe to leave in production code.Set-PSBreakpointsets breakpoints from the console, on a line, a command, or whenever a variable is read or written.Get-Help <cmdlet> -FullandGet-Command -Syntax <cmdlet>show parameters and parameter sets. RunUpdate-Helponce to download the full help content.
Lint and test
Section titled “Lint and test”- PSScriptAnalyzer (
Install-Module PSScriptAnalyzer, thenInvoke-ScriptAnalyzer -Path .\script.ps1) flags unapproved verbs, aliases in scripts, unused parameters, plain-text password parameters and more. The VS Code extension runs it as you type. - Pester is the standard test framework for PowerShell. Functions like
Get-AppSettingthat take input as parameters and return objects are easy to test with it.
Organise functions into modules
Section titled “Organise functions into modules”Once you have a handful of related functions, move them into a module instead of dot-sourcing script files:
- Put the functions in a
.psm1file, e.g.AppTools\AppTools.psm1. - Generate a manifest with
New-ModuleManifest -Path .\AppTools\AppTools.psd1 -RootModule AppTools.psm1, and list the public functions inFunctionsToExportso helpers stay private. - Put the folder on a path in
$env:PSModulePathandImport-Module AppTools, or let module auto-loading pick it up.
To share a module publicly, publish it to the PowerShell Gallery with Publish-PSResource (PSResourceGet, included with PowerShell 7.4 and later) or the older Publish-Module from PowerShellGet.
Keep scripts and modules in Git like any other code.
Execution policy
Section titled “Execution policy”The execution policy controls whether PowerShell will run script files (.ps1, .psm1, profiles). It is enforced only on Windows; on Linux and macOS it is always Unrestricted. Microsoft describes it as a safety feature rather than a security boundary: it stops users running scripts by accident, but anyone can bypass it.
The policies are Restricted (no scripts), AllSigned, RemoteSigned, Unrestricted, Bypass, plus Default and Undefined. If nothing is set in any scope, Windows clients behave as Restricted and Windows Server as RemoteSigned.
# See the policy in every scope, highest precedence firstGet-ExecutionPolicy -List
# Allow local scripts and signed downloaded scripts, for your account only (no admin needed)Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
# Run one script with a different policy, without changing any saved settingpwsh -ExecutionPolicy Bypass -File .\script.ps1 # PowerShell 7powershell -ExecutionPolicy Bypass -File .\script.ps1 # Windows PowerShell 5.1Things to know:
- Scope precedence. Group Policy (
MachinePolicy,UserPolicy) wins over everything, thenProcess,CurrentUser,LocalMachine. ASet-ExecutionPolicycall can succeed and still have no effect if a higher scope overrides it. In a domain, administrators set it with the Turn on Script Execution Group Policy setting. - Downloaded files are marked. Browsers and email clients add a “from the internet” marker (an alternate data stream) to downloaded files. Under
RemoteSigned, PowerShell refuses to run those unless they’re signed. After reviewing a script,Unblock-File .\script.ps1removes the marker. Files fetched withInvoke-WebRequestorcurl.exemay not be marked at all, soRemoteSignedis no substitute for reading what you run. - Signing. For scripts you distribute inside an organisation, sign them with
Set-AuthenticodeSignatureand useAllSigned. - Secrets. Don’t put passwords or tokens in scripts. Take a
[PSCredential]parameter, or use the SecretManagement module to read them from a vault.
Further reading
Section titled “Further reading”© 2026 David Li · Home · Blog · RSS ·Classic site · Built with Astro, Starlight and three.js · Logos:Font Awesome Free (CC BY 4.0)