diff --git a/.agents/skills/powershell-ci-pipeline/SKILL.md b/.agents/skills/powershell-ci-pipeline/SKILL.md new file mode 100644 index 0000000..470932a --- /dev/null +++ b/.agents/skills/powershell-ci-pipeline/SKILL.md @@ -0,0 +1,38 @@ +--- +name: powershell-ci-pipeline +description: Add or fix a CI workflow for a PowerShell project that runs PSScriptAnalyzer and Pester with a coverage gate. Use when asked to set up, create, or repair CI, GitHub Actions, or quality gates for PowerShell code. +--- + +# Set up CI for a PowerShell project + +Read `.github/instructions/powershell-cicd.instructions.md` first, unless it is already loaded. It +holds the rules, a pull request workflow, and a publishing workflow. + +## Steps + +1. Look at what exists: workflow files, a build script, the test folder, and the module manifest. + Extend an existing workflow instead of adding a second one that does the same job. +2. Establish what the project supports from its manifest and `#requires` lines: PowerShell 7.6 only, + or also Windows PowerShell 5.1, and which operating systems. Build the job list from that. Do not + add a version or operating system the project does not claim to support. +3. Add the pull request workflow from the CI rules: install PSScriptAnalyzer and Pester at fixed + versions, run PSScriptAnalyzer and fail on findings, and run the test gate. +4. Put the test gate in a script in the repository, `Tests/Invoke-Tests.ps1` unless the project + keeps its build scripts elsewhere, so that developers can run the same check locally. Use the + runner in `.github/instructions/pester-supporting-docs/test-execution.md`, and pass + `-CodeCoverage` in the job that holds the coverage gate; the alternative is the minimal gate in + `.github/instructions/powershell-pester.instructions.md`, which takes no parameters. Set its test + path and coverage paths to the project's real folders. +5. If the repository has no `PSScriptAnalyzerSettings.psd1`, offer to add the one shown in the CI + rules. Adding it can surface many layout findings in existing code, so say that first. +6. If the repository has no `.gitattributes` file, add one that contains `* text=auto eol=lf` + (CIC-11), so that the tests see the same line endings on every runner. +7. If the module ships compiled help, add the help checks from + `.github/instructions/powershell-platyps.instructions.md`. +8. Validate the workflow file's syntax, and run the gate script locally if you can. + +## Report + +Say which files you added or changed, what each job runs, and what you were able to run locally. A +workflow is not verified until it has run on the CI system; say so, and do not claim that it passes. +Do not add publishing, signing, or deployment steps unless the user asked for them. diff --git a/.agents/skills/powershell-module-help/SKILL.md b/.agents/skills/powershell-module-help/SKILL.md new file mode 100644 index 0000000..ff1eef4 --- /dev/null +++ b/.agents/skills/powershell-module-help/SKILL.md @@ -0,0 +1,35 @@ +--- +name: powershell-module-help +description: Generate, update, validate, or build PowerShell module help with Microsoft.PowerShell.PlatyPS, where help is written as Markdown and shipped as compiled external help. Use when asked to document a module's commands, update help after a parameter change, or fix Get-Help output for a module. +--- + +# Maintain module help with PlatyPS + +Read `.github/instructions/powershell-platyps.instructions.md` first, unless it is already loaded. It +holds the rules and every command used below. + +## Steps + +1. Confirm the tool. `Get-Module -ListAvailable Microsoft.PowerShell.PlatyPS` must show version 1.0.3 + or later. Do not use the retired `platyPS` module or its commands. +2. Find the state of the module's help: whether `docs//` exists, which exported commands + have a Markdown file, and whether the exported functions carry `.EXTERNALHELP`. +3. For a command with no Markdown yet: make sure the function has complete comment-based help, run + `New-MarkdownCommandHelp` with `-Locale`, and only then add `.EXTERNALHELP` and reduce the comment + block to a one-line `.SYNOPSIS`. The order matters. +4. For a command whose parameters changed: import the module and run `Update-MarkdownCommandHelp`, + then update the module page. Do not edit syntax blocks or parameter metadata by hand. +5. Write the content. Replace every `{{ Fill in ... }}` placeholder, put each example's command in a + fenced `powershell` block, and describe only what the command does. +6. Validate with the checks in the PlatyPS rules: structure, leftover placeholders, and relative + links. +7. Build the compiled help with `Export-MamlCommandHelp`, copy it into the module's culture folder, + and confirm with `Get-Help -Full` against the imported module that the text and the + examples appear. Before a release, repeat the check against the packaged module on a + case-sensitive file system (PLT-14). + +## Report + +List the Markdown files you created or changed, the result of each validation, and what `Get-Help` +showed. Mention any command whose description or examples you could not write from the code alone, +and ask the user for the missing facts instead of inventing them. diff --git a/.agents/skills/powershell-new-function/SKILL.md b/.agents/skills/powershell-new-function/SKILL.md new file mode 100644 index 0000000..9f8cc2f --- /dev/null +++ b/.agents/skills/powershell-new-function/SKILL.md @@ -0,0 +1,43 @@ +--- +name: powershell-new-function +description: Write a new PowerShell function with its comment-based help and Pester tests, following this repository's PowerShell standards. Use when asked to create, add, or scaffold a PowerShell function or command. +--- + +# Write a new PowerShell function + +Read these before writing code, unless they are already loaded: + +- `.github/copilot-instructions.md`, or `AGENTS.md` if the repository has no such file (the core rules + and the function template) +- `.github/instructions/powershell-functions.instructions.md` +- `.github/instructions/powershell-error-handling.instructions.md` +- `.github/instructions/powershell-help.instructions.md` + +## Steps + +1. Find the target version. Read the `#requires -Version` lines and the nearest module manifest. If the + project declares nothing and it is not clear which target applies, ask. If you cannot ask, target + PowerShell 7.6 and say that you assumed it. +2. Choose the name. Use a verb that `Get-Verb` lists and a singular noun. Search the repository for an + existing function with that name or purpose before creating a new one. +3. Decide where the file goes. In a module, an exported function goes in `Public/.ps1` and its + name is added to `FunctionsToExport` in the manifest; an internal one goes in `Private/.ps1`. + Outside a module, put it where the user asked. +4. Write the function in the shape of the function template: help first, `[CmdletBinding()]`, + `[OutputType()]`, typed and validated parameters, a `process` block for pipeline input, `try` and + `$PSCmdlet.ThrowTerminatingError()` for a failure that ends the function, + `$PSCmdlet.WriteError()` for a failure of one item, and objects written to the pipeline as they are + produced. +5. If the function changes state, add `SupportsShouldProcess` and guard each change with + `$PSCmdlet.ShouldProcess()`. If it only reads, do not. +6. Write the tests following `.github/instructions/powershell-pester.instructions.md`, in + `Tests/Unit/.Tests.ps1` (MOD-01) or beside the tests the project already has. Cover each + parameter set, the documented output, each validation failure, and each error path. +7. Run PSScriptAnalyzer on the new files, with `-Settings ./PSScriptAnalyzerSettings.psd1` when that + file exists, and run the tests. Fix what they report. + +## Report + +Say which files you created or changed, which PowerShell version you targeted and why, what you ran +and what it reported, and anything you could not verify. Ask instead of guessing when the purpose, the +inputs, or the output of the function is unclear. diff --git a/.agents/skills/powershell-new-module/SKILL.md b/.agents/skills/powershell-new-module/SKILL.md new file mode 100644 index 0000000..a756dd9 --- /dev/null +++ b/.agents/skills/powershell-new-module/SKILL.md @@ -0,0 +1,40 @@ +--- +name: powershell-new-module +description: Create a new PowerShell module with a manifest, a root module, Public and Private folders, a first function, and Pester tests, following this repository's PowerShell standards. Use when asked to create, scaffold, or start a PowerShell module. +--- + +# Create a new PowerShell module + +Read these before writing files, unless they are already loaded: + +- `.github/copilot-instructions.md`, or `AGENTS.md` if the repository has no such file (the core rules + and the function template) +- `.github/instructions/powershell-modules.instructions.md` +- `.github/instructions/powershell-version.instructions.md` + +## Steps + +1. Ask for, or confirm, the module name, what it is for, and whether it must run on Windows PowerShell + 5.1. Without a 5.1 requirement, target PowerShell 7.6. +2. Create the layout from the module rules: `ModuleName.psd1`, `ModuleName.psm1`, `Public/`, + `Private/`, and `Tests/`, with the unit tests under `Tests/Unit/` (MOD-01). Add + `Tests/Integration/` and `Tests/Performance/` when the module has such tests, and `Classes/` only + if the module defines a class. Do not create empty folders for things the module does not have. +3. Write the manifest with literal values only. Generate the GUID once with `New-Guid` and paste the + result. Set `PowerShellVersion` and `CompatiblePSEditions` for the target. List exported functions + by name. Take `Author` and the project links from the user or the repository; leave out what you do + not know. +4. Write the root module exactly as the module rules show it: a `#Requires -Version` line that + matches the manifest's `PowerShellVersion` (MOD-08), strict mode, then `Classes`, `Private`, and + `Public` dot-sourced in that order, failing the import if a file fails to load. +5. Add the first function with the `powershell-new-function` skill, or follow its steps. +6. Import the module in a new session with `Import-Module ./ModuleName.psd1 -Force`, confirm that + `Get-Command -Module ModuleName` lists exactly the exported functions, and run the tests. +7. Add a `README.md` that follows `.github/instructions/powershell-readme.instructions.md`. + +## Report + +List the files you created, the target version, and the results of the import check and the tests. Do +not add dependencies or CI workflows unless the user asked for them; mention them as possible next +steps instead. Every module generates its command help with PlatyPS (PLT-10): do that with the +`powershell-module-help` skill, or say that it is still to do. diff --git a/.agents/skills/powershell-performance-review/SKILL.md b/.agents/skills/powershell-performance-review/SKILL.md new file mode 100644 index 0000000..fe836fb --- /dev/null +++ b/.agents/skills/powershell-performance-review/SKILL.md @@ -0,0 +1,37 @@ +--- +name: powershell-performance-review +description: Find and fix performance problems in PowerShell code by measuring it. Use when asked to optimize, speed up, profile, or analyze the performance of PowerShell code. +--- + +# Performance review of PowerShell code + +The collection and string rules are in `.github/instructions/powershell-style.instructions.md` +(STY-22, STY-40 to STY-45, and STY-50). Read them first, unless that file is already loaded. + +## Steps + +1. Ask what is slow and how large the real input is, if the user has not said. An improvement that + matters at 100,000 items can be noise at 100. +2. Measure before changing anything. Use `Measure-Command` around the code with realistic input, and + repeat the run several times. If you cannot run the code, say so and present your suggestions as + unmeasured. +3. Look for the causes that usually dominate: + - An array grown with `+=` inside a loop, or a string extended with `+=` about 100 times or + more. Below that, `+=` on a string is fine (STY-22); do not report it. + - A command called once for each item when it accepts all items at once, or a remote or disk call + inside a loop that could be made once outside it. + - Filtering with `Where-Object` what the source command could have filtered. + - A lookup that scans a collection inside a loop, where a hashtable built once would do. + - `ForEach-Object` over a large collection that is already in memory. + - Output piped to `Out-Null` in a tight loop. +4. Change one thing at a time and measure again with the same input. Keep a change only if it is + faster and the output is the same. +5. Do not trade correctness or clarity for a small gain, and do not add parallelism + (`ForEach-Object -Parallel`, thread jobs) unless the work is slow per item and the items are + independent. + +## Report + +Give the measurements before and after, with the input size and the PowerShell version, for each +change you kept. Performance figures MUST come from runs you made; do not estimate percentages. List +what you tried that did not help. diff --git a/.agents/skills/powershell-review/SKILL.md b/.agents/skills/powershell-review/SKILL.md new file mode 100644 index 0000000..0325569 --- /dev/null +++ b/.agents/skills/powershell-review/SKILL.md @@ -0,0 +1,35 @@ +--- +name: powershell-review +description: Review PowerShell code against this repository's PowerShell standards and report findings by rule ID. Use when asked to review, validate, analyze, or check PowerShell code for quality or standards compliance. +--- + +# Review PowerShell code against the standards + +Read the core rules (`.github/copilot-instructions.md`, or `AGENTS.md` if the repository has no such +file) and the topic files they list for the kind of file under review, unless they are already +loaded. Every rule has an ID such as `ERR-10`; cite it. + +## Steps + +1. Establish the target version from `#requires` lines and the module manifest. Judge the code + against that version, not against the newest one. +2. Run the tools first when you can: PSScriptAnalyzer, with `-Settings ./PSScriptAnalyzerSettings.psd1` + when that file exists, and the existing tests. Include what they report. +3. Read the code for what tools cannot see, in this order: + 1. Correctness: logic errors, unhandled failure paths, wrong assumptions about a command's output. + 2. Error handling: the ERR rules, in particular `throw` in advanced functions, a missing + `-ErrorAction Stop` inside `try`, and empty or silent `catch` blocks. + 3. Security: the SEC rules. + 4. Functions and output: the FUN rules. + 5. Version fit: the VER rules. + 6. Help and style: the DOC and STY rules. +4. Confirm each finding before reporting it. Read the surrounding code, and where behaviour is in + doubt, run a small test. Do not report a rule violation in code that the change did not touch, + unless it is a defect. + +## Report + +List findings with the most serious first. For each one give the file and line, the rule ID or the +word "defect", what is wrong, and the corrected code. Separate requirements (MUST) from +recommendations (SHOULD). State what you ran and what you did not check. If nothing is wrong, say so; +do not invent findings. diff --git a/.agents/skills/powershell-security-review/SKILL.md b/.agents/skills/powershell-security-review/SKILL.md new file mode 100644 index 0000000..9e79603 --- /dev/null +++ b/.agents/skills/powershell-security-review/SKILL.md @@ -0,0 +1,41 @@ +--- +name: powershell-security-review +description: Review PowerShell code for security problems such as exposed secrets, unsafe credential handling, command or path injection, and disabled certificate checks. Use when asked for a security review or audit of PowerShell code. +--- + +# Security review of PowerShell code + +Read `.github/instructions/powershell-security.instructions.md` first, unless it is already loaded. + +## Steps + +1. Map where data enters the code: parameters, files, environment variables, web responses, and + pipeline input. Treat each as untrusted unless the code proves otherwise. +2. Follow each input to where it is used and check: + - Secrets and credentials: SEC-01 to SEC-08, and SEC-50 to SEC-53 where the code uses a secret + vault. Search for literals that look like passwords, tokens, keys, and connection strings, + including in comments, defaults, and test data. + - Command construction: SEC-10. Look for `Invoke-Expression`, `[scriptblock]::Create()`, + `Start-Process` with a built argument string, and strings passed to `cmd /c` or `pwsh -Command`. + - Paths: SEC-12. Look for input joined into a path that is then read, written, or deleted. + - Queries: SEC-13. + - Input checks: SEC-11 and SEC-16 to SEC-19. + - Code signing, where the code signs files: SEC-30 to SEC-35. + - Transport and privilege: SEC-14 and SEC-15. +3. Check what the code writes. Verbose, debug, warning, and error messages, log files, and exported + files must not contain secrets or personal data. +4. Run PSScriptAnalyzer. Its rules `PSAvoidUsingPlainTextForPassword`, + `PSAvoidUsingConvertToSecureStringWithPlainText`, `PSAvoidUsingUsernameAndPasswordParams`, and + `PSAvoidUsingInvokeExpression` cover part of this. +5. Confirm each finding by reading the full path from input to use. A pattern match alone is not a + finding. The patterns of SEC-40 find candidates. `Add-Type -TypeDefinition` is a Medium finding + (SEC-41). + +## Report + +List findings with the most serious first, each with its tier (Critical, High, Medium, or Low), and +state the overall risk as the highest tier found (SEC-42): file and line, rule ID, how the problem +could be exploited or exposed, and the corrected code. Say which inputs you traced and which you did +not. If you find a real secret, tell the user that it must be revoked and replaced; removing it from +the file does not remove it from the repository history. This review covers the code only. It is not +a compliance assessment, so do not state that the code meets any regulation or framework. diff --git a/.agents/skills/powershell-write-tests/SKILL.md b/.agents/skills/powershell-write-tests/SKILL.md new file mode 100644 index 0000000..6a0ee0f --- /dev/null +++ b/.agents/skills/powershell-write-tests/SKILL.md @@ -0,0 +1,33 @@ +--- +name: powershell-write-tests +description: Write or extend Pester 6 tests for existing PowerShell code, following this repository's testing rules. Use when asked to add tests, raise coverage, or test a PowerShell function, script, or module. +--- + +# Write Pester tests for PowerShell code + +Read `.github/instructions/powershell-pester.instructions.md` first, unless it is already loaded. It +holds the rules, a complete test file, and a table of assertion behaviour. + +## Steps + +1. Read the code under test completely: its parameters and parameter sets, validation attributes, + output type, every `catch`, and every call that leaves the process (network, files, other modules, + the clock). +2. Look at an existing test file in the repository. Keep its assertion style and layout. In a new + file use the Pester 6 `Should-*` assertions. +3. List the behaviours to test before writing any: each parameter set, the documented output, each + validation failure, each error path, pipeline input, and for a `Test-` function both outcomes. +4. Write the file so that it runs on its own: a versioned `#Requires` for Pester, the code loaded in a + top-level `BeforeAll`, and test data built in `BeforeDiscovery`. +5. Mock only what crosses a boundary. For code inside a module, pass `-ModuleName` to `Mock` and + `Should-Invoke`, and reach private functions with `InModuleScope`. +6. Make every test able to fail: assert specific values, assert the count before reading by index, and + assert expected errors with `Should-Throw` or by counting error records. +7. Run the tests. A test that passes on its first run has not been shown to work: break the behaviour + it covers, or the expected value, once to see it fail, then restore it. + +## Report + +Say which behaviours are covered and which are not, the pass and fail counts, and the coverage figure +if you measured it. If a test exposes a defect in the code, report the defect; do not weaken the test +to make it pass, and do not change the code under test unless the user asked for that. diff --git a/.claude/commands/powershell-standards/.keep b/.claude/commands/powershell-standards/.keep deleted file mode 100644 index ff5471a..0000000 --- a/.claude/commands/powershell-standards/.keep +++ /dev/null @@ -1,2 +0,0 @@ -This folder is kept so that sync workflows written for earlier versions still find it. -The prompt files it mirrored were replaced by skills. diff --git a/.claude/skills/powershell-ci-pipeline/SKILL.md b/.claude/skills/powershell-ci-pipeline/SKILL.md new file mode 100644 index 0000000..470932a --- /dev/null +++ b/.claude/skills/powershell-ci-pipeline/SKILL.md @@ -0,0 +1,38 @@ +--- +name: powershell-ci-pipeline +description: Add or fix a CI workflow for a PowerShell project that runs PSScriptAnalyzer and Pester with a coverage gate. Use when asked to set up, create, or repair CI, GitHub Actions, or quality gates for PowerShell code. +--- + +# Set up CI for a PowerShell project + +Read `.github/instructions/powershell-cicd.instructions.md` first, unless it is already loaded. It +holds the rules, a pull request workflow, and a publishing workflow. + +## Steps + +1. Look at what exists: workflow files, a build script, the test folder, and the module manifest. + Extend an existing workflow instead of adding a second one that does the same job. +2. Establish what the project supports from its manifest and `#requires` lines: PowerShell 7.6 only, + or also Windows PowerShell 5.1, and which operating systems. Build the job list from that. Do not + add a version or operating system the project does not claim to support. +3. Add the pull request workflow from the CI rules: install PSScriptAnalyzer and Pester at fixed + versions, run PSScriptAnalyzer and fail on findings, and run the test gate. +4. Put the test gate in a script in the repository, `Tests/Invoke-Tests.ps1` unless the project + keeps its build scripts elsewhere, so that developers can run the same check locally. Use the + runner in `.github/instructions/pester-supporting-docs/test-execution.md`, and pass + `-CodeCoverage` in the job that holds the coverage gate; the alternative is the minimal gate in + `.github/instructions/powershell-pester.instructions.md`, which takes no parameters. Set its test + path and coverage paths to the project's real folders. +5. If the repository has no `PSScriptAnalyzerSettings.psd1`, offer to add the one shown in the CI + rules. Adding it can surface many layout findings in existing code, so say that first. +6. If the repository has no `.gitattributes` file, add one that contains `* text=auto eol=lf` + (CIC-11), so that the tests see the same line endings on every runner. +7. If the module ships compiled help, add the help checks from + `.github/instructions/powershell-platyps.instructions.md`. +8. Validate the workflow file's syntax, and run the gate script locally if you can. + +## Report + +Say which files you added or changed, what each job runs, and what you were able to run locally. A +workflow is not verified until it has run on the CI system; say so, and do not claim that it passes. +Do not add publishing, signing, or deployment steps unless the user asked for them. diff --git a/.claude/skills/powershell-module-help/SKILL.md b/.claude/skills/powershell-module-help/SKILL.md new file mode 100644 index 0000000..ff1eef4 --- /dev/null +++ b/.claude/skills/powershell-module-help/SKILL.md @@ -0,0 +1,35 @@ +--- +name: powershell-module-help +description: Generate, update, validate, or build PowerShell module help with Microsoft.PowerShell.PlatyPS, where help is written as Markdown and shipped as compiled external help. Use when asked to document a module's commands, update help after a parameter change, or fix Get-Help output for a module. +--- + +# Maintain module help with PlatyPS + +Read `.github/instructions/powershell-platyps.instructions.md` first, unless it is already loaded. It +holds the rules and every command used below. + +## Steps + +1. Confirm the tool. `Get-Module -ListAvailable Microsoft.PowerShell.PlatyPS` must show version 1.0.3 + or later. Do not use the retired `platyPS` module or its commands. +2. Find the state of the module's help: whether `docs//` exists, which exported commands + have a Markdown file, and whether the exported functions carry `.EXTERNALHELP`. +3. For a command with no Markdown yet: make sure the function has complete comment-based help, run + `New-MarkdownCommandHelp` with `-Locale`, and only then add `.EXTERNALHELP` and reduce the comment + block to a one-line `.SYNOPSIS`. The order matters. +4. For a command whose parameters changed: import the module and run `Update-MarkdownCommandHelp`, + then update the module page. Do not edit syntax blocks or parameter metadata by hand. +5. Write the content. Replace every `{{ Fill in ... }}` placeholder, put each example's command in a + fenced `powershell` block, and describe only what the command does. +6. Validate with the checks in the PlatyPS rules: structure, leftover placeholders, and relative + links. +7. Build the compiled help with `Export-MamlCommandHelp`, copy it into the module's culture folder, + and confirm with `Get-Help -Full` against the imported module that the text and the + examples appear. Before a release, repeat the check against the packaged module on a + case-sensitive file system (PLT-14). + +## Report + +List the Markdown files you created or changed, the result of each validation, and what `Get-Help` +showed. Mention any command whose description or examples you could not write from the code alone, +and ask the user for the missing facts instead of inventing them. diff --git a/.claude/skills/powershell-new-function/SKILL.md b/.claude/skills/powershell-new-function/SKILL.md new file mode 100644 index 0000000..9f8cc2f --- /dev/null +++ b/.claude/skills/powershell-new-function/SKILL.md @@ -0,0 +1,43 @@ +--- +name: powershell-new-function +description: Write a new PowerShell function with its comment-based help and Pester tests, following this repository's PowerShell standards. Use when asked to create, add, or scaffold a PowerShell function or command. +--- + +# Write a new PowerShell function + +Read these before writing code, unless they are already loaded: + +- `.github/copilot-instructions.md`, or `AGENTS.md` if the repository has no such file (the core rules + and the function template) +- `.github/instructions/powershell-functions.instructions.md` +- `.github/instructions/powershell-error-handling.instructions.md` +- `.github/instructions/powershell-help.instructions.md` + +## Steps + +1. Find the target version. Read the `#requires -Version` lines and the nearest module manifest. If the + project declares nothing and it is not clear which target applies, ask. If you cannot ask, target + PowerShell 7.6 and say that you assumed it. +2. Choose the name. Use a verb that `Get-Verb` lists and a singular noun. Search the repository for an + existing function with that name or purpose before creating a new one. +3. Decide where the file goes. In a module, an exported function goes in `Public/.ps1` and its + name is added to `FunctionsToExport` in the manifest; an internal one goes in `Private/.ps1`. + Outside a module, put it where the user asked. +4. Write the function in the shape of the function template: help first, `[CmdletBinding()]`, + `[OutputType()]`, typed and validated parameters, a `process` block for pipeline input, `try` and + `$PSCmdlet.ThrowTerminatingError()` for a failure that ends the function, + `$PSCmdlet.WriteError()` for a failure of one item, and objects written to the pipeline as they are + produced. +5. If the function changes state, add `SupportsShouldProcess` and guard each change with + `$PSCmdlet.ShouldProcess()`. If it only reads, do not. +6. Write the tests following `.github/instructions/powershell-pester.instructions.md`, in + `Tests/Unit/.Tests.ps1` (MOD-01) or beside the tests the project already has. Cover each + parameter set, the documented output, each validation failure, and each error path. +7. Run PSScriptAnalyzer on the new files, with `-Settings ./PSScriptAnalyzerSettings.psd1` when that + file exists, and run the tests. Fix what they report. + +## Report + +Say which files you created or changed, which PowerShell version you targeted and why, what you ran +and what it reported, and anything you could not verify. Ask instead of guessing when the purpose, the +inputs, or the output of the function is unclear. diff --git a/.claude/skills/powershell-new-module/SKILL.md b/.claude/skills/powershell-new-module/SKILL.md new file mode 100644 index 0000000..a756dd9 --- /dev/null +++ b/.claude/skills/powershell-new-module/SKILL.md @@ -0,0 +1,40 @@ +--- +name: powershell-new-module +description: Create a new PowerShell module with a manifest, a root module, Public and Private folders, a first function, and Pester tests, following this repository's PowerShell standards. Use when asked to create, scaffold, or start a PowerShell module. +--- + +# Create a new PowerShell module + +Read these before writing files, unless they are already loaded: + +- `.github/copilot-instructions.md`, or `AGENTS.md` if the repository has no such file (the core rules + and the function template) +- `.github/instructions/powershell-modules.instructions.md` +- `.github/instructions/powershell-version.instructions.md` + +## Steps + +1. Ask for, or confirm, the module name, what it is for, and whether it must run on Windows PowerShell + 5.1. Without a 5.1 requirement, target PowerShell 7.6. +2. Create the layout from the module rules: `ModuleName.psd1`, `ModuleName.psm1`, `Public/`, + `Private/`, and `Tests/`, with the unit tests under `Tests/Unit/` (MOD-01). Add + `Tests/Integration/` and `Tests/Performance/` when the module has such tests, and `Classes/` only + if the module defines a class. Do not create empty folders for things the module does not have. +3. Write the manifest with literal values only. Generate the GUID once with `New-Guid` and paste the + result. Set `PowerShellVersion` and `CompatiblePSEditions` for the target. List exported functions + by name. Take `Author` and the project links from the user or the repository; leave out what you do + not know. +4. Write the root module exactly as the module rules show it: a `#Requires -Version` line that + matches the manifest's `PowerShellVersion` (MOD-08), strict mode, then `Classes`, `Private`, and + `Public` dot-sourced in that order, failing the import if a file fails to load. +5. Add the first function with the `powershell-new-function` skill, or follow its steps. +6. Import the module in a new session with `Import-Module ./ModuleName.psd1 -Force`, confirm that + `Get-Command -Module ModuleName` lists exactly the exported functions, and run the tests. +7. Add a `README.md` that follows `.github/instructions/powershell-readme.instructions.md`. + +## Report + +List the files you created, the target version, and the results of the import check and the tests. Do +not add dependencies or CI workflows unless the user asked for them; mention them as possible next +steps instead. Every module generates its command help with PlatyPS (PLT-10): do that with the +`powershell-module-help` skill, or say that it is still to do. diff --git a/.claude/skills/powershell-performance-review/SKILL.md b/.claude/skills/powershell-performance-review/SKILL.md new file mode 100644 index 0000000..fe836fb --- /dev/null +++ b/.claude/skills/powershell-performance-review/SKILL.md @@ -0,0 +1,37 @@ +--- +name: powershell-performance-review +description: Find and fix performance problems in PowerShell code by measuring it. Use when asked to optimize, speed up, profile, or analyze the performance of PowerShell code. +--- + +# Performance review of PowerShell code + +The collection and string rules are in `.github/instructions/powershell-style.instructions.md` +(STY-22, STY-40 to STY-45, and STY-50). Read them first, unless that file is already loaded. + +## Steps + +1. Ask what is slow and how large the real input is, if the user has not said. An improvement that + matters at 100,000 items can be noise at 100. +2. Measure before changing anything. Use `Measure-Command` around the code with realistic input, and + repeat the run several times. If you cannot run the code, say so and present your suggestions as + unmeasured. +3. Look for the causes that usually dominate: + - An array grown with `+=` inside a loop, or a string extended with `+=` about 100 times or + more. Below that, `+=` on a string is fine (STY-22); do not report it. + - A command called once for each item when it accepts all items at once, or a remote or disk call + inside a loop that could be made once outside it. + - Filtering with `Where-Object` what the source command could have filtered. + - A lookup that scans a collection inside a loop, where a hashtable built once would do. + - `ForEach-Object` over a large collection that is already in memory. + - Output piped to `Out-Null` in a tight loop. +4. Change one thing at a time and measure again with the same input. Keep a change only if it is + faster and the output is the same. +5. Do not trade correctness or clarity for a small gain, and do not add parallelism + (`ForEach-Object -Parallel`, thread jobs) unless the work is slow per item and the items are + independent. + +## Report + +Give the measurements before and after, with the input size and the PowerShell version, for each +change you kept. Performance figures MUST come from runs you made; do not estimate percentages. List +what you tried that did not help. diff --git a/.claude/skills/powershell-review/SKILL.md b/.claude/skills/powershell-review/SKILL.md new file mode 100644 index 0000000..0325569 --- /dev/null +++ b/.claude/skills/powershell-review/SKILL.md @@ -0,0 +1,35 @@ +--- +name: powershell-review +description: Review PowerShell code against this repository's PowerShell standards and report findings by rule ID. Use when asked to review, validate, analyze, or check PowerShell code for quality or standards compliance. +--- + +# Review PowerShell code against the standards + +Read the core rules (`.github/copilot-instructions.md`, or `AGENTS.md` if the repository has no such +file) and the topic files they list for the kind of file under review, unless they are already +loaded. Every rule has an ID such as `ERR-10`; cite it. + +## Steps + +1. Establish the target version from `#requires` lines and the module manifest. Judge the code + against that version, not against the newest one. +2. Run the tools first when you can: PSScriptAnalyzer, with `-Settings ./PSScriptAnalyzerSettings.psd1` + when that file exists, and the existing tests. Include what they report. +3. Read the code for what tools cannot see, in this order: + 1. Correctness: logic errors, unhandled failure paths, wrong assumptions about a command's output. + 2. Error handling: the ERR rules, in particular `throw` in advanced functions, a missing + `-ErrorAction Stop` inside `try`, and empty or silent `catch` blocks. + 3. Security: the SEC rules. + 4. Functions and output: the FUN rules. + 5. Version fit: the VER rules. + 6. Help and style: the DOC and STY rules. +4. Confirm each finding before reporting it. Read the surrounding code, and where behaviour is in + doubt, run a small test. Do not report a rule violation in code that the change did not touch, + unless it is a defect. + +## Report + +List findings with the most serious first. For each one give the file and line, the rule ID or the +word "defect", what is wrong, and the corrected code. Separate requirements (MUST) from +recommendations (SHOULD). State what you ran and what you did not check. If nothing is wrong, say so; +do not invent findings. diff --git a/.claude/skills/powershell-security-review/SKILL.md b/.claude/skills/powershell-security-review/SKILL.md new file mode 100644 index 0000000..9e79603 --- /dev/null +++ b/.claude/skills/powershell-security-review/SKILL.md @@ -0,0 +1,41 @@ +--- +name: powershell-security-review +description: Review PowerShell code for security problems such as exposed secrets, unsafe credential handling, command or path injection, and disabled certificate checks. Use when asked for a security review or audit of PowerShell code. +--- + +# Security review of PowerShell code + +Read `.github/instructions/powershell-security.instructions.md` first, unless it is already loaded. + +## Steps + +1. Map where data enters the code: parameters, files, environment variables, web responses, and + pipeline input. Treat each as untrusted unless the code proves otherwise. +2. Follow each input to where it is used and check: + - Secrets and credentials: SEC-01 to SEC-08, and SEC-50 to SEC-53 where the code uses a secret + vault. Search for literals that look like passwords, tokens, keys, and connection strings, + including in comments, defaults, and test data. + - Command construction: SEC-10. Look for `Invoke-Expression`, `[scriptblock]::Create()`, + `Start-Process` with a built argument string, and strings passed to `cmd /c` or `pwsh -Command`. + - Paths: SEC-12. Look for input joined into a path that is then read, written, or deleted. + - Queries: SEC-13. + - Input checks: SEC-11 and SEC-16 to SEC-19. + - Code signing, where the code signs files: SEC-30 to SEC-35. + - Transport and privilege: SEC-14 and SEC-15. +3. Check what the code writes. Verbose, debug, warning, and error messages, log files, and exported + files must not contain secrets or personal data. +4. Run PSScriptAnalyzer. Its rules `PSAvoidUsingPlainTextForPassword`, + `PSAvoidUsingConvertToSecureStringWithPlainText`, `PSAvoidUsingUsernameAndPasswordParams`, and + `PSAvoidUsingInvokeExpression` cover part of this. +5. Confirm each finding by reading the full path from input to use. A pattern match alone is not a + finding. The patterns of SEC-40 find candidates. `Add-Type -TypeDefinition` is a Medium finding + (SEC-41). + +## Report + +List findings with the most serious first, each with its tier (Critical, High, Medium, or Low), and +state the overall risk as the highest tier found (SEC-42): file and line, rule ID, how the problem +could be exploited or exposed, and the corrected code. Say which inputs you traced and which you did +not. If you find a real secret, tell the user that it must be revoked and replaced; removing it from +the file does not remove it from the repository history. This review covers the code only. It is not +a compliance assessment, so do not state that the code meets any regulation or framework. diff --git a/.claude/skills/powershell-write-tests/SKILL.md b/.claude/skills/powershell-write-tests/SKILL.md new file mode 100644 index 0000000..6a0ee0f --- /dev/null +++ b/.claude/skills/powershell-write-tests/SKILL.md @@ -0,0 +1,33 @@ +--- +name: powershell-write-tests +description: Write or extend Pester 6 tests for existing PowerShell code, following this repository's testing rules. Use when asked to add tests, raise coverage, or test a PowerShell function, script, or module. +--- + +# Write Pester tests for PowerShell code + +Read `.github/instructions/powershell-pester.instructions.md` first, unless it is already loaded. It +holds the rules, a complete test file, and a table of assertion behaviour. + +## Steps + +1. Read the code under test completely: its parameters and parameter sets, validation attributes, + output type, every `catch`, and every call that leaves the process (network, files, other modules, + the clock). +2. Look at an existing test file in the repository. Keep its assertion style and layout. In a new + file use the Pester 6 `Should-*` assertions. +3. List the behaviours to test before writing any: each parameter set, the documented output, each + validation failure, each error path, pipeline input, and for a `Test-` function both outcomes. +4. Write the file so that it runs on its own: a versioned `#Requires` for Pester, the code loaded in a + top-level `BeforeAll`, and test data built in `BeforeDiscovery`. +5. Mock only what crosses a boundary. For code inside a module, pass `-ModuleName` to `Mock` and + `Should-Invoke`, and reach private functions with `InModuleScope`. +6. Make every test able to fail: assert specific values, assert the count before reading by index, and + assert expected errors with `Should-Throw` or by counting error records. +7. Run the tests. A test that passes on its first run has not been shown to work: break the behaviour + it covers, or the expected value, once to see it fail, then restore it. + +## Report + +Say which behaviours are covered and which are not, the pass and fail counts, and the coverage figure +if you measured it. If a test exposes a defect in the code, report the defect; do not weaken the test +to make it pass, and do not change the code under test unless the user asked for that. diff --git a/.github/prompts/README.md b/.github/prompts/README.md deleted file mode 100644 index fb771f4..0000000 --- a/.github/prompts/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# Prompt files were replaced by skills - -This folder is kept only so that a sync workflow installed before version 2.0 keeps running. That -workflow copies this folder into your repository, and it fails if the folder does not exist. - -Version 2.0 of the PowerShell standards has no prompt files. The tasks they covered are now skills, -which GitHub Copilot, Claude Code, and Codex load from `.github/skills`, `.claude/skills`, and -`.agents/skills`. - -If you are reading this in your own repository, the old sync workflow has updated your instruction -files but has not installed the skills or the files for Claude Code and Codex. To get them: - -1. Clone the standards repository. -2. Run `./Tools/Install-CopilotStandards.ps1 -ProjectPath -RemoveLegacyFiles`. -3. Replace `.github/workflows/sync-copilot-standards.yml` in your repository with the current - template from `Templates/Workflows` in the standards repository. -4. Delete this folder. diff --git a/.github/skills/powershell-ci-pipeline/SKILL.md b/.github/skills/powershell-ci-pipeline/SKILL.md new file mode 100644 index 0000000..470932a --- /dev/null +++ b/.github/skills/powershell-ci-pipeline/SKILL.md @@ -0,0 +1,38 @@ +--- +name: powershell-ci-pipeline +description: Add or fix a CI workflow for a PowerShell project that runs PSScriptAnalyzer and Pester with a coverage gate. Use when asked to set up, create, or repair CI, GitHub Actions, or quality gates for PowerShell code. +--- + +# Set up CI for a PowerShell project + +Read `.github/instructions/powershell-cicd.instructions.md` first, unless it is already loaded. It +holds the rules, a pull request workflow, and a publishing workflow. + +## Steps + +1. Look at what exists: workflow files, a build script, the test folder, and the module manifest. + Extend an existing workflow instead of adding a second one that does the same job. +2. Establish what the project supports from its manifest and `#requires` lines: PowerShell 7.6 only, + or also Windows PowerShell 5.1, and which operating systems. Build the job list from that. Do not + add a version or operating system the project does not claim to support. +3. Add the pull request workflow from the CI rules: install PSScriptAnalyzer and Pester at fixed + versions, run PSScriptAnalyzer and fail on findings, and run the test gate. +4. Put the test gate in a script in the repository, `Tests/Invoke-Tests.ps1` unless the project + keeps its build scripts elsewhere, so that developers can run the same check locally. Use the + runner in `.github/instructions/pester-supporting-docs/test-execution.md`, and pass + `-CodeCoverage` in the job that holds the coverage gate; the alternative is the minimal gate in + `.github/instructions/powershell-pester.instructions.md`, which takes no parameters. Set its test + path and coverage paths to the project's real folders. +5. If the repository has no `PSScriptAnalyzerSettings.psd1`, offer to add the one shown in the CI + rules. Adding it can surface many layout findings in existing code, so say that first. +6. If the repository has no `.gitattributes` file, add one that contains `* text=auto eol=lf` + (CIC-11), so that the tests see the same line endings on every runner. +7. If the module ships compiled help, add the help checks from + `.github/instructions/powershell-platyps.instructions.md`. +8. Validate the workflow file's syntax, and run the gate script locally if you can. + +## Report + +Say which files you added or changed, what each job runs, and what you were able to run locally. A +workflow is not verified until it has run on the CI system; say so, and do not claim that it passes. +Do not add publishing, signing, or deployment steps unless the user asked for them. diff --git a/.github/skills/powershell-module-help/SKILL.md b/.github/skills/powershell-module-help/SKILL.md new file mode 100644 index 0000000..ff1eef4 --- /dev/null +++ b/.github/skills/powershell-module-help/SKILL.md @@ -0,0 +1,35 @@ +--- +name: powershell-module-help +description: Generate, update, validate, or build PowerShell module help with Microsoft.PowerShell.PlatyPS, where help is written as Markdown and shipped as compiled external help. Use when asked to document a module's commands, update help after a parameter change, or fix Get-Help output for a module. +--- + +# Maintain module help with PlatyPS + +Read `.github/instructions/powershell-platyps.instructions.md` first, unless it is already loaded. It +holds the rules and every command used below. + +## Steps + +1. Confirm the tool. `Get-Module -ListAvailable Microsoft.PowerShell.PlatyPS` must show version 1.0.3 + or later. Do not use the retired `platyPS` module or its commands. +2. Find the state of the module's help: whether `docs//` exists, which exported commands + have a Markdown file, and whether the exported functions carry `.EXTERNALHELP`. +3. For a command with no Markdown yet: make sure the function has complete comment-based help, run + `New-MarkdownCommandHelp` with `-Locale`, and only then add `.EXTERNALHELP` and reduce the comment + block to a one-line `.SYNOPSIS`. The order matters. +4. For a command whose parameters changed: import the module and run `Update-MarkdownCommandHelp`, + then update the module page. Do not edit syntax blocks or parameter metadata by hand. +5. Write the content. Replace every `{{ Fill in ... }}` placeholder, put each example's command in a + fenced `powershell` block, and describe only what the command does. +6. Validate with the checks in the PlatyPS rules: structure, leftover placeholders, and relative + links. +7. Build the compiled help with `Export-MamlCommandHelp`, copy it into the module's culture folder, + and confirm with `Get-Help -Full` against the imported module that the text and the + examples appear. Before a release, repeat the check against the packaged module on a + case-sensitive file system (PLT-14). + +## Report + +List the Markdown files you created or changed, the result of each validation, and what `Get-Help` +showed. Mention any command whose description or examples you could not write from the code alone, +and ask the user for the missing facts instead of inventing them. diff --git a/.github/skills/powershell-new-function/SKILL.md b/.github/skills/powershell-new-function/SKILL.md new file mode 100644 index 0000000..9f8cc2f --- /dev/null +++ b/.github/skills/powershell-new-function/SKILL.md @@ -0,0 +1,43 @@ +--- +name: powershell-new-function +description: Write a new PowerShell function with its comment-based help and Pester tests, following this repository's PowerShell standards. Use when asked to create, add, or scaffold a PowerShell function or command. +--- + +# Write a new PowerShell function + +Read these before writing code, unless they are already loaded: + +- `.github/copilot-instructions.md`, or `AGENTS.md` if the repository has no such file (the core rules + and the function template) +- `.github/instructions/powershell-functions.instructions.md` +- `.github/instructions/powershell-error-handling.instructions.md` +- `.github/instructions/powershell-help.instructions.md` + +## Steps + +1. Find the target version. Read the `#requires -Version` lines and the nearest module manifest. If the + project declares nothing and it is not clear which target applies, ask. If you cannot ask, target + PowerShell 7.6 and say that you assumed it. +2. Choose the name. Use a verb that `Get-Verb` lists and a singular noun. Search the repository for an + existing function with that name or purpose before creating a new one. +3. Decide where the file goes. In a module, an exported function goes in `Public/.ps1` and its + name is added to `FunctionsToExport` in the manifest; an internal one goes in `Private/.ps1`. + Outside a module, put it where the user asked. +4. Write the function in the shape of the function template: help first, `[CmdletBinding()]`, + `[OutputType()]`, typed and validated parameters, a `process` block for pipeline input, `try` and + `$PSCmdlet.ThrowTerminatingError()` for a failure that ends the function, + `$PSCmdlet.WriteError()` for a failure of one item, and objects written to the pipeline as they are + produced. +5. If the function changes state, add `SupportsShouldProcess` and guard each change with + `$PSCmdlet.ShouldProcess()`. If it only reads, do not. +6. Write the tests following `.github/instructions/powershell-pester.instructions.md`, in + `Tests/Unit/.Tests.ps1` (MOD-01) or beside the tests the project already has. Cover each + parameter set, the documented output, each validation failure, and each error path. +7. Run PSScriptAnalyzer on the new files, with `-Settings ./PSScriptAnalyzerSettings.psd1` when that + file exists, and run the tests. Fix what they report. + +## Report + +Say which files you created or changed, which PowerShell version you targeted and why, what you ran +and what it reported, and anything you could not verify. Ask instead of guessing when the purpose, the +inputs, or the output of the function is unclear. diff --git a/.github/skills/powershell-new-module/SKILL.md b/.github/skills/powershell-new-module/SKILL.md new file mode 100644 index 0000000..a756dd9 --- /dev/null +++ b/.github/skills/powershell-new-module/SKILL.md @@ -0,0 +1,40 @@ +--- +name: powershell-new-module +description: Create a new PowerShell module with a manifest, a root module, Public and Private folders, a first function, and Pester tests, following this repository's PowerShell standards. Use when asked to create, scaffold, or start a PowerShell module. +--- + +# Create a new PowerShell module + +Read these before writing files, unless they are already loaded: + +- `.github/copilot-instructions.md`, or `AGENTS.md` if the repository has no such file (the core rules + and the function template) +- `.github/instructions/powershell-modules.instructions.md` +- `.github/instructions/powershell-version.instructions.md` + +## Steps + +1. Ask for, or confirm, the module name, what it is for, and whether it must run on Windows PowerShell + 5.1. Without a 5.1 requirement, target PowerShell 7.6. +2. Create the layout from the module rules: `ModuleName.psd1`, `ModuleName.psm1`, `Public/`, + `Private/`, and `Tests/`, with the unit tests under `Tests/Unit/` (MOD-01). Add + `Tests/Integration/` and `Tests/Performance/` when the module has such tests, and `Classes/` only + if the module defines a class. Do not create empty folders for things the module does not have. +3. Write the manifest with literal values only. Generate the GUID once with `New-Guid` and paste the + result. Set `PowerShellVersion` and `CompatiblePSEditions` for the target. List exported functions + by name. Take `Author` and the project links from the user or the repository; leave out what you do + not know. +4. Write the root module exactly as the module rules show it: a `#Requires -Version` line that + matches the manifest's `PowerShellVersion` (MOD-08), strict mode, then `Classes`, `Private`, and + `Public` dot-sourced in that order, failing the import if a file fails to load. +5. Add the first function with the `powershell-new-function` skill, or follow its steps. +6. Import the module in a new session with `Import-Module ./ModuleName.psd1 -Force`, confirm that + `Get-Command -Module ModuleName` lists exactly the exported functions, and run the tests. +7. Add a `README.md` that follows `.github/instructions/powershell-readme.instructions.md`. + +## Report + +List the files you created, the target version, and the results of the import check and the tests. Do +not add dependencies or CI workflows unless the user asked for them; mention them as possible next +steps instead. Every module generates its command help with PlatyPS (PLT-10): do that with the +`powershell-module-help` skill, or say that it is still to do. diff --git a/.github/skills/powershell-performance-review/SKILL.md b/.github/skills/powershell-performance-review/SKILL.md new file mode 100644 index 0000000..fe836fb --- /dev/null +++ b/.github/skills/powershell-performance-review/SKILL.md @@ -0,0 +1,37 @@ +--- +name: powershell-performance-review +description: Find and fix performance problems in PowerShell code by measuring it. Use when asked to optimize, speed up, profile, or analyze the performance of PowerShell code. +--- + +# Performance review of PowerShell code + +The collection and string rules are in `.github/instructions/powershell-style.instructions.md` +(STY-22, STY-40 to STY-45, and STY-50). Read them first, unless that file is already loaded. + +## Steps + +1. Ask what is slow and how large the real input is, if the user has not said. An improvement that + matters at 100,000 items can be noise at 100. +2. Measure before changing anything. Use `Measure-Command` around the code with realistic input, and + repeat the run several times. If you cannot run the code, say so and present your suggestions as + unmeasured. +3. Look for the causes that usually dominate: + - An array grown with `+=` inside a loop, or a string extended with `+=` about 100 times or + more. Below that, `+=` on a string is fine (STY-22); do not report it. + - A command called once for each item when it accepts all items at once, or a remote or disk call + inside a loop that could be made once outside it. + - Filtering with `Where-Object` what the source command could have filtered. + - A lookup that scans a collection inside a loop, where a hashtable built once would do. + - `ForEach-Object` over a large collection that is already in memory. + - Output piped to `Out-Null` in a tight loop. +4. Change one thing at a time and measure again with the same input. Keep a change only if it is + faster and the output is the same. +5. Do not trade correctness or clarity for a small gain, and do not add parallelism + (`ForEach-Object -Parallel`, thread jobs) unless the work is slow per item and the items are + independent. + +## Report + +Give the measurements before and after, with the input size and the PowerShell version, for each +change you kept. Performance figures MUST come from runs you made; do not estimate percentages. List +what you tried that did not help. diff --git a/.github/skills/powershell-review/SKILL.md b/.github/skills/powershell-review/SKILL.md new file mode 100644 index 0000000..0325569 --- /dev/null +++ b/.github/skills/powershell-review/SKILL.md @@ -0,0 +1,35 @@ +--- +name: powershell-review +description: Review PowerShell code against this repository's PowerShell standards and report findings by rule ID. Use when asked to review, validate, analyze, or check PowerShell code for quality or standards compliance. +--- + +# Review PowerShell code against the standards + +Read the core rules (`.github/copilot-instructions.md`, or `AGENTS.md` if the repository has no such +file) and the topic files they list for the kind of file under review, unless they are already +loaded. Every rule has an ID such as `ERR-10`; cite it. + +## Steps + +1. Establish the target version from `#requires` lines and the module manifest. Judge the code + against that version, not against the newest one. +2. Run the tools first when you can: PSScriptAnalyzer, with `-Settings ./PSScriptAnalyzerSettings.psd1` + when that file exists, and the existing tests. Include what they report. +3. Read the code for what tools cannot see, in this order: + 1. Correctness: logic errors, unhandled failure paths, wrong assumptions about a command's output. + 2. Error handling: the ERR rules, in particular `throw` in advanced functions, a missing + `-ErrorAction Stop` inside `try`, and empty or silent `catch` blocks. + 3. Security: the SEC rules. + 4. Functions and output: the FUN rules. + 5. Version fit: the VER rules. + 6. Help and style: the DOC and STY rules. +4. Confirm each finding before reporting it. Read the surrounding code, and where behaviour is in + doubt, run a small test. Do not report a rule violation in code that the change did not touch, + unless it is a defect. + +## Report + +List findings with the most serious first. For each one give the file and line, the rule ID or the +word "defect", what is wrong, and the corrected code. Separate requirements (MUST) from +recommendations (SHOULD). State what you ran and what you did not check. If nothing is wrong, say so; +do not invent findings. diff --git a/.github/skills/powershell-security-review/SKILL.md b/.github/skills/powershell-security-review/SKILL.md new file mode 100644 index 0000000..9e79603 --- /dev/null +++ b/.github/skills/powershell-security-review/SKILL.md @@ -0,0 +1,41 @@ +--- +name: powershell-security-review +description: Review PowerShell code for security problems such as exposed secrets, unsafe credential handling, command or path injection, and disabled certificate checks. Use when asked for a security review or audit of PowerShell code. +--- + +# Security review of PowerShell code + +Read `.github/instructions/powershell-security.instructions.md` first, unless it is already loaded. + +## Steps + +1. Map where data enters the code: parameters, files, environment variables, web responses, and + pipeline input. Treat each as untrusted unless the code proves otherwise. +2. Follow each input to where it is used and check: + - Secrets and credentials: SEC-01 to SEC-08, and SEC-50 to SEC-53 where the code uses a secret + vault. Search for literals that look like passwords, tokens, keys, and connection strings, + including in comments, defaults, and test data. + - Command construction: SEC-10. Look for `Invoke-Expression`, `[scriptblock]::Create()`, + `Start-Process` with a built argument string, and strings passed to `cmd /c` or `pwsh -Command`. + - Paths: SEC-12. Look for input joined into a path that is then read, written, or deleted. + - Queries: SEC-13. + - Input checks: SEC-11 and SEC-16 to SEC-19. + - Code signing, where the code signs files: SEC-30 to SEC-35. + - Transport and privilege: SEC-14 and SEC-15. +3. Check what the code writes. Verbose, debug, warning, and error messages, log files, and exported + files must not contain secrets or personal data. +4. Run PSScriptAnalyzer. Its rules `PSAvoidUsingPlainTextForPassword`, + `PSAvoidUsingConvertToSecureStringWithPlainText`, `PSAvoidUsingUsernameAndPasswordParams`, and + `PSAvoidUsingInvokeExpression` cover part of this. +5. Confirm each finding by reading the full path from input to use. A pattern match alone is not a + finding. The patterns of SEC-40 find candidates. `Add-Type -TypeDefinition` is a Medium finding + (SEC-41). + +## Report + +List findings with the most serious first, each with its tier (Critical, High, Medium, or Low), and +state the overall risk as the highest tier found (SEC-42): file and line, rule ID, how the problem +could be exploited or exposed, and the corrected code. Say which inputs you traced and which you did +not. If you find a real secret, tell the user that it must be revoked and replaced; removing it from +the file does not remove it from the repository history. This review covers the code only. It is not +a compliance assessment, so do not state that the code meets any regulation or framework. diff --git a/.github/skills/powershell-write-tests/SKILL.md b/.github/skills/powershell-write-tests/SKILL.md new file mode 100644 index 0000000..6a0ee0f --- /dev/null +++ b/.github/skills/powershell-write-tests/SKILL.md @@ -0,0 +1,33 @@ +--- +name: powershell-write-tests +description: Write or extend Pester 6 tests for existing PowerShell code, following this repository's testing rules. Use when asked to add tests, raise coverage, or test a PowerShell function, script, or module. +--- + +# Write Pester tests for PowerShell code + +Read `.github/instructions/powershell-pester.instructions.md` first, unless it is already loaded. It +holds the rules, a complete test file, and a table of assertion behaviour. + +## Steps + +1. Read the code under test completely: its parameters and parameter sets, validation attributes, + output type, every `catch`, and every call that leaves the process (network, files, other modules, + the clock). +2. Look at an existing test file in the repository. Keep its assertion style and layout. In a new + file use the Pester 6 `Should-*` assertions. +3. List the behaviours to test before writing any: each parameter set, the documented output, each + validation failure, each error path, pipeline input, and for a `Test-` function both outcomes. +4. Write the file so that it runs on its own: a versioned `#Requires` for Pester, the code loaded in a + top-level `BeforeAll`, and test data built in `BeforeDiscovery`. +5. Mock only what crosses a boundary. For code inside a module, pass `-ModuleName` to `Mock` and + `Should-Invoke`, and reach private functions with `InModuleScope`. +6. Make every test able to fail: assert specific values, assert the count before reading by index, and + assert expected errors with `Should-Throw` or by counting error records. +7. Run the tests. A test that passes on its first run has not been shown to work: break the behaviour + it covers, or the expected value, once to see it fail, then restore it. + +## Report + +Say which behaviours are covered and which are not, the pass and fail counts, and the coverage figure +if you measured it. If a test exposes a defect in the code, report the defect; do not weaken the test +to make it pass, and do not change the code under test unless the user asked for that. diff --git a/.github/workflows/sync-copilot-standards.yml b/.github/workflows/sync-copilot-standards.yml index 815d267..58e0514 100644 --- a/.github/workflows/sync-copilot-standards.yml +++ b/.github/workflows/sync-copilot-standards.yml @@ -1,17 +1,14 @@ -name: Sync Copilot Standards +name: Sync PowerShell standards -# Keeps this repository's Copilot and Claude Code standards files in sync with the standards -# repository, and opens a pull request whenever they drift. -# -# Copy to .github/workflows/sync-copilot-standards.yml in the consuming project. +# Keeps this repository's PowerShell standards files in step with the standards +# repository, and opens a pull request when they change. # # Before the first run, enable: # Settings -> Actions -> General -> Workflow permissions # -> "Allow GitHub Actions to create and approve pull requests" -# Without it the job detects drift correctly and then fails at the PR step. +# Without it the job installs the files and then fails at the pull request step. # -# Forked the standards repository? Change STANDARDS_REPO below. It is the only -# line that needs editing. +# Edit the three values under env to suit this repository. on: schedule: @@ -23,7 +20,12 @@ permissions: pull-requests: write env: + # Repository that publishes the standards. Change it if you maintain a fork. STANDARDS_REPO: fadwen/ai-powershell-standards + # Branch, tag, or commit to install from. Set a release tag to decide when updates arrive. + STANDARDS_REF: main + # Agents this repository uses: any of Copilot, ClaudeCode, Codex, separated by commas. + STANDARDS_AGENTS: Copilot,ClaudeCode,Codex jobs: sync: @@ -31,82 +33,42 @@ jobs: steps: - name: Check out this repository - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Check out the standards repository - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: ${{ env.STANDARDS_REPO }} + ref: ${{ env.STANDARDS_REF }} path: .standards + persist-credentials: false - - name: Mirror instruction files - run: | - set -euo pipefail - src=.standards/.github - - cp "$src/copilot-instructions.md" .github/copilot-instructions.md - - # Mirror, not merge: files deleted upstream are deleted here too. - # Local edits to these paths are overwritten. Customisations belong - # upstream, or in a file outside the six mirrored paths. - for dir in instructions prompts; do - rm -rf ".github/$dir" - cp -r "$src/$dir" ".github/$dir" - done - - # The instruction files link to worked examples at ../../powershell-standards/Examples/. - # Mirror that folder too, or every one of those links dangles here. - rm -rf powershell-standards - cp -r .standards/powershell-standards powershell-standards - - # Claude Code rules. They import the instruction files by relative path, so - # they must sit at this exact depth. The project's own CLAUDE.md and any other - # rules under .claude/rules/ are not touched. - mkdir -p .claude/rules - rm -rf .claude/rules/powershell-standards - cp -r .standards/.claude/rules/powershell-standards .claude/rules/powershell-standards - - # Claude Code slash commands, one per prompt file. Each attaches its prompt from - # .github/prompts/ rather than copying it. Other commands under .claude/commands/ - # are not touched. - mkdir -p .claude/commands - rm -rf .claude/commands/powershell-standards - cp -r .standards/.claude/commands/powershell-standards .claude/commands/powershell-standards - - rm -rf .standards - - - name: Detect drift - id: drift + - name: Install the standards + id: install + shell: pwsh run: | - # Stage first: a file added upstream is untracked here, and plain - # `git diff` would not see it. - git add -A .github powershell-standards .claude/rules/powershell-standards .claude/commands/powershell-standards - if git diff --cached --quiet -- .github powershell-standards .claude/rules/powershell-standards .claude/commands/powershell-standards; then - echo "changed=false" >> "$GITHUB_OUTPUT" - echo "Instruction files are already up to date." - else - echo "changed=true" >> "$GITHUB_OUTPUT" - git diff --cached --stat -- .github powershell-standards .claude/rules/powershell-standards .claude/commands/powershell-standards - fi + $ErrorActionPreference = 'Stop' + $agents = @($env:STANDARDS_AGENTS -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) + $files = @(./.standards/Tools/Install-CopilotStandards.ps1 -ProjectPath . -Agent $agents -RemoveLegacyFiles) + $files | Where-Object Status -NE 'Unchanged' | Format-Table -Property Status, Path -AutoSize + $manifest = Import-PowerShellDataFile -LiteralPath ./.standards/standards/manifest.psd1 + "version=$($manifest.Version)" >> $env:GITHUB_OUTPUT + Remove-Item -LiteralPath ./.standards -Recurse -Force - name: Open pull request - if: steps.drift.outputs.changed == 'true' - uses: peter-evans/create-pull-request@v8 + uses: peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3 with: - branch: chore/sync-copilot-standards + branch: chore/sync-powershell-standards delete-branch: true - commit-message: 'chore: sync Copilot and Claude Code standards from standards repo' - title: 'chore: sync Copilot and Claude Code standards from standards repo' + commit-message: 'chore: sync PowerShell standards ${{ steps.install.outputs.version }}' + title: 'chore: sync PowerShell standards ${{ steps.install.outputs.version }}' body: | - Automated sync from the AI PowerShell Standards repository. + Automated update from `${{ env.STANDARDS_REPO }}` at `${{ env.STANDARDS_REF }}`, + standards version ${{ steps.install.outputs.version }}. - Covers `.github/copilot-instructions.md`, `.github/instructions/`, - `.github/prompts/`, `powershell-standards/` (the worked examples), - `.claude/rules/powershell-standards/` (the Claude Code rules) and - `.claude/commands/powershell-standards/` (the Claude Code slash commands). - Other workflows in `.github/workflows/`, this repository's own `CLAUDE.md`, - and any other rules or commands under `.claude/` are not touched by this job. + The files in this pull request are generated. Do not edit them here: a change made in + this repository is overwritten by the next run. Propose it in the standards repository + instead. - Review the diff before merging. Anything intended as a permanent local - customisation belongs upstream, or this job will overwrite it again on - the next run. + This repository's own `AGENTS.md` and `.github/copilot-instructions.md` + are replaced only if an earlier installation wrote them. diff --git a/AGENTS.md b/AGENTS.md index b7d9cde..23600fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,10 +11,11 @@ four checks to run and the compatibility both editions of PowerShell are held to General PowerShell conventions - module structure, comment-based help, Pester, error handling - are not there. They come from -[Powershell-Copilot-Standards](https://github.com/fadwen/Powershell-Copilot-Standards) and are -mirrored into `.github/copilot-instructions.md`, `.github/instructions/` and `.github/prompts/`. -Those three paths are overwritten wholesale on every sync, so a local edit to them is silently -reverted; a change to a convention belongs upstream. +[ai-powershell-standards](https://github.com/fadwen/ai-powershell-standards), and a weekly sync +installs them. **Read `.github/copilot-instructions.md` before working on PowerShell files**; it +holds the core rules and lists the topic files under `.github/instructions/` to read for each kind +of work. The `powershell-*` skills are under `.agents/skills/`. The sync overwrites those files, so +a local edit to them is silently reverted; a change to a convention belongs upstream. ## Why this file is a pointer diff --git a/CLAUDE.md b/CLAUDE.md index 320694d..ba833a7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,17 +8,21 @@ to the PowerShell Gallery. General PowerShell conventions - module structure, comment-based help, Pester, error handling - come from -[Powershell-Copilot-Standards](https://github.com/fadwen/Powershell-Copilot-Standards) and -are mirrored into this repository by `.github/workflows/sync-copilot-standards.yml`: +[ai-powershell-standards](https://github.com/fadwen/ai-powershell-standards). Its installer +writes them into this repository, and `.github/workflows/sync-copilot-standards.yml` runs it +every week and opens a pull request when they change: - `.github/copilot-instructions.md` -- `.github/instructions/` -- `.github/prompts/` +- `.github/instructions/powershell-*.instructions.md` +- `.github/instructions/pester-supporting-docs/` +- `.claude/rules/powershell-standards/` +- the `powershell-*` skills under `.github/skills/`, `.claude/skills/` and `.agents/skills/` -**Those three paths are mirrored with `rm -rf` + `cp`.** A local edit there is silently -reverted on the next sync. Changes belong upstream in the standards repository. +**The next sync overwrites those files.** A local edit there is silently reverted, and a file +the standards stop producing is deleted. Changes belong upstream in the standards repository. +`AGENTS.md` is this repository's own, and the installer leaves it alone. -This file is outside the mirror, so it is the right place for anything specific to this +This file is not one of them, so it is the right place for anything specific to this module. What follows is *not* general convention - it is the set of local invariants that look wrong or arbitrary until you know why, and that are cheap to break by accident. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eae6081..127ebf7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,9 +14,9 @@ Thank you for looking. Issues and pull requests are welcome. ## The conventions General PowerShell conventions - module layout, comment-based help, Pester, error handling - are -mirrored into `.github/` from -[Powershell-Copilot-Standards](https://github.com/fadwen/Powershell-Copilot-Standards). Those -paths are overwritten on every sync, so a change to a convention belongs upstream. +installed into `.github/`, `.claude/` and `.agents/` from +[ai-powershell-standards](https://github.com/fadwen/ai-powershell-standards). Those files are +overwritten on every sync, so a change to a convention belongs upstream. Everything specific to this module is in `CLAUDE.md`. The ones most often tripped over: diff --git a/powershell-standards/Examples/Basic-Function-Example.ps1 b/powershell-standards/Examples/Basic-Function-Example.ps1 deleted file mode 100644 index 2512d0f..0000000 --- a/powershell-standards/Examples/Basic-Function-Example.ps1 +++ /dev/null @@ -1,132 +0,0 @@ -function Get-BasicServerInfo { - <# - .SYNOPSIS - Gets operating system and hardware information from Windows computers. - - .DESCRIPTION - Opens a CIM session to each computer, reads its operating system and computer system - information, and emits one object for each computer. A computer that cannot be queried is - reported as a non-terminating error and the remaining computers are still processed. Each - session is closed before the next computer is queried. - - .PARAMETER ComputerName - One or more computer names, as NetBIOS names or fully qualified domain names. A name starts - with a letter or a digit and contains only letters, digits, hyphens, and dots. - - .PARAMETER Credential - Credential for the CIM sessions. Without it, the sessions use the identity of the current - user. - - .PARAMETER IncludeServices - Adds the running services of each computer to the RunningServices property. - - .EXAMPLE - Get-BasicServerInfo -ComputerName 'SERVER01' - - Gets operating system and hardware information from SERVER01. - - .EXAMPLE - 'WEB01', 'WEB02' | Get-BasicServerInfo -IncludeServices - - Takes the computer names from the pipeline and adds the running services of each computer. - - .EXAMPLE - Get-BasicServerInfo -ComputerName 'DB01' -Credential (Get-Credential) - - Asks for a credential and uses it to query DB01. - - .INPUTS - System.String. You can pipe computer names, or objects that have a ComputerName property, to - this function. - - .OUTPUTS - Example.ServerInfo. An object with ComputerName, OperatingSystem, Version, Architecture, - LastBootTime, UptimeDays, Manufacturer, Model, Domain, TotalMemoryGB, LogicalProcessors, and - RunningServices properties. RunningServices is empty unless IncludeServices is specified. - #> - [CmdletBinding()] - [OutputType('Example.ServerInfo')] - param( - [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] - [ValidatePattern('^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$')] - [Alias('CN', 'ServerName')] - [string[]]$ComputerName, - - [Parameter()] - [System.Management.Automation.PSCredential] - [System.Management.Automation.Credential()] - $Credential = [System.Management.Automation.PSCredential]::Empty, - - [Parameter()] - [switch]$IncludeServices - ) - - begin { - $sessionParameters = @{ - ErrorAction = 'Stop' - } - if ($Credential -ne [System.Management.Automation.PSCredential]::Empty) { - $sessionParameters['Credential'] = $Credential - } - } - - process { - foreach ($computer in $ComputerName) { - $cimSession = $null - try { - Write-Verbose "Querying '$computer'." - $cimSession = New-CimSession -ComputerName $computer @sessionParameters - $queryParameters = @{ - CimSession = $cimSession - ErrorAction = 'Stop' - } - $operatingSystem = Get-CimInstance -ClassName 'Win32_OperatingSystem' @queryParameters - $computerSystem = Get-CimInstance -ClassName 'Win32_ComputerSystem' @queryParameters - - $runningServices = @() - if ($IncludeServices) { - $serviceParameters = @{ - ClassName = 'Win32_Service' - Filter = 'State = "Running"' - } - $runningServices = @( - Get-CimInstance @serviceParameters @queryParameters | - Select-Object -Property Name, DisplayName, StartMode - ) - } - - $uptime = (Get-Date) - $operatingSystem.LastBootUpTime - $serverInfo = [PSCustomObject]@{ - PSTypeName = 'Example.ServerInfo' - ComputerName = $computer - OperatingSystem = $operatingSystem.Caption - Version = $operatingSystem.Version - Architecture = $operatingSystem.OSArchitecture - LastBootTime = $operatingSystem.LastBootUpTime - UptimeDays = [math]::Round($uptime.TotalDays, 2) - Manufacturer = $computerSystem.Manufacturer - Model = $computerSystem.Model - Domain = $computerSystem.Domain - TotalMemoryGB = [math]::Round($computerSystem.TotalPhysicalMemory / 1GB, 2) - LogicalProcessors = $computerSystem.NumberOfLogicalProcessors - RunningServices = $runningServices - } - } catch { - $message = "Server information could not be read from '$computer'. $($_.Exception.Message)" - $exception = [System.InvalidOperationException]::new($message, $_.Exception) - $errorRecord = [System.Management.Automation.ErrorRecord]::new( - $exception, 'ServerInfoQueryFailed', $_.CategoryInfo.Category, $computer) - $PSCmdlet.WriteError($errorRecord) - continue - } finally { - if ($null -ne $cimSession) { - Remove-CimSession -CimSession $cimSession - } - } - - # Emitted outside the try block. An exception thrown by a script block further down the - # pipeline would otherwise be caught above and reported as a failed query. - $serverInfo - } - } -} diff --git a/powershell-standards/Examples/Configuration/DefaultConfiguration.psd1 b/powershell-standards/Examples/Configuration/DefaultConfiguration.psd1 deleted file mode 100644 index 5d12554..0000000 --- a/powershell-standards/Examples/Configuration/DefaultConfiguration.psd1 +++ /dev/null @@ -1,24 +0,0 @@ -# Example of a settings file. Read it with Import-PowerShellDataFile, which returns the hashtable and -# does not run code, so every value in the file is a literal. Secrets do not belong in a settings -# file: read them at run time from a secret store. -@{ - Environments = @{ - Development = @{ - LogLevel = 'Verbose' - TimeoutSeconds = 30 - RetryCount = 3 - } - - Testing = @{ - LogLevel = 'Information' - TimeoutSeconds = 20 - RetryCount = 2 - } - - Production = @{ - LogLevel = 'Warning' - TimeoutSeconds = 10 - RetryCount = 1 - } - } -} diff --git a/powershell-standards/Examples/Module-Structure-Example/Classes/ExampleClass.ps1 b/powershell-standards/Examples/Module-Structure-Example/Classes/ExampleClass.ps1 deleted file mode 100644 index 2559657..0000000 --- a/powershell-standards/Examples/Module-Structure-Example/Classes/ExampleClass.ps1 +++ /dev/null @@ -1,26 +0,0 @@ -# A class gives the output of Get-ExampleData a type name that [OutputType()], the help, and the -# tests can refer to, and it keeps IsUsable() beside the data that the method reads. -class ExampleServiceResult { - [string]$ServiceName - [string]$Environment - - [ValidateSet('Healthy', 'Degraded', 'Unavailable')] - [string]$Status - - [datetime]$CheckedAt - - ExampleServiceResult([string]$ServiceName, [string]$Environment, [string]$Status) { - $this.ServiceName = $ServiceName - $this.Environment = $Environment - $this.Status = $Status - $this.CheckedAt = Get-Date - } - - [bool] IsUsable() { - return $this.Status -in 'Healthy', 'Degraded' - } - - [string] ToString() { - return "$($this.ServiceName) [$($this.Environment)]: $($this.Status)" - } -} diff --git a/powershell-standards/Examples/Module-Structure-Example/ModuleExample.psd1 b/powershell-standards/Examples/Module-Structure-Example/ModuleExample.psd1 deleted file mode 100644 index 9d65bd1..0000000 --- a/powershell-standards/Examples/Module-Structure-Example/ModuleExample.psd1 +++ /dev/null @@ -1,25 +0,0 @@ -@{ - RootModule = 'ModuleExample.psm1' - ModuleVersion = '1.0.0' - GUID = '8f2b1c9d-4e7a-4b3f-9c21-5d6e8a0f7b34' - Author = 'Example Author' - Description = 'Example module with Public, Private, and Classes folders and an explicit export list.' - - PowerShellVersion = '7.6' - CompatiblePSEditions = @('Core') - - # Only Get-ExampleData is exported. The functions in Private stay internal, so they can change - # without breaking a caller of the module. - FunctionsToExport = @('Get-ExampleData') - CmdletsToExport = @() - VariablesToExport = @() - AliasesToExport = @() - - PrivateData = @{ - PSData = @{ - Tags = @('PowerShell', 'Example', 'Standards', 'Reference') - ProjectUri = 'https://github.com/fadwen/Powershell-Copilot-Standards' - LicenseUri = 'https://github.com/fadwen/Powershell-Copilot-Standards/blob/main/LICENSE' - } - } -} diff --git a/powershell-standards/Examples/Module-Structure-Example/ModuleExample.psm1 b/powershell-standards/Examples/Module-Structure-Example/ModuleExample.psm1 deleted file mode 100644 index 69feb16..0000000 --- a/powershell-standards/Examples/Module-Structure-Example/ModuleExample.psm1 +++ /dev/null @@ -1,24 +0,0 @@ -#Requires -Version 7.6 - -# Root module. Files load in the order Classes, Private, Public, so that a type exists before a -# function that names it is defined. The manifest's FunctionsToExport decides what is exported. - -Set-StrictMode -Version Latest - -foreach ($folder in 'Classes', 'Private', 'Public') { - $folderPath = Join-Path -Path $PSScriptRoot -ChildPath $folder - if (-not (Test-Path -LiteralPath $folderPath)) { - continue - } - - foreach ($file in Get-ChildItem -LiteralPath $folderPath -Filter '*.ps1' -File) { - try { - Write-Verbose "Loading $folder file: $($file.Name)" - . $file.FullName - } catch { - # A file that fails to load must fail the import. Without this, the loop would carry - # on and the module would import with commands missing. - throw - } - } -} diff --git a/powershell-standards/Examples/Module-Structure-Example/Private/Connect-ExampleService.ps1 b/powershell-standards/Examples/Module-Structure-Example/Private/Connect-ExampleService.ps1 deleted file mode 100644 index 8204f2e..0000000 --- a/powershell-standards/Examples/Module-Structure-Example/Private/Connect-ExampleService.ps1 +++ /dev/null @@ -1,39 +0,0 @@ -function Connect-ExampleService { - <# - .SYNOPSIS - Creates the session that the module uses to query the example service. - - .DESCRIPTION - Returns a hashtable that names the environment and the endpoint of its service. There is no - real service behind this module, so no connection is opened. - - The manifest does not export this function, so its parameters and its output can change - without breaking a caller of the module. - - .PARAMETER Environment - Environment whose service the session targets. - - .EXAMPLE - $session = Connect-ExampleService -Environment 'Test' - - Creates a session for the Test environment and keeps it in a variable. - - .INPUTS - None. You cannot pipe objects to this function. - - .OUTPUTS - System.Collections.Hashtable. A session with the keys Environment and Endpoint. - #> - [CmdletBinding()] - [OutputType([hashtable])] - param( - [Parameter(Mandatory)] - [ValidateSet('Development', 'Test', 'Production')] - [string]$Environment - ) - - @{ - Environment = $Environment - Endpoint = "https://service.example.com/$($Environment.ToLowerInvariant())" - } -} diff --git a/powershell-standards/Examples/Module-Structure-Example/Private/Get-ExampleServiceStatus.ps1 b/powershell-standards/Examples/Module-Structure-Example/Private/Get-ExampleServiceStatus.ps1 deleted file mode 100644 index b7988e2..0000000 --- a/powershell-standards/Examples/Module-Structure-Example/Private/Get-ExampleServiceStatus.ps1 +++ /dev/null @@ -1,61 +0,0 @@ -function Get-ExampleServiceStatus { - <# - .SYNOPSIS - Gets the status of one service. - - .DESCRIPTION - Looks the service name up in a fixed table that stands in for a real service, and returns - the status found there. A name that is not in the table is a terminating error with the - error ID ServiceNotFound. - - Get-ExampleData calls this function once for each service name. It reports a failure as a - non-terminating error, so that the remaining names are still processed. - - .PARAMETER ServiceName - Name of the service to query. The names in the table are Billing, Identity, and Reporting. - - .PARAMETER Session - Session that Connect-ExampleService returned. - - .EXAMPLE - Get-ExampleServiceStatus -ServiceName 'Billing' -Session (Connect-ExampleService -Environment 'Test') - - Gets the status of the Billing service in the Test environment. - - .INPUTS - None. You cannot pipe objects to this function. - - .OUTPUTS - System.String. One of Healthy, Degraded, or Unavailable. - #> - [CmdletBinding()] - [OutputType([string])] - param( - [Parameter(Mandatory)] - [string]$ServiceName, - - [Parameter(Mandatory)] - [hashtable]$Session - ) - - # There is no real service. This table stands in for one, so that a batch returns different - # statuses and an unknown name gives the caller a real failure to handle. - $statusByService = @{ - Billing = 'Healthy' - Identity = 'Degraded' - Reporting = 'Unavailable' - } - - Write-Verbose "Querying '$ServiceName' at $($Session['Endpoint'])." - - if (-not $statusByService.ContainsKey($ServiceName)) { - $message = "Service '$ServiceName' was not found in the $($Session['Environment']) environment." - $exception = [System.Management.Automation.ItemNotFoundException]::new($message) - $category = [System.Management.Automation.ErrorCategory]::ObjectNotFound - $errorRecord = [System.Management.Automation.ErrorRecord]::new( - $exception, 'ServiceNotFound', $category, $ServiceName) - $PSCmdlet.ThrowTerminatingError($errorRecord) - } - - $statusByService[$ServiceName] -} diff --git a/powershell-standards/Examples/Module-Structure-Example/Public/Get-ExampleData.ps1 b/powershell-standards/Examples/Module-Structure-Example/Public/Get-ExampleData.ps1 deleted file mode 100644 index 0d6ad9b..0000000 --- a/powershell-standards/Examples/Module-Structure-Example/Public/Get-ExampleData.ps1 +++ /dev/null @@ -1,35 +0,0 @@ -function Get-ExampleData { - <# - .EXTERNALHELP ModuleExample-Help.xml - .SYNOPSIS - Gets the status of one or more services. - #> - [CmdletBinding()] - [OutputType('ExampleServiceResult')] - param( - [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] - [string[]]$ServiceName, - - [ValidateSet('Development', 'Test', 'Production')] - [string]$Environment = 'Development' - ) - - begin { - $session = Connect-ExampleService -Environment $Environment - } - - process { - foreach ($name in $ServiceName) { - try { - $status = Get-ExampleServiceStatus -ServiceName $name -Session $session -ErrorAction Stop - } catch { - # One service that cannot be queried must not end the batch. Passing the original - # error on as non-terminating lets the caller decide that with -ErrorAction. - $PSCmdlet.WriteError($_) - continue - } - - [ExampleServiceResult]::new($name, $Environment, $status) - } - } -} diff --git a/powershell-standards/Examples/Module-Structure-Example/README.md b/powershell-standards/Examples/Module-Structure-Example/README.md deleted file mode 100644 index 383acb5..0000000 --- a/powershell-standards/Examples/Module-Structure-Example/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# ModuleExample - -A small working module that shows how the PowerShell standards in this repository lay a module out. -It is an example to read and to copy from. There is no real service behind it: the statuses it -returns come from a fixed table that knows the services Billing, Identity, and Reporting. - -## Requirements - -- PowerShell 7.6 or later, Core edition. The module calls no platform-specific commands. -- No other module is needed to use it. -- Pester 6.2.0 or later, to run the tests. -- Microsoft.PowerShell.PlatyPS 1.0.3 or later, to rebuild the help. - -## Installation - -The module is not published. Import it from this folder: - -```powershell -Import-Module -Name ./ModuleExample.psd1 -Force -``` - -## Usage - -```powershell -Get-ExampleData -ServiceName 'Billing' -``` - -Gets the status of the Billing service in the Development environment. The result is an -`ExampleServiceResult` object with `ServiceName`, `Environment`, `Status`, and `CheckedAt` properties. - -```powershell -'Billing', 'Identity', 'Reporting' | Get-ExampleData -Environment 'Test' -``` - -Takes the service names from the pipeline and queries the Test environment. - -```powershell -Get-ExampleData -ServiceName 'Billing', 'Missing', 'Reporting' -``` - -Returns the results for Billing and Reporting, and writes a non-terminating error for Missing. Add -`-ErrorAction Stop` to end the command at the first error instead. - -Run `Get-Help Get-ExampleData -Full` for every parameter, and `Get-Help about_ModuleExample` for the -behaviour that the examples above rely on. - -## Layout - -```text -Module-Structure-Example/ - ModuleExample.psd1 manifest; names the one exported function - ModuleExample.psm1 root module; loads Classes, Private, Public in that order - Classes/ - ExampleClass.ps1 the ExampleServiceResult class - Private/ - Connect-ExampleService.ps1 not exported - Get-ExampleServiceStatus.ps1 not exported - Public/ - Get-ExampleData.ps1 the exported function - Tests/ - ModuleExample.Tests.ps1 - docs/ - ModuleExample/ - Get-ExampleData.md source of the help for Get-ExampleData - ModuleExample.md module page - en-US/ - ModuleExample-Help.xml compiled from docs; this is what Get-Help reads - about_ModuleExample.help.txt written by hand -``` - -## What the example shows - -| Rule | File | What to look at | -| --- | --- | --- | -| MOD-02 | `ModuleExample.psd1` | `FunctionsToExport` names the one public function. The two functions in `Private` are loaded but not exported. | -| MOD-05 | `ModuleExample.psm1` | Strict mode, then `Classes`, `Private`, and `Public`. A file that fails to load fails the import. | -| FUN-10 | `Public/Get-ExampleData.ps1` | `[OutputType('ExampleServiceResult')]` names the class as a string. | -| FUN-21 | `Public/Get-ExampleData.ps1` | `ServiceName` is an array that the `process` block loops over, so the pipeline and an array argument behave the same way. | -| ERR-10 | `Private/Get-ExampleServiceStatus.ps1` | An unknown service becomes an `ErrorRecord` with the ID `ServiceNotFound`, passed to `$PSCmdlet.ThrowTerminatingError()`. | -| ERR-13 | `Public/Get-ExampleData.ps1` | The `catch` block passes that error to `$PSCmdlet.WriteError()` and continues with the next name. | -| DOC-09 | `Public/Get-ExampleData.ps1` | The exported function carries `.EXTERNALHELP` and a one-line synopsis. The private functions keep full comment-based help. | -| MOD-07 | `Tests/ModuleExample.Tests.ps1` | The private functions and the class are tested inside `InModuleScope`. | -| TST-17 | `Tests/ModuleExample.Tests.ps1` | The partial-failure tests merge the error stream and count the error records. | -| TST-20 | `Tests/ModuleExample.Tests.ps1` | The only mock is `Get-Date`, the clock. | - -The rules are in -[powershell-modules](../../../.github/instructions/powershell-modules.instructions.md), -[powershell-functions](../../../.github/instructions/powershell-functions.instructions.md), -[powershell-error-handling](../../../.github/instructions/powershell-error-handling.instructions.md), -[powershell-help](../../../.github/instructions/powershell-help.instructions.md), and -[powershell-pester](../../../.github/instructions/powershell-pester.instructions.md). - -## Tests - -Run the tests from this folder: - -```powershell -Invoke-Pester -Path ./Tests -``` - -## Help - -The help for `Get-ExampleData` is written in `docs/ModuleExample/Get-ExampleData.md`. After editing -it, compile it again from this folder: - -```powershell -Measure-PlatyPSMarkdown -Path ./docs/ModuleExample/*.md | - Where-Object Filetype -Match 'CommandHelp' | - Import-MarkdownCommandHelp -Path { $_.FilePath } | - Export-MamlCommandHelp -OutputFolder ./maml -Force - -Copy-Item -LiteralPath ./maml/ModuleExample/ModuleExample-Help.xml -Destination ./en-US -Force -``` - -The `maml` folder is a build intermediate, and the repository's `.gitignore` excludes it. The rules -for the Markdown are in -[powershell-platyps](../../../.github/instructions/powershell-platyps.instructions.md). - -## License - -MIT. See [LICENSE](../../../LICENSE). diff --git a/powershell-standards/Examples/Module-Structure-Example/Tests/ModuleExample.Tests.ps1 b/powershell-standards/Examples/Module-Structure-Example/Tests/ModuleExample.Tests.ps1 deleted file mode 100644 index 80034f3..0000000 --- a/powershell-standards/Examples/Module-Structure-Example/Tests/ModuleExample.Tests.ps1 +++ /dev/null @@ -1,239 +0,0 @@ -#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } - -BeforeAll { - # This file holds the module's contract tests, so it is the one file that imports with -Force: - # it asserts what a newly imported module looks like. No file removes the module afterwards. - $moduleRoot = Split-Path -Path $PSScriptRoot -Parent - Import-Module -Name (Join-Path -Path $moduleRoot -ChildPath 'ModuleExample.psd1') -Force -} - -Describe 'ModuleExample' -Tag 'Unit' { - Context 'The export list' { - It 'Exports Get-ExampleData and nothing else' { - $commands = @(Get-Command -Module ModuleExample) - - $commands | Should-BeCollection -Count 1 - $commands[0].Name | Should-Be 'Get-ExampleData' - } - - It 'Keeps private' -ForEach @( - @{ CommandName = 'Connect-ExampleService' } - @{ CommandName = 'Get-ExampleServiceStatus' } - ) { - $module = Get-Module -Name ModuleExample - - $module.ExportedCommands.ContainsKey($CommandName) | Should-BeFalse - InModuleScope ModuleExample -Parameters @{ CommandName = $CommandName } { - (Get-Command -Name $CommandName).CommandType | Should-Be 'Function' - } - } - - It 'Declares ExampleServiceResult as the output type of Get-ExampleData' { - $outputTypes = @((Get-Command -Name Get-ExampleData).OutputType) - - $outputTypes | Should-BeCollection -Count 1 - $outputTypes[0].Name | Should-Be 'ExampleServiceResult' - } - } - - Context 'The root module' { - It 'Fails the import when a function file does not load' { - $brokenRoot = Join-Path -Path $TestDrive -ChildPath 'BrokenModule' - $publicPath = Join-Path -Path $brokenRoot -ChildPath 'Public' - $null = New-Item -Path $publicPath -ItemType Directory -Force - $sourcePath = Join-Path -Path $moduleRoot -ChildPath 'ModuleExample.psm1' - $rootModulePath = Join-Path -Path $brokenRoot -ChildPath 'BrokenModule.psm1' - Copy-Item -LiteralPath $sourcePath -Destination $rootModulePath - $brokenFilePath = Join-Path -Path $publicPath -ChildPath 'Get-Broken.ps1' - Set-Content -LiteralPath $brokenFilePath -Value 'function Get-Broken {' -Encoding ascii - $expectedErrorId = 'MissingEndCurlyBrace,Microsoft.PowerShell.Commands.ImportModuleCommand' - - { Import-Module -Name $rootModulePath -Force } | - Should-Throw -FullyQualifiedErrorId $expectedErrorId - Get-Module -Name BrokenModule | Should-BeNull - } - } -} - -Describe 'Get-ExampleData' -Tag 'Unit' { - Context 'When the services exist' { - It 'Returns the status for ' -ForEach @( - @{ ServiceName = 'Billing'; Expected = 'Healthy' } - @{ ServiceName = 'Identity'; Expected = 'Degraded' } - @{ ServiceName = 'Reporting'; Expected = 'Unavailable' } - ) { - $result = Get-ExampleData -ServiceName $ServiceName - - $result | Should-HaveType 'ExampleServiceResult' - $result.ServiceName | Should-Be $ServiceName - $result.Status | Should-Be $Expected - } - - It 'Queries the Development environment by default' { - $result = Get-ExampleData -ServiceName 'Billing' - - $result.Environment | Should-Be 'Development' - } - - It 'Records the environment on the result' -ForEach @( - @{ Environment = 'Test' } - @{ Environment = 'Production' } - ) { - $result = Get-ExampleData -ServiceName 'Billing' -Environment $Environment - - $result.Environment | Should-Be $Environment - } - - It 'Emits one result for each name received from the pipeline, in order' { - $result = @('Reporting', 'Billing', 'Identity' | Get-ExampleData) - - $result | Should-BeCollection -Count 3 - $result[0].ServiceName | Should-Be 'Reporting' - $result[1].ServiceName | Should-Be 'Billing' - $result[2].ServiceName | Should-Be 'Identity' - } - - It 'Emits one result for each name in an array argument, in order' { - $result = @(Get-ExampleData -ServiceName 'Identity', 'Billing') - - $result | Should-BeCollection -Count 2 - $result[0].ServiceName | Should-Be 'Identity' - $result[1].ServiceName | Should-Be 'Billing' - } - - It 'Takes the name from the ServiceName property of a piped object' { - $result = @([PSCustomObject]@{ ServiceName = 'Identity' } | Get-ExampleData) - - $result | Should-BeCollection -Count 1 - $result[0].ServiceName | Should-Be 'Identity' - } - - It 'Records the time of the check on the result' { - $checkedAt = [datetime]::new(2001, 2, 3, 4, 5, 6) - Mock -CommandName Get-Date -ModuleName ModuleExample -MockWith { $checkedAt } - - $result = Get-ExampleData -ServiceName 'Billing' - - $result.CheckedAt | Should-Be $checkedAt - Should-Invoke -CommandName Get-Date -ModuleName ModuleExample -Times 1 -Exactly - } - } - - Context 'When a service cannot be queried' { - # A module function reads $ErrorActionPreference from the global scope, which a CI runner - # sets to Stop. Each call below passes -ErrorAction Continue, so the outcome does not depend - # on where the tests run. - It 'Writes one non-terminating error and still returns the other services' { - $serviceNames = 'Billing', 'Missing', 'Reporting' - $output = Get-ExampleData -ServiceName $serviceNames -ErrorAction Continue 2>&1 - $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) - $results = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }) - - $errors | Should-BeCollection -Count 1 - $errors[0].FullyQualifiedErrorId | Should-Be 'ServiceNotFound,Get-ExampleData' - $errors[0].TargetObject | Should-Be 'Missing' - $results | Should-BeCollection -Count 2 - $results[0].ServiceName | Should-Be 'Billing' - $results[1].ServiceName | Should-Be 'Reporting' - } - - It 'Writes one error for each service when every service fails' { - $output = 'Missing', 'Absent' | Get-ExampleData -ErrorAction Continue 2>&1 - $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) - - $output | Should-BeCollection -Count 2 - $errors | Should-BeCollection -Count 2 - $errors[0].TargetObject | Should-Be 'Missing' - $errors[1].TargetObject | Should-Be 'Absent' - } - - It 'Throws when the caller passes -ErrorAction Stop' { - { Get-ExampleData -ServiceName 'Missing', 'Billing' -ErrorAction Stop } | - Should-Throw -FullyQualifiedErrorId 'ServiceNotFound,Get-ExampleData' - } - } - - Context 'When an argument is not valid' { - It 'Rejects an environment that is not in the allowed set' { - { Get-ExampleData -ServiceName 'Billing' -Environment 'Staging' } | - Should-Throw -FullyQualifiedErrorId 'ParameterArgumentValidationError,Get-ExampleData' - } - - It 'Rejects an empty service name' { - $expectedErrorId = 'ParameterArgumentValidationErrorEmptyStringNotAllowed,Get-ExampleData' - - { Get-ExampleData -ServiceName '' } | Should-Throw -FullyQualifiedErrorId $expectedErrorId - } - } -} - -Describe 'ExampleServiceResult' -Tag 'Unit' { - It 'Reports the status as usable: ' -ForEach @( - @{ Status = 'Healthy'; Expected = $true } - @{ Status = 'Degraded'; Expected = $true } - @{ Status = 'Unavailable'; Expected = $false } - ) { - InModuleScope ModuleExample -Parameters @{ Status = $Status; Expected = $Expected } { - $result = [ExampleServiceResult]::new('Billing', 'Test', $Status) - - $result.IsUsable() | Should-Be $Expected - } - } - - It 'Converts to a string that names the service, the environment, and the status' { - InModuleScope ModuleExample { - $result = [ExampleServiceResult]::new('Billing', 'Test', 'Healthy') - - $result.ToString() | Should-Be 'Billing [Test]: Healthy' - } - } - - It 'Rejects a status that is not in the allowed set' { - InModuleScope ModuleExample { - { [ExampleServiceResult]::new('Billing', 'Test', 'Exploded') } | - Should-Throw -ExceptionType ([System.Management.Automation.SetValueInvocationException]) - } - } -} - -Describe 'Connect-ExampleService' -Tag 'Unit' { - It 'Returns a session for the environment' -ForEach @( - @{ Environment = 'Development'; Endpoint = 'https://service.example.com/development' } - @{ Environment = 'Test'; Endpoint = 'https://service.example.com/test' } - @{ Environment = 'Production'; Endpoint = 'https://service.example.com/production' } - ) { - InModuleScope ModuleExample -Parameters @{ Environment = $Environment; Endpoint = $Endpoint } { - $session = Connect-ExampleService -Environment $Environment - - $session | Should-HaveType ([hashtable]) - $session['Environment'] | Should-Be $Environment - $session['Endpoint'] | Should-Be $Endpoint - } - } - - It 'Rejects an environment that is not in the allowed set' { - InModuleScope ModuleExample { - { Connect-ExampleService -Environment 'Staging' } | - Should-Throw -FullyQualifiedErrorId 'ParameterArgumentValidationError,Connect-ExampleService' - } - } -} - -Describe 'Get-ExampleServiceStatus' -Tag 'Unit' { - It 'Returns the status of a service that exists' { - InModuleScope ModuleExample { - $session = Connect-ExampleService -Environment 'Test' - - Get-ExampleServiceStatus -ServiceName 'Identity' -Session $session | Should-Be 'Degraded' - } - } - - It 'Throws ServiceNotFound for a service that does not exist' { - InModuleScope ModuleExample { - $session = Connect-ExampleService -Environment 'Test' - - { Get-ExampleServiceStatus -ServiceName 'Missing' -Session $session } | - Should-Throw -FullyQualifiedErrorId 'ServiceNotFound,Get-ExampleServiceStatus' - } - } -} diff --git a/powershell-standards/Examples/Module-Structure-Example/docs/ModuleExample/Get-ExampleData.md b/powershell-standards/Examples/Module-Structure-Example/docs/ModuleExample/Get-ExampleData.md deleted file mode 100644 index 27fa06f..0000000 --- a/powershell-standards/Examples/Module-Structure-Example/docs/ModuleExample/Get-ExampleData.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -document type: cmdlet -external help file: ModuleExample-Help.xml -HelpUri: '' -Locale: en-US -Module Name: ModuleExample -ms.date: 11 15 2026 -PlatyPS schema version: 2024-05-01 -title: Get-ExampleData ---- - -# Get-ExampleData - -## SYNOPSIS - -Gets the status of one or more services. - -## SYNTAX - -### __AllParameterSets - -``` -Get-ExampleData [-ServiceName] [[-Environment] ] -``` - -## DESCRIPTION - -Emits one ExampleServiceResult object for each service name, in the order the names are received. A service that cannot be queried is reported as a non-terminating error, and the remaining names are still processed. - -There is no real service behind this module. The statuses come from a fixed table that knows the services Billing, Identity, and Reporting. Every other name fails with the error ID ServiceNotFound. - -## EXAMPLES - -### Example 1: Get the status of one service - -```powershell -Get-ExampleData -ServiceName 'Billing' -``` - -Gets the status of the Billing service in the Development environment. - -### Example 2: Take the service names from the pipeline - -```powershell -'Billing', 'Identity', 'Reporting' | Get-ExampleData -Environment 'Test' -``` - -Gets the status of three services in the Test environment, taking the names from the pipeline. - -### Example 3: Continue after a service that cannot be queried - -```powershell -Get-ExampleData -ServiceName 'Billing', 'Missing', 'Reporting' -``` - -Gets the status of Billing and Reporting, and writes a non-terminating error for Missing. - -## PARAMETERS - -### -Environment - -Environment to query, which is recorded on each result. - -```yaml -Type: System.String -DefaultValue: Development -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 1 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -ServiceName - -One or more names of services to query. - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: true - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String[] - -You can pipe service names to this function, or objects that have a ServiceName property. - -## OUTPUTS - -### ExampleServiceResult - -One object for each service that was queried, with ServiceName, Environment, Status, and CheckedAt properties. - -## NOTES - -The error for a service that cannot be queried is non-terminating. To end the command at the first such service, pass -ErrorAction Stop. - -## RELATED LINKS - -- [about_ModuleExample]() -- [PowerShell-Copilot-Standards](https://github.com/fadwen/Powershell-Copilot-Standards) diff --git a/powershell-standards/Examples/Module-Structure-Example/docs/ModuleExample/ModuleExample.md b/powershell-standards/Examples/Module-Structure-Example/docs/ModuleExample/ModuleExample.md deleted file mode 100644 index dfdf2a8..0000000 --- a/powershell-standards/Examples/Module-Structure-Example/docs/ModuleExample/ModuleExample.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -document type: module -Help Version: 1.0.0.0 -HelpInfoUri: -Locale: en-US -Module Guid: 8f2b1c9d-4e7a-4b3f-9c21-5d6e8a0f7b34 -Module Name: ModuleExample -ms.date: 11 15 2026 -PlatyPS schema version: 2024-05-01 -title: ModuleExample Module ---- - -# ModuleExample Module - -## Description - -Example module with Public, Private, and Classes folders and an explicit export list. - -## ModuleExample - -### [Get-ExampleData](Get-ExampleData.md) - -Gets the status of one or more services. - diff --git a/powershell-standards/Examples/Module-Structure-Example/en-US/ModuleExample-Help.xml b/powershell-standards/Examples/Module-Structure-Example/en-US/ModuleExample-Help.xml deleted file mode 100644 index c265907..0000000 --- a/powershell-standards/Examples/Module-Structure-Example/en-US/ModuleExample-Help.xml +++ /dev/null @@ -1,138 +0,0 @@ - - - - - Get-ExampleData - - Gets the status of one or more services. - - Get - ExampleData - - - Emits one ExampleServiceResult object for each service name, in the order the names are received. A service that cannot be queried is reported as a non-terminating error, and the remaining names are still processed. - -There is no real service behind this module. The statuses come from a fixed table that knows the services Billing, Identity, and Reporting. Every other name fails with the error ID ServiceNotFound. - - - - Get-ExampleData - - ServiceName - - string[] - - System.String[] - - - - Environment - - string - - System.String - - - - - - - Environment - - Environment to query, which is recorded on each result. - - System.String - - System.String - - - - ServiceName - - One or more names of services to query. - - System.String[] - - System.String[] - - - - - - - System.String[] - - - You can pipe service names to this function, or objects that have a ServiceName property. - - - - - - - ExampleServiceResult - - - One object for each service that was queried, with ServiceName, Environment, Status, and CheckedAt properties. - - - - - - The error for a service that cannot be queried is non-terminating. To end the command at the first such service, pass -ErrorAction Stop. - - - - - --------- Example 1: Get the status of one service --------- - - ```powershell -Get-ExampleData -ServiceName 'Billing' -``` - € - Gets the status of the Billing service in the Development environment. - - - - - - --------- Example 2: Take the service names from the pipeline --------- - - ```powershell -'Billing', 'Identity', 'Reporting' | Get-ExampleData -Environment 'Test' -``` - € - Gets the status of three services in the Test environment, taking the names from the pipeline. - - - - - - --------- Example 3: Continue after a service that cannot be queried --------- - - ```powershell -Get-ExampleData -ServiceName 'Billing', 'Missing', 'Reporting' -``` - € - Gets the status of Billing and Reporting, and writes a non-terminating error for Missing. - - - - - - - - Online Version - - - - about_ModuleExample - - - - PowerShell-Copilot-Standards - https://github.com/fadwen/Powershell-Copilot-Standards - - - - \ No newline at end of file diff --git a/powershell-standards/Examples/Module-Structure-Example/en-US/about_ModuleExample.help.txt b/powershell-standards/Examples/Module-Structure-Example/en-US/about_ModuleExample.help.txt deleted file mode 100644 index f8f0189..0000000 --- a/powershell-standards/Examples/Module-Structure-Example/en-US/about_ModuleExample.help.txt +++ /dev/null @@ -1,60 +0,0 @@ -TOPIC - about_ModuleExample - -SHORT DESCRIPTION - Describes the behaviour of the ModuleExample module that does not belong - to the help of one command. - -LONG DESCRIPTION - ModuleExample is an example module. It shows a module laid out in Public, - Private, and Classes folders, with an explicit export list, a class as a - named output type, and command help that is built from Markdown. - - There is no real service behind the module. The statuses it returns come - from a fixed table that knows three services: Billing, Identity, and - Reporting. - - ENVIRONMENTS - - Get-ExampleData has an -Environment parameter that accepts Development, - Test, or Production. The default is Development. The value is recorded on - each result: - - Get-ExampleData -ServiceName 'Billing' -Environment 'Test' - - PARTIAL FAILURE - - A service that cannot be queried does not end the command. The command - writes a non-terminating error for that service and continues with the - next one, so the results for the other services are still returned: - - Get-ExampleData -ServiceName 'Billing', 'Missing', 'Reporting' - - The error has the ID ServiceNotFound. To end the command at the first - service that cannot be queried, pass -ErrorAction Stop: - - 'Billing', 'Missing' | Get-ExampleData -ErrorAction Stop - - OUTPUT - - Get-ExampleData emits ExampleServiceResult objects. Each object has the - properties ServiceName, Environment, Status, and CheckedAt. Status is - Healthy, Degraded, or Unavailable. The IsUsable() method returns $true - when the status is Healthy or Degraded: - - Get-ExampleData -ServiceName 'Billing', 'Reporting' | - Where-Object { $_.IsUsable() } - - HELP - - The help for Get-ExampleData is written as Markdown in - docs/ModuleExample/Get-ExampleData.md and compiled to - en-US/ModuleExample-Help.xml. The function file carries only an - .EXTERNALHELP keyword and a one-line synopsis. To change the help, edit - the Markdown and compile it again. Do not edit the XML file. - - This topic is a plain text file that is written by hand. - -SEE ALSO - Get-ExampleData - https://github.com/fadwen/Powershell-Copilot-Standards diff --git a/powershell-standards/Examples/README.md b/powershell-standards/Examples/README.md deleted file mode 100644 index 58e6b9e..0000000 --- a/powershell-standards/Examples/README.md +++ /dev/null @@ -1,93 +0,0 @@ -# Examples - -Working code that follows the PowerShell standards in this repository, and one file that breaks them -on purpose. The function, the module, and the negative example have Pester tests. - -## Requirements - -- PowerShell 7.6 or later. -- Windows, for `Basic-Function-Example.ps1`. It calls the CIM commands and queries computers over - WinRM. -- Pester 6.2.0 or later, to run the tests. -- PSScriptAnalyzer 1.25.0 or later, for `Test-QualityGates.Tests.ps1`. - -## Contents - -| Example | What it shows | -| --- | --- | -| [Basic-Function-Example.ps1](Basic-Function-Example.ps1) | One advanced function, `Get-BasicServerInfo`, with pipeline input, per-item errors, and a named output type. | -| [Testing-Examples/](Testing-Examples/) | The tests for `Get-BasicServerInfo`, with the CIM commands and the clock mocked. | -| [Module-Structure-Example/](Module-Structure-Example/) | A small working module. Its own [README](Module-Structure-Example/README.md) describes it. | -| [Configuration/DefaultConfiguration.psd1](Configuration/DefaultConfiguration.psd1) | A settings file that holds data only. | -| [Test-QualityGates.ps1](Test-QualityGates.ps1) | A negative example. It breaks the standards on purpose and is not code to copy. | - -## Usage - -Run the commands in this section from this folder. - -### The function example - -```powershell -. ./Basic-Function-Example.ps1 - -Get-BasicServerInfo -ComputerName 'SERVER01' -'SERVER01', 'SERVER02' | Get-BasicServerInfo -IncludeServices -``` - -Replace the names with computers that accept WinRM connections. The first command returns one -`Example.ServerInfo` object. The second takes the names from the pipeline and fills the -`RunningServices` property of each object. A computer that cannot be queried produces a -non-terminating error, and the remaining computers are still processed. - -| Rule | What to look at in the file | -| --- | --- | -| DOC-02 | The help block is the first thing in the function body. | -| FUN-10 | `[OutputType('Example.ServerInfo')]` names the type, and the object carries the same name as `PSTypeName`. | -| FUN-21 | `ComputerName` is an array that the `process` block loops over. | -| FUN-31 | The function only reads, so it does not declare `SupportsShouldProcess`. | -| SEC-03 | `Credential` is a `PSCredential` with the `Credential()` attribute and an empty default. | -| SEC-11 | An anchored `ValidatePattern` rejects a bad computer name when the parameter is bound. | -| ERR-13, ERR-14 | The `catch` block wraps the failure in a new `ErrorRecord`, passes it to `$PSCmdlet.WriteError()`, and continues with the next computer. | -| ERR-22 | The CIM session is closed in `finally`. | - -### The settings file - -```powershell -$settings = Import-PowerShellDataFile -LiteralPath ./Configuration/DefaultConfiguration.psd1 -$settings['Environments']['Production']['TimeoutSeconds'] -``` - -Reads the file into a hashtable and returns `10`, the timeout of the Production environment. - -### The negative example - -[Test-QualityGates.ps1](Test-QualityGates.ps1) exists so that the quality gates have something to -catch. Its header lists every rule it breaks, in two groups: the violations that PSScriptAnalyzer -reports, and the ones that it does not report. - -```powershell -Invoke-ScriptAnalyzer -Path ./Test-QualityGates.ps1 -Settings ../../PSScriptAnalyzerSettings.psd1 -``` - -Shows the first group. An analysis run that has to pass must leave this file out by name. - -## Tests - -```powershell -Invoke-Pester -Path ./Testing-Examples, ./Test-QualityGates.Tests.ps1 -``` - -Runs the tests for the function example and for the negative example. The tests for the negative -example record what its functions do, and they fail when a violation is added to the file or removed -from it. The module example has its own tests; see its README. - -## Related files - -- [PSScriptAnalyzerSettings.psd1](../../PSScriptAnalyzerSettings.psd1): the analyzer settings that - check the layout rules. -- [Templates/Powershell-Module](../../Templates/Powershell-Module/): a module to copy and rename. -- The rules that the examples follow: - [powershell-functions](../../.github/instructions/powershell-functions.instructions.md), - [powershell-error-handling](../../.github/instructions/powershell-error-handling.instructions.md), - [powershell-help](../../.github/instructions/powershell-help.instructions.md), and - [powershell-pester](../../.github/instructions/powershell-pester.instructions.md). diff --git a/powershell-standards/Examples/Testing-Examples/Basic-Function-Example.Tests.ps1 b/powershell-standards/Examples/Testing-Examples/Basic-Function-Example.Tests.ps1 deleted file mode 100644 index 7562635..0000000 --- a/powershell-standards/Examples/Testing-Examples/Basic-Function-Example.Tests.ps1 +++ /dev/null @@ -1,238 +0,0 @@ -#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } - -BeforeAll { - $examplesRoot = Split-Path -Path $PSScriptRoot -Parent - . (Join-Path -Path $examplesRoot -ChildPath 'Basic-Function-Example.ps1') -} - -Describe 'Get-BasicServerInfo' -Tag 'Unit' { - BeforeAll { - # The CIM commands reach the network and the clock decides the uptime, so every test replaces - # them. The stand-in session is not a CimSession. The two commands that receive it are - # therefore mocked with -RemoveParameterType, because parameter binding would otherwise - # reject the stand-in before the mock ran. - Mock -CommandName Get-Date -MockWith { [datetime]'2026-03-06T12:00:00' } - - Mock -CommandName New-CimSession -MockWith { - [PSCustomObject]@{ ComputerName = $ComputerName } - } - - Mock -CommandName Remove-CimSession -RemoveParameterType CimSession -MockWith { } - - Mock -CommandName Get-CimInstance -RemoveParameterType CimSession -MockWith { - switch ($ClassName) { - 'Win32_OperatingSystem' { - [PSCustomObject]@{ - Caption = 'Microsoft Windows Server 2022 Standard' - Version = '10.0.20348' - OSArchitecture = '64-bit' - LastBootUpTime = [datetime]'2026-03-01T00:00:00' - } - } - 'Win32_ComputerSystem' { - [PSCustomObject]@{ - Manufacturer = 'Contoso' - Model = 'Rack Server 1' - Domain = 'contoso.com' - TotalPhysicalMemory = 16GB - NumberOfLogicalProcessors = 8 - } - } - 'Win32_Service' { - [PSCustomObject]@{ Name = 'Spooler'; DisplayName = 'Print Spooler'; StartMode = 'Auto' } - [PSCustomObject]@{ Name = 'Themes'; DisplayName = 'Themes'; StartMode = 'Auto' } - } - default { - throw "The test does not expect a query for the class '$ClassName'." - } - } - } - } - - Context 'When the computers answer' { - It 'Returns one object with the values read from the computer' { - $result = @(Get-BasicServerInfo -ComputerName 'SERVER01') - - $result | Should-BeCollection -Count 1 - $result[0] | Should-HaveType 'Example.ServerInfo' - $result[0].ComputerName | Should-Be 'SERVER01' - $result[0].OperatingSystem | Should-Be 'Microsoft Windows Server 2022 Standard' - $result[0].Version | Should-Be '10.0.20348' - $result[0].Architecture | Should-Be '64-bit' - $result[0].Manufacturer | Should-Be 'Contoso' - $result[0].Model | Should-Be 'Rack Server 1' - $result[0].Domain | Should-Be 'contoso.com' - $result[0].TotalMemoryGB | Should-Be 16 - $result[0].LogicalProcessors | Should-Be 8 - } - - It 'Calculates the uptime from the last boot time' { - $result = Get-BasicServerInfo -ComputerName 'SERVER01' - - $result.LastBootTime | Should-Be ([datetime]'2026-03-01T00:00:00') - $result.UptimeDays | Should-Be 5.5 - } - - It 'Accepts the computer name ' -ForEach @( - @{ ValidName = 'SERVER01' } - @{ ValidName = 'web01.contoso.com' } - @{ ValidName = 'DB-SERVER-01' } - ) { - $result = Get-BasicServerInfo -ComputerName $ValidName - - $result.ComputerName | Should-Be $ValidName - } - - It 'Emits one object for each computer name received from the pipeline, in order' { - $result = @('WEB01', 'WEB02' | Get-BasicServerInfo) - - $result | Should-BeCollection -Count 2 - $result[0].ComputerName | Should-Be 'WEB01' - $result[1].ComputerName | Should-Be 'WEB02' - } - - It 'Reads the computer name from the ComputerName property of a pipeline object' { - $server = [PSCustomObject]@{ ComputerName = 'APP01' } - - $result = @($server | Get-BasicServerInfo) - - $result | Should-BeCollection -Count 1 - $result[0].ComputerName | Should-Be 'APP01' - } - - It 'Closes the session of every computer' { - $null = Get-BasicServerInfo -ComputerName 'WEB01', 'WEB02' - - Should-Invoke -CommandName New-CimSession -Times 2 -Exactly - Should-Invoke -CommandName Remove-CimSession -Times 2 -Exactly - } - } - - Context 'When the running services are requested' { - It 'Leaves RunningServices empty and does not query the services by default' { - $result = Get-BasicServerInfo -ComputerName 'SERVER01' - - $result | Should-HaveType 'Example.ServerInfo' - $result.RunningServices | Should-BeCollection -Count 0 - Should-Invoke -CommandName Get-CimInstance -Times 0 -Exactly -ParameterFilter { - $ClassName -eq 'Win32_Service' - } - } - - It 'Adds the running services, in the order the computer returned them' { - $result = Get-BasicServerInfo -ComputerName 'SERVER01' -IncludeServices - - $result.RunningServices | Should-BeCollection -Count 2 - $result.RunningServices[0].Name | Should-Be 'Spooler' - $result.RunningServices[0].DisplayName | Should-Be 'Print Spooler' - $result.RunningServices[1].Name | Should-Be 'Themes' - } - - It 'Asks the computer for running services only' { - $null = Get-BasicServerInfo -ComputerName 'SERVER01' -IncludeServices - - Should-Invoke -CommandName Get-CimInstance -Times 1 -Exactly -ParameterFilter { - $ClassName -eq 'Win32_Service' -and $Filter -eq 'State = "Running"' - } - } - } - - Context 'When a credential is supplied' { - It 'Opens the session with that credential' { - # An empty SecureString keeps a password out of the test file. - $operatorCredential = [System.Management.Automation.PSCredential]::new( - 'CONTOSO\operator', [System.Security.SecureString]::new()) - - $null = Get-BasicServerInfo -ComputerName 'SERVER01' -Credential $operatorCredential - - Should-Invoke -CommandName New-CimSession -Times 1 -Exactly -ParameterFilter { - $PesterBoundParameters.ContainsKey('Credential') -and - $Credential.UserName -eq 'CONTOSO\operator' - } - } - - It 'Opens the session as the current user when no credential is supplied' { - $null = Get-BasicServerInfo -ComputerName 'SERVER01' - - Should-Invoke -CommandName New-CimSession -Times 1 -Exactly -ParameterFilter { - -not $PesterBoundParameters.ContainsKey('Credential') - } - } - } - - Context 'When a computer name is not valid' { - It 'Rejects a name that ' -ForEach @( - @{ InvalidName = 'SERVER_01'; Reason = 'contains an underscore' } - @{ InvalidName = 'SERVER 01'; Reason = 'contains a space' } - @{ InvalidName = '-SERVER01'; Reason = 'starts with a hyphen' } - @{ InvalidName = ''; Reason = 'is empty' } - ) { - { Get-BasicServerInfo -ComputerName $InvalidName } | - Should-Throw -FullyQualifiedErrorId 'ParameterArgumentValidationError,Get-BasicServerInfo' - - Should-Invoke -CommandName New-CimSession -Times 0 -Exactly - } - } - - Context 'When a computer cannot be reached' { - BeforeAll { - Mock -CommandName New-CimSession -ParameterFilter { $ComputerName -contains 'OFFLINE01' } -MockWith { - throw 'The WinRM client cannot complete the operation.' - } - } - - It 'Writes one non-terminating error and still returns the computers that answer' { - $output = Get-BasicServerInfo -ComputerName 'OFFLINE01', 'SERVER01' -ErrorAction Continue 2>&1 - $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) - $values = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }) - - $errors | Should-BeCollection -Count 1 - $errors[0].FullyQualifiedErrorId | Should-BeLikeString 'ServerInfoQueryFailed*' - $errors[0].TargetObject | Should-Be 'OFFLINE01' - $values | Should-BeCollection -Count 1 - $values[0].ComputerName | Should-Be 'SERVER01' - } - - It 'Keeps the original failure as the inner exception' { - $output = Get-BasicServerInfo -ComputerName 'OFFLINE01' -ErrorAction Continue 2>&1 - $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) - - $errors | Should-BeCollection -Count 1 - $errors[0].Exception | Should-HaveType ([System.InvalidOperationException]) - $errors[0].Exception.InnerException.Message | - Should-Be 'The WinRM client cannot complete the operation.' - } - - It 'Does not close a session that never opened' { - $null = Get-BasicServerInfo -ComputerName 'OFFLINE01' -ErrorAction Continue 2>&1 - - Should-Invoke -CommandName Remove-CimSession -Times 0 -Exactly - } - - It 'Stops at the failed computer when the caller passes -ErrorAction Stop' { - { Get-BasicServerInfo -ComputerName 'OFFLINE01', 'SERVER01' -ErrorAction Stop } | - Should-Throw -FullyQualifiedErrorId 'ServerInfoQueryFailed,Get-BasicServerInfo' - - Should-Invoke -CommandName New-CimSession -Times 1 -Exactly - } - } - - Context 'When a query fails after the session opened' { - BeforeAll { - Mock -CommandName Get-CimInstance -RemoveParameterType CimSession -ParameterFilter { - $ClassName -eq 'Win32_ComputerSystem' - } -MockWith { - throw 'Access is denied.' - } - } - - It 'Reports the failure, returns nothing for that computer, and closes the session' { - $output = @(Get-BasicServerInfo -ComputerName 'SERVER01' -ErrorAction Continue 2>&1) - - $output | Should-BeCollection -Count 1 - $output[0] | Should-HaveType ([System.Management.Automation.ErrorRecord]) - $output[0].FullyQualifiedErrorId | Should-BeLikeString 'ServerInfoQueryFailed*' - Should-Invoke -CommandName Remove-CimSession -Times 1 -Exactly - } - } -}