powershell-style-guide
PowerShell Style Guide
Scope Boundaries
- Use this skill when the task matches the trigger condition described in
description. - Do not use this skill when the primary task falls outside this skill's domain.
Use this skill to write and review PowerShell scripts that are predictable, secure, and maintainable for local automation and CI.
Trigger And Co-activation Reference
- If available, use
references/trigger-matrix.mdfor canonical co-activation rules. - If available, resolve style-guide activation from changed files with
python3 scripts/resolve_style_guides.py <changed-path>.... - If available, validate trigger matrix consistency with
python3 scripts/validate_trigger_matrix_sync.py.
Quality Gate Command Reference
- If available, use
references/quality-gate-command-matrix.mdfor CI check-only and local autofix mapping.
Quick Start Snippets
Script skeleton with strict mode and fail-fast behavior
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
function Write-Failure {
param(
[string]$Message,
[System.Exception]$Exception
)
Write-Error "$Message`n$($Exception.Message)"
}
try {
# Main logic
Write-Host 'Script started'
}
catch {
Write-Failure -Message 'Unhandled failure' -Exception $_.Exception
exit 1
}
Required environment variable check
$apiToken = $env:API_TOKEN
if ([string]::IsNullOrWhiteSpace($apiToken)) {
throw 'API_TOKEN is required.'
}
Parameter validation and approved verbs
function Get-ReleaseArtifact {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$ArtifactId,
[ValidateSet('dev', 'staging', 'prod')]
[string]$Environment = 'dev'
)
# Implementation
"artifact=$ArtifactId env=$Environment"
}
Bounded retry with backoff
function Invoke-WithRetry {
param(
[Parameter(Mandatory)]
[scriptblock]$Operation,
[int]$MaxAttempts = 5,
[int]$DelaySeconds = 2
)
for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
try {
return & $Operation
}
catch {
if ($attempt -eq $MaxAttempts) { throw }
Start-Sleep -Seconds $DelaySeconds
}
}
}
Safe external command invocation
$arguments = @(
'--fail'
'--silent'
'--show-error'
'--header'; "Authorization: Bearer $env:API_TOKEN"
'https://example.com/health'
)
& curl @arguments
Structure And Readability
- Use approved PowerShell verb-noun naming (
Get-,Set-,Invoke-,Test-). - Prefer functions with explicit parameters over global mutable state.
- Keep scripts orchestration-focused and move reusable logic to functions/modules.
- Replace magic numbers with named constants including units.
- Add short comments only where intent is non-obvious.
Parameters, Types, And Data Handling
- Use
[CmdletBinding()]for advanced functions where appropriate. - Validate input with
ValidateNotNullOrEmpty,ValidateSet, or explicit checks. - Use typed parameters/returns for non-trivial data.
- Avoid implicit string parsing when structured objects are available.
- Prefer splatting for complex command arguments.
Error Handling And Control Flow
- Set
$ErrorActionPreference = 'Stop'for fail-fast scripts. - Use
try/catch/finallyfor boundary error handling and cleanup. - Throw specific, actionable errors.
- Do not suppress failures without explicit rationale.
- Return non-zero exit codes for automation-visible failures.
Security And Operational Safety
- Treat all external input as untrusted.
- Avoid command injection by separating command and arguments.
- Never print secrets; redact sensitive values in logs.
- Use least privilege and avoid unnecessary elevation.
- Validate file paths and destructive command targets.
Performance And Scalability
- Prefer pipeline/object operations over repeated text parsing when feasible.
- Avoid unnecessary process spawning in loops.
- Use streaming (
Get-Content -ReadCount, pipeline) for large inputs. - Use bounded retries with explicit constants.
Testing And Verification
- Add Pester tests for critical behavior and failure paths.
- Cover edge cases: missing env vars, invalid parameters, timeout, transient errors.
- Document manual verification where environment dependencies exist.
- Validate idempotency for repeatable automation scripts.
Minimal Pester example
Describe 'Get-ReleaseArtifact' {
It 'throws when ArtifactId is empty' {
{ Get-ReleaseArtifact -ArtifactId '' } | Should -Throw
}
}
CI Required Quality Gates (check-only)
- Run
Invoke-ScriptAnalyzerin check mode with fail-on-issue policy. - Run formatting/lint check (
Invoke-Formatter -Checkor repository equivalent). - Run
Invoke-Pester. - Reject changes that rely on implicit failures or silent fallbacks.
Optional Autofix Commands (local)
- Run
Invoke-Formatter(or repository formatter autofix command). - Apply safe
Invoke-ScriptAnalyzer -Fixresults, then rerun checks.
More from kentoshimizu/sw-agent-skills
graph-algorithms
Graph algorithm workflow for modeling entities/relations and selecting traversal, path, ordering, or flow strategies. Use when correctness or performance depends on graph representation and algorithm choice; do not use for schema-only modeling or deployment topology planning.
14bash-style-guide
Style, review, and refactoring standards for Bash shell scripting. Trigger when `.sh` files, files with `#!/usr/bin/env bash` or `#!/bin/bash`, or CI workflow blocks with `shell: bash` are created, modified, or reviewed and Bash-specific quality controls (quoting safety, error handling, portability, readability) must be enforced. Do not use for generic POSIX `sh`, PowerShell, or language-specific application style rules. In multi-language pull requests, run together with other applicable `*-style-guide` skills.
11architecture-clean-architecture
Clean Architecture workflow for enforcing dependency direction, stable domain boundaries, and use-case-centered application design. Use when teams must separate business rules from frameworks and delivery mechanisms; do not use for isolated module cleanup without boundary implications.
11github-codeowners-management
Govern CODEOWNERS rules so review routing reflects real ownership and risk boundaries on GitHub. Use when repository ownership mapping or mandatory reviewer rules must be defined, updated, or audited; do not use for non-GitHub runtime architecture or data-layer design.
9security-authentication
Security workflow for authentication architecture, credential lifecycle, and session/token assurance. Use when login, identity proofing, MFA, or session security decisions are required; do not use for authorization policy design or non-security quality tuning.
9redis-caching-patterns
Redis caching workflow for latency improvement with explicit key strategy, TTL/invalidation policy, and correctness bounds. Use when Redis-backed caching decisions are required for application performance; do not use for repository-wide architecture governance or release management policy.
9