Use this when writing PowerShell script files.
Scripts
PowerShell scripts are .ps1 files with parameters, functions and logic. Sign them or set an execution policy like RemoteSigned, and use #Requires to declare needed modules and versions.
1. Scripts (.ps1) combine commands.
2. #Requires for version/modules.
3. $ErrorActionPreference = 'Stop'.
4. Sign for AllSigned environments.
5. Log with transcripts or logging.
script.ps1 → engine → actions
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Verification path Verify boundary
Parse and lint before execution where tooling is available, inspect #Requires, then run in the same non-interactive host and identity used by production automation. Capture streams and exit behavior, and verify any external mutations with independent read-back. When a script launches native tools, record $LASTEXITCODE immediately after each critical process.
Step 2 Common mistakes Narrow the fault
- Scripts without
Set-StrictMode.
Step 3 Where it fails Narrow the fault
A script that runs interactively may fail unattended due to profiles, current directory, credentials or prompts. Execution-policy acceptance does not show trust, and a signed script can still be logically unsafe. Separate parsing/requirements, host/session context, command execution, process exit semantics and external target state.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
- #Requires declares needed modules and versions.
- Execution policy controls which scripts run.
- Signing scripts proves origin.
Invoke-ScriptAnalyzer -Path script.ps1— lintGet-AuthenticodeSignature script.ps1— signatureGet-ExecutionPolicy -List— policy
ReferenceWhy it matters1 section · depth on demand
In depth
PowerShell scripts (.ps1) are the unit most automation is delivered in. A production-ready script has a predictable structure: help, parameters, strict mode, error handling, logging and a clear exit code.
<#
.SYNOPSIS Backs up switch configurations.
.EXAMPLE .\Backup-Switches.ps1 -Site oslo -WhatIf
#>
[CmdletBinding(SupportsShouldProcess)]
param([Parameter(Mandatory)][string]$Site)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
try {
# work here, honour $PSCmdlet.ShouldProcess()
exit 0
} catch {
Write-Error $_; exit 1
}
Execution policy controls whether scripts may run (RemoteSigned or AllSigned in production); sign scripts used broadly. Run with pwsh -NoProfile -File from schedulers so user profiles do not change behaviour.
ReferenceImportant terms & boundaries1 section · depth on demand
PowerShell mechanics
A .ps1 script is parsed and executed in script scope unless it is dot-sourced into the caller. Parameters, #Requires, scriptblocks, functions and output streams form its execution contract. The host process, current location, profiles, environment, module state and PowerShell edition can all influence a script unless the script makes its prerequisites explicit.
ReferenceConfiguration & state1 section · depth on demand
Authoring and lifecycle
Version scripts in source control, declare parameters and requirements, avoid interactive prompts in unattended automation, and keep configuration/secrets outside source code. Prefer invocation with an explicit path and working directory, and distinguish ordinary execution from dot-sourcing because dot-sourcing intentionally mutates caller scope. Code signing/execution policy can be part of operational policy but is not a comprehensive security boundary.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Configuration & expected output
Concrete examples are shown only when the stored reference contains an actual configuration or output shape for this Topic.
Configuration example
Assumptions: Review target identity, permissions and environment before mutation.
#Requires -Version 7.2
param([Parameter(Mandatory)][string]$Name)
Set-StrictMode -Version LatestVerification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Microsoft Learn documentation reviewed for bounded PowerShell reference claims. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scripts?view=powershell-7.5 · confidence 94%Quick lookup tables
Scripts · PowerShell operational reference
Topic-specific PowerShell runtime identity, persistence, verification, output and failure-boundary lookup.
| Boundary | Scripts reference |
|---|---|
| Runtime identity | PowerShell edition/version + command/module source |
| Persistent intent | Script/module/config prerequisites under source control |
| Verification | Read-only discovery → execution evidence → independent target read-back |
| Output contract | Structured objects/streams before formatting |
| Failure boundary | Separate engine/binding from transport/API/native and target-state failures |
Deep reference
Healthy vs suspicious evidence
Output interpretation
Script output includes every success-stream object not otherwise captured; console appearance is not the full contract. exit can terminate the hosting session/process depending on context, while return exits the current scope. Non-terminating errors may leave the script running, so structured status plus target verification is safer than checking only whether the script reached its final line.