From 238877203c010f50969b27716bf4d3677aabc43a Mon Sep 17 00:00:00 2001 From: fadwen <110697945+fadwen@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:27:38 +0000 Subject: [PATCH] chore: sync PowerShell standards 2.0.0 --- .agents/skills/powershell-logging/SKILL.md | 320 ++++++++++++++++++ .agents/skills/powershell-review/SKILL.md | 9 +- .claude/skills/powershell-logging/SKILL.md | 320 ++++++++++++++++++ .claude/skills/powershell-review/SKILL.md | 9 +- .github/copilot-instructions.md | 3 +- .../cicd-integration.md | 13 +- .../pester-supporting-docs/v6-migration.md | 11 +- .../powershell-cicd.instructions.md | 8 +- .../powershell-error-handling.instructions.md | 55 ++- .../powershell-help.instructions.md | 50 +++ .../powershell-modules.instructions.md | 90 ++--- .../powershell-readme.instructions.md | 5 + .github/skills/powershell-logging/SKILL.md | 320 ++++++++++++++++++ .github/skills/powershell-review/SKILL.md | 9 +- 14 files changed, 1159 insertions(+), 63 deletions(-) create mode 100644 .agents/skills/powershell-logging/SKILL.md create mode 100644 .claude/skills/powershell-logging/SKILL.md create mode 100644 .github/skills/powershell-logging/SKILL.md diff --git a/.agents/skills/powershell-logging/SKILL.md b/.agents/skills/powershell-logging/SKILL.md new file mode 100644 index 0000000..c02dd97 --- /dev/null +++ b/.agents/skills/powershell-logging/SKILL.md @@ -0,0 +1,320 @@ +--- +name: powershell-logging +description: Add logging to a PowerShell module, script, or project with PSFramework, or bring the logging that it already has into one standard form. Use when asked to add, set up, standardize, unify, or clean up logging or log files. +--- + +# Add or standardize logging with PSFramework + +These standards write messages to the output streams and add no logging module (ERR-30). Use this +skill when a project also wants log files. The streams keep working: a message written with +`Write-PSFMessage` still reaches the caller's verbose or warning stream. + +Read these first, unless they are already loaded: + +- `.github/copilot-instructions.md`, or `AGENTS.md` if the repository has no such file +- `.github/instructions/powershell-error-handling.instructions.md` +- `.github/instructions/powershell-security.instructions.md` + +Every statement about PSFramework below was measured with PSFramework 1.15.479 on PowerShell 7.7.0, +PowerShell 7.6.10, and Windows PowerShell 5.1. + +## Steps + +1. Confirm that PSFramework loads, with `Import-Module -Name PSFramework`. Its assembly is not + signed. Windows Smart App Control refuses the import with "An Application Control policy has + blocked this file", and another application control policy can do the same. When the import + fails, stop and report it. Do not look for a way around the policy. When the code runs on + other computers, ask whether they have such a policy. +2. Find the logging that the files in scope already have. Search for `Write-Host`, `Write-Verbose`, + `Write-Warning`, `Write-Debug`, `Write-Information`, `Write-PSFMessage`, `Stop-PSFFunction`, + `Set-PSFLoggingProvider`, `Start-Transcript`, `Write-EventLog`, text appended to a file with + `Add-Content` or `Out-File`, and functions of the project whose name contains `Log`. +3. Choose the mode from what was found, and say which one applies: + - **Add.** Nothing writes a log file. Add the standard form below. + - **Standardize.** The code logs in one or more other ways. List each way with the number of + places, then replace them with the standard form. Keep the meaning of every message and move + it to the level in the table. Change the callers of a logging function of the project first, + and remove the function only when nothing calls it any more. Code that already uses + PSFramework is brought to the same form: other levels, `Stop-PSFFunction`, and a provider + that a module sets up are replaced. Ask before removing `Start-Transcript`, because a + transcript records console output that a log file does not. +4. Ask where the log files go and how long they are kept, unless the project already says so. Do + not invent a path or a retention time. +5. Change the code that does the work, then the script that runs it, then the tests, as the three + sections below say. +6. Run PSScriptAnalyzer and the tests, then run the script once and read the log file it wrote. + +## The code that does the work + +A module or a function only writes messages. It MUST NOT enable, change, or disable a logging +provider, and a module MUST NOT do so when it is imported (MOD-06). The script that runs the code +decides where the messages go. + +| The code has, or means | Write | +| --- | --- | +| `Write-Verbose`, progress detail | `Write-PSFMessage -Level Verbose` | +| `Write-Debug`, diagnostics | `Write-PSFMessage -Level Debug` | +| `Write-Warning`, a condition the caller should know about | `Write-PSFMessage -Level Warning` | +| `Write-Host` or `Write-Information` with status text | `Write-PSFMessage -Level Verbose` | +| A failure, in `catch` | `Write-PSFMessage -Level Error -ErrorRecord $_` with `3>$null`, then the error as ERR-10 or ERR-13 says | + +- These four levels are the only ones for a function or a module. PSFramework writes `Critical`, + `Important`, `Host`, `Output`, and `Significant` straight to the console, where the caller can + neither capture nor silence them (ERR-31). It has no level named `Information`. +- A `Verbose` message is shown when the caller passes `-Verbose`, and a `Warning` message follows + `-WarningAction`. Every message goes to the log whether it is shown or not, `Debug` included. +- Logging does not replace error handling. `-Level Error` writes a warning, not an error, and + `-ErrorRecord` does not end the function. Log the failure, then call `$PSCmdlet.WriteError()` or + `$PSCmdlet.ThrowTerminatingError()`. `Stop-PSFFunction` and `-EnableException` MUST NOT be used. +- Discard the warning of the `Error` level with `3>$null` on that call. The caller then gets the + failure once, as an error. Without it the caller also gets a warning, which + `-ErrorAction SilentlyContinue` does not silence. +- Put the item being processed in `-Target`, as its name or ID and not as a whole object, and a + category in `-Tag`. Secrets and personal data MUST NOT go into the message, the target, the + tags, or `-Data` (SEC-06). With `-ErrorRecord`, PSFramework adds the exception's message to the + logged message. +- Do not write a message for every item of a large input. One call took between 16 microseconds + and 1.5 milliseconds on the computers measured, whether the message was shown or not. Write one + for each step or batch. +- Declare the dependency. A module lists + `@{ ModuleName = 'PSFramework'; ModuleVersion = '1.15.479' }` in `RequiredModules`, with the + version that the project tested (MOD-04). Importing the module then loads PSFramework. Name it + in the README's requirements (RDM-02) and install it at a fixed version in CI (CIC-02). + +This function follows the form. It and the script below are files with tests in the standards +repository: + +```powershell +function Get-FolderSize { + <# + .SYNOPSIS + Gets the number of files in a folder and their total size. + + .DESCRIPTION + Emits one object for each folder, with the count and the total length of the files directly + in it. A folder that cannot be read is reported as a non-terminating error and the remaining + folders are still processed. + + The function writes its progress, its warnings, and its failures with Write-PSFMessage. A + script that has enabled a PSFramework logging provider gets them in its log, and a caller + still sees them on the verbose, warning, and error streams. The PSFramework module is + required. + + .PARAMETER LiteralPath + One or more folders to measure. Wildcard characters are not expanded. + + .EXAMPLE + Get-FolderSize -LiteralPath './reports' + + Gets the file count and the total size of the reports folder. + + .EXAMPLE + './reports', './archive' | Get-FolderSize + + Measures two folders, taking the paths from the pipeline. + + .INPUTS + System.String. You can pipe folder paths to this function. + + .OUTPUTS + Example.FolderSize. An object with Path, FileCount, and TotalBytes properties. + #> + [CmdletBinding()] + [OutputType('Example.FolderSize')] + param( + [Parameter(Mandatory, ValueFromPipeline)] + [string[]]$LiteralPath + ) + + process { + foreach ($item in $LiteralPath) { + Write-PSFMessage -Level Verbose -Message "Measuring '$item'." -Target $item -Tag 'measure' + + try { + $fullPath = Convert-Path -LiteralPath $item -ErrorAction Stop + $files = @(Get-ChildItem -LiteralPath $fullPath -File -ErrorAction Stop) + } catch { + $failure = @{ + Level = 'Error' + Message = "Could not measure '$item'." + ErrorRecord = $_ + Target = $item + Tag = 'measure', 'failure' + } + # PSFramework writes this level to the warning stream as well. That warning is + # discarded: the caller gets the failure once, as an error that -ErrorAction controls. + Write-PSFMessage @failure 3>$null + $PSCmdlet.WriteError($_) + continue + } + + $totalBytes = [long]0 + foreach ($file in $files) { + $totalBytes += $file.Length + } + + if ($files.Count -eq 0) { + $message = "'$fullPath' contains no files." + Write-PSFMessage -Level Warning -Message $message -Target $item -Tag 'measure' + } + + [PSCustomObject]@{ + PSTypeName = 'Example.FolderSize' + Path = $fullPath + FileCount = $files.Count + TotalBytes = $totalBytes + } + } + } +} +``` + +## The script that runs the code + +- Turn off the provider named `filesystem` for the run. It is on by default. On PowerShell 7 it + writes every message, shown or not, to the profile of the account, with the computer name, the + path of the script, and the target. On PowerShell 7 and on Windows PowerShell 5.1 it writes each + error there as an XML file, with the computer name and the script stack trace (SEC-06). +- Put it back. The provider belongs to the whole process, and other code in the same session may + use it. Read `(Get-PSFLoggingProvider -Name filesystem).Enabled` before turning it off, and in + `finally` enable it again when it was enabled. The messages of the run did not reach it + afterwards. PowerShell 7 creates an empty file in the profile when the provider is enabled again. +- Enable one instance of the `logfile` provider, with these settings: + - A full path (STY-31). `%Date%` in the file name gives one file for each day. It is the local + date, with `-UTC` as well, so a file can hold timestamps of two UTC dates. + - `-FileType Json` with `-JsonCompress` and `-JsonNoComma`, so that every line is one JSON + object, and `-JsonString`, so that the level is a word. Without them the file starts with a + comma and the level is a number. + - `-Headers` with the columns the project wants. The default headers add the computer name and + the user name to every line (SEC-06). + - `-TimeFormat` and `-UTC`. The default timestamp is written in the format of the session's + culture. + - `-LogRotatePath`, `-LogRetentionTime`, and `-LogRotateFilter`, to remove old log files. Set + the filter to the names of the project's log files. With the default filter, every file in + that folder that is older than the retention time is removed. +- Call `Wait-PSFMessage` in `finally`, then disable the instance, then put `filesystem` back. + Without the wait, the last message was missing from the file after the process had ended, on a + Windows 11 virtual machine. +- A message that the script writes itself has the module name `` and the name of the + script file as its function name. `-IncludeModules` limits an instance to the named modules, and + leaves those messages out. +- To follow one run or one request through the log, put its ID in `-Data`, as in + `-Data @{ CorrelationId = $correlationId }`, and add the header + `'Data.CorrelationId as CorrelationId'`. `-Data` is not written to the file unless a header + names it. + +```powershell +#requires -Version 7.6 +#requires -Modules @{ ModuleName = 'PSFramework'; ModuleVersion = '1.15.479' } + +<# +.SYNOPSIS +Measures folders and writes what happened to a log file. + +.DESCRIPTION +Turns on a PSFramework log file, measures each folder with Get-FolderSize, and writes the results +to the pipeline. The log is a file of JSON lines in the log folder, one file for each day, with +timestamps in UTC. Log files of this script that are older than 30 days are removed. PSFramework's +own log is off while the script runs and has its earlier state again when the script ends. + +The script stops at the first folder that cannot be measured. The failure is in the log file. + +.PARAMETER LiteralPath +One or more folders to measure. Wildcard characters are not expanded. + +.PARAMETER LogDirectory +Folder for the log files. It is created when it does not exist. + +.EXAMPLE +./Invoke-FolderSizeReport.ps1 -LiteralPath './reports', './archive' -LogDirectory './logs' + +Measures two folders and writes the log to the logs folder. + +.INPUTS +None. + +.OUTPUTS +Example.FolderSize. One object for each folder, with Path, FileCount, and TotalBytes properties. +#> +[CmdletBinding()] +[OutputType('Example.FolderSize')] +param( + [Parameter(Mandatory)] + [string[]]$LiteralPath, + + [Parameter(Mandatory)] + [string]$LogDirectory +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +. (Join-Path -Path $PSScriptRoot -ChildPath 'Get-FolderSize.ps1') + +$logFolder = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($LogDirectory) +$null = New-Item -Path $logFolder -ItemType Directory -Force + +# PSFramework's own log is on by default. It records every message, shown or not, in the profile +# of the account, with the computer name and the path of the script. It is off while this script +# runs. The setting belongs to the whole process, so it gets its state back at the end. +$ownLogWasEnabled = (Get-PSFLoggingProvider -Name filesystem).Enabled + +$logFile = @{ + Name = 'logfile' + InstanceName = 'FolderSizeReport' + FilePath = Join-Path -Path $logFolder -ChildPath 'FolderSizeReport-%Date%.jsonl' + FileType = 'Json' + # With these two, every line of the file is one JSON object. + JsonCompress = $true + JsonNoComma = $true + # Writes the level as a word. Without it the level is a number. + JsonString = $true + # The default headers add the computer name and the user name to every line. + Headers = 'Timestamp', 'Level', 'ModuleName', 'FunctionName', 'Message', 'Tags', 'TargetObject' + TimeFormat = 'yyyy-MM-ddTHH:mm:ss.fffZ' + UTC = $true + LogRotatePath = $logFolder + # Without a filter, every file in the folder that is older than the retention time is removed. + LogRotateFilter = 'FolderSizeReport-*.jsonl' + LogRetentionTime = '30d' + Enabled = $true + Wait = $true +} + +try { + Set-PSFLoggingProvider -Name filesystem -Enabled $false -Wait + Set-PSFLoggingProvider @logFile + Write-PSFMessage -Level Verbose -Message "Measuring $($LiteralPath.Count) folder(s)." -Tag 'start' + Get-FolderSize -LiteralPath $LiteralPath +} finally { + # The last message can be missing from the file when the process ends without this call. + Wait-PSFMessage + Set-PSFLoggingProvider -Name logfile -InstanceName 'FolderSizeReport' -Enabled $false -Wait + if ($ownLogWasEnabled) { + Set-PSFLoggingProvider -Name filesystem -Enabled $true -Wait + } +} +``` + +## The tests + +- A unit test replaces `Write-PSFMessage` with a mock, and asserts the messages that matter with + `Should-Invoke -ParameterFilter`, by `$Level`, `$Message`, `$Target`, and `$Tag`. The mock names + the module when the function is in a module (TST-21), and not when the test dot-sources the + function file. It takes the place of the mocks of `Write-Verbose` and `Write-Information` that + TST-20 asks for. +- Assert a failure twice: the message with the level `Error`, and the error that the caller gets + (TST-17). +- An integration test runs the script with a log folder under `$TestDrive` and reads the file back + line by line with `ConvertFrom-Json`. It also asserts that the `filesystem` provider has the + state after the script that it had before. A test that writes a message without running the + script disables that provider first, and puts its state back in `AfterAll`. + +## Report + +Say which mode applied and what step 2 found. List the files changed, the logging that was +replaced or removed, and where the log files go. Give the results of PSScriptAnalyzer and the +tests, and quote one line of the log file that the script wrote. Say that the project now depends +on PSFramework and that its assembly is not signed, because some organizations approve such a +dependency before it is used. Say plainly when PSFramework could not be loaded and the code is +therefore untested. diff --git a/.agents/skills/powershell-review/SKILL.md b/.agents/skills/powershell-review/SKILL.md index 0325569..cbc706d 100644 --- a/.agents/skills/powershell-review/SKILL.md +++ b/.agents/skills/powershell-review/SKILL.md @@ -26,10 +26,15 @@ loaded. Every rule has an ID such as `ERR-10`; cite it. 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. +5. A comment of the form `# Exception to ERR-11: reason` records a decision of the project (DOC-22). + Do not report the code under it as a finding of that rule. Do report the comment when its reason + is missing or no longer matches the code. A comment that names a security rule (SEC) excuses + nothing: report the finding, and the comment. Do not propose such a comment as the fix for a + finding. ## 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. +recommendations (SHOULD). List the recorded exceptions with their reasons, apart from the findings. +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-logging/SKILL.md b/.claude/skills/powershell-logging/SKILL.md new file mode 100644 index 0000000..c02dd97 --- /dev/null +++ b/.claude/skills/powershell-logging/SKILL.md @@ -0,0 +1,320 @@ +--- +name: powershell-logging +description: Add logging to a PowerShell module, script, or project with PSFramework, or bring the logging that it already has into one standard form. Use when asked to add, set up, standardize, unify, or clean up logging or log files. +--- + +# Add or standardize logging with PSFramework + +These standards write messages to the output streams and add no logging module (ERR-30). Use this +skill when a project also wants log files. The streams keep working: a message written with +`Write-PSFMessage` still reaches the caller's verbose or warning stream. + +Read these first, unless they are already loaded: + +- `.github/copilot-instructions.md`, or `AGENTS.md` if the repository has no such file +- `.github/instructions/powershell-error-handling.instructions.md` +- `.github/instructions/powershell-security.instructions.md` + +Every statement about PSFramework below was measured with PSFramework 1.15.479 on PowerShell 7.7.0, +PowerShell 7.6.10, and Windows PowerShell 5.1. + +## Steps + +1. Confirm that PSFramework loads, with `Import-Module -Name PSFramework`. Its assembly is not + signed. Windows Smart App Control refuses the import with "An Application Control policy has + blocked this file", and another application control policy can do the same. When the import + fails, stop and report it. Do not look for a way around the policy. When the code runs on + other computers, ask whether they have such a policy. +2. Find the logging that the files in scope already have. Search for `Write-Host`, `Write-Verbose`, + `Write-Warning`, `Write-Debug`, `Write-Information`, `Write-PSFMessage`, `Stop-PSFFunction`, + `Set-PSFLoggingProvider`, `Start-Transcript`, `Write-EventLog`, text appended to a file with + `Add-Content` or `Out-File`, and functions of the project whose name contains `Log`. +3. Choose the mode from what was found, and say which one applies: + - **Add.** Nothing writes a log file. Add the standard form below. + - **Standardize.** The code logs in one or more other ways. List each way with the number of + places, then replace them with the standard form. Keep the meaning of every message and move + it to the level in the table. Change the callers of a logging function of the project first, + and remove the function only when nothing calls it any more. Code that already uses + PSFramework is brought to the same form: other levels, `Stop-PSFFunction`, and a provider + that a module sets up are replaced. Ask before removing `Start-Transcript`, because a + transcript records console output that a log file does not. +4. Ask where the log files go and how long they are kept, unless the project already says so. Do + not invent a path or a retention time. +5. Change the code that does the work, then the script that runs it, then the tests, as the three + sections below say. +6. Run PSScriptAnalyzer and the tests, then run the script once and read the log file it wrote. + +## The code that does the work + +A module or a function only writes messages. It MUST NOT enable, change, or disable a logging +provider, and a module MUST NOT do so when it is imported (MOD-06). The script that runs the code +decides where the messages go. + +| The code has, or means | Write | +| --- | --- | +| `Write-Verbose`, progress detail | `Write-PSFMessage -Level Verbose` | +| `Write-Debug`, diagnostics | `Write-PSFMessage -Level Debug` | +| `Write-Warning`, a condition the caller should know about | `Write-PSFMessage -Level Warning` | +| `Write-Host` or `Write-Information` with status text | `Write-PSFMessage -Level Verbose` | +| A failure, in `catch` | `Write-PSFMessage -Level Error -ErrorRecord $_` with `3>$null`, then the error as ERR-10 or ERR-13 says | + +- These four levels are the only ones for a function or a module. PSFramework writes `Critical`, + `Important`, `Host`, `Output`, and `Significant` straight to the console, where the caller can + neither capture nor silence them (ERR-31). It has no level named `Information`. +- A `Verbose` message is shown when the caller passes `-Verbose`, and a `Warning` message follows + `-WarningAction`. Every message goes to the log whether it is shown or not, `Debug` included. +- Logging does not replace error handling. `-Level Error` writes a warning, not an error, and + `-ErrorRecord` does not end the function. Log the failure, then call `$PSCmdlet.WriteError()` or + `$PSCmdlet.ThrowTerminatingError()`. `Stop-PSFFunction` and `-EnableException` MUST NOT be used. +- Discard the warning of the `Error` level with `3>$null` on that call. The caller then gets the + failure once, as an error. Without it the caller also gets a warning, which + `-ErrorAction SilentlyContinue` does not silence. +- Put the item being processed in `-Target`, as its name or ID and not as a whole object, and a + category in `-Tag`. Secrets and personal data MUST NOT go into the message, the target, the + tags, or `-Data` (SEC-06). With `-ErrorRecord`, PSFramework adds the exception's message to the + logged message. +- Do not write a message for every item of a large input. One call took between 16 microseconds + and 1.5 milliseconds on the computers measured, whether the message was shown or not. Write one + for each step or batch. +- Declare the dependency. A module lists + `@{ ModuleName = 'PSFramework'; ModuleVersion = '1.15.479' }` in `RequiredModules`, with the + version that the project tested (MOD-04). Importing the module then loads PSFramework. Name it + in the README's requirements (RDM-02) and install it at a fixed version in CI (CIC-02). + +This function follows the form. It and the script below are files with tests in the standards +repository: + +```powershell +function Get-FolderSize { + <# + .SYNOPSIS + Gets the number of files in a folder and their total size. + + .DESCRIPTION + Emits one object for each folder, with the count and the total length of the files directly + in it. A folder that cannot be read is reported as a non-terminating error and the remaining + folders are still processed. + + The function writes its progress, its warnings, and its failures with Write-PSFMessage. A + script that has enabled a PSFramework logging provider gets them in its log, and a caller + still sees them on the verbose, warning, and error streams. The PSFramework module is + required. + + .PARAMETER LiteralPath + One or more folders to measure. Wildcard characters are not expanded. + + .EXAMPLE + Get-FolderSize -LiteralPath './reports' + + Gets the file count and the total size of the reports folder. + + .EXAMPLE + './reports', './archive' | Get-FolderSize + + Measures two folders, taking the paths from the pipeline. + + .INPUTS + System.String. You can pipe folder paths to this function. + + .OUTPUTS + Example.FolderSize. An object with Path, FileCount, and TotalBytes properties. + #> + [CmdletBinding()] + [OutputType('Example.FolderSize')] + param( + [Parameter(Mandatory, ValueFromPipeline)] + [string[]]$LiteralPath + ) + + process { + foreach ($item in $LiteralPath) { + Write-PSFMessage -Level Verbose -Message "Measuring '$item'." -Target $item -Tag 'measure' + + try { + $fullPath = Convert-Path -LiteralPath $item -ErrorAction Stop + $files = @(Get-ChildItem -LiteralPath $fullPath -File -ErrorAction Stop) + } catch { + $failure = @{ + Level = 'Error' + Message = "Could not measure '$item'." + ErrorRecord = $_ + Target = $item + Tag = 'measure', 'failure' + } + # PSFramework writes this level to the warning stream as well. That warning is + # discarded: the caller gets the failure once, as an error that -ErrorAction controls. + Write-PSFMessage @failure 3>$null + $PSCmdlet.WriteError($_) + continue + } + + $totalBytes = [long]0 + foreach ($file in $files) { + $totalBytes += $file.Length + } + + if ($files.Count -eq 0) { + $message = "'$fullPath' contains no files." + Write-PSFMessage -Level Warning -Message $message -Target $item -Tag 'measure' + } + + [PSCustomObject]@{ + PSTypeName = 'Example.FolderSize' + Path = $fullPath + FileCount = $files.Count + TotalBytes = $totalBytes + } + } + } +} +``` + +## The script that runs the code + +- Turn off the provider named `filesystem` for the run. It is on by default. On PowerShell 7 it + writes every message, shown or not, to the profile of the account, with the computer name, the + path of the script, and the target. On PowerShell 7 and on Windows PowerShell 5.1 it writes each + error there as an XML file, with the computer name and the script stack trace (SEC-06). +- Put it back. The provider belongs to the whole process, and other code in the same session may + use it. Read `(Get-PSFLoggingProvider -Name filesystem).Enabled` before turning it off, and in + `finally` enable it again when it was enabled. The messages of the run did not reach it + afterwards. PowerShell 7 creates an empty file in the profile when the provider is enabled again. +- Enable one instance of the `logfile` provider, with these settings: + - A full path (STY-31). `%Date%` in the file name gives one file for each day. It is the local + date, with `-UTC` as well, so a file can hold timestamps of two UTC dates. + - `-FileType Json` with `-JsonCompress` and `-JsonNoComma`, so that every line is one JSON + object, and `-JsonString`, so that the level is a word. Without them the file starts with a + comma and the level is a number. + - `-Headers` with the columns the project wants. The default headers add the computer name and + the user name to every line (SEC-06). + - `-TimeFormat` and `-UTC`. The default timestamp is written in the format of the session's + culture. + - `-LogRotatePath`, `-LogRetentionTime`, and `-LogRotateFilter`, to remove old log files. Set + the filter to the names of the project's log files. With the default filter, every file in + that folder that is older than the retention time is removed. +- Call `Wait-PSFMessage` in `finally`, then disable the instance, then put `filesystem` back. + Without the wait, the last message was missing from the file after the process had ended, on a + Windows 11 virtual machine. +- A message that the script writes itself has the module name `` and the name of the + script file as its function name. `-IncludeModules` limits an instance to the named modules, and + leaves those messages out. +- To follow one run or one request through the log, put its ID in `-Data`, as in + `-Data @{ CorrelationId = $correlationId }`, and add the header + `'Data.CorrelationId as CorrelationId'`. `-Data` is not written to the file unless a header + names it. + +```powershell +#requires -Version 7.6 +#requires -Modules @{ ModuleName = 'PSFramework'; ModuleVersion = '1.15.479' } + +<# +.SYNOPSIS +Measures folders and writes what happened to a log file. + +.DESCRIPTION +Turns on a PSFramework log file, measures each folder with Get-FolderSize, and writes the results +to the pipeline. The log is a file of JSON lines in the log folder, one file for each day, with +timestamps in UTC. Log files of this script that are older than 30 days are removed. PSFramework's +own log is off while the script runs and has its earlier state again when the script ends. + +The script stops at the first folder that cannot be measured. The failure is in the log file. + +.PARAMETER LiteralPath +One or more folders to measure. Wildcard characters are not expanded. + +.PARAMETER LogDirectory +Folder for the log files. It is created when it does not exist. + +.EXAMPLE +./Invoke-FolderSizeReport.ps1 -LiteralPath './reports', './archive' -LogDirectory './logs' + +Measures two folders and writes the log to the logs folder. + +.INPUTS +None. + +.OUTPUTS +Example.FolderSize. One object for each folder, with Path, FileCount, and TotalBytes properties. +#> +[CmdletBinding()] +[OutputType('Example.FolderSize')] +param( + [Parameter(Mandatory)] + [string[]]$LiteralPath, + + [Parameter(Mandatory)] + [string]$LogDirectory +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +. (Join-Path -Path $PSScriptRoot -ChildPath 'Get-FolderSize.ps1') + +$logFolder = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($LogDirectory) +$null = New-Item -Path $logFolder -ItemType Directory -Force + +# PSFramework's own log is on by default. It records every message, shown or not, in the profile +# of the account, with the computer name and the path of the script. It is off while this script +# runs. The setting belongs to the whole process, so it gets its state back at the end. +$ownLogWasEnabled = (Get-PSFLoggingProvider -Name filesystem).Enabled + +$logFile = @{ + Name = 'logfile' + InstanceName = 'FolderSizeReport' + FilePath = Join-Path -Path $logFolder -ChildPath 'FolderSizeReport-%Date%.jsonl' + FileType = 'Json' + # With these two, every line of the file is one JSON object. + JsonCompress = $true + JsonNoComma = $true + # Writes the level as a word. Without it the level is a number. + JsonString = $true + # The default headers add the computer name and the user name to every line. + Headers = 'Timestamp', 'Level', 'ModuleName', 'FunctionName', 'Message', 'Tags', 'TargetObject' + TimeFormat = 'yyyy-MM-ddTHH:mm:ss.fffZ' + UTC = $true + LogRotatePath = $logFolder + # Without a filter, every file in the folder that is older than the retention time is removed. + LogRotateFilter = 'FolderSizeReport-*.jsonl' + LogRetentionTime = '30d' + Enabled = $true + Wait = $true +} + +try { + Set-PSFLoggingProvider -Name filesystem -Enabled $false -Wait + Set-PSFLoggingProvider @logFile + Write-PSFMessage -Level Verbose -Message "Measuring $($LiteralPath.Count) folder(s)." -Tag 'start' + Get-FolderSize -LiteralPath $LiteralPath +} finally { + # The last message can be missing from the file when the process ends without this call. + Wait-PSFMessage + Set-PSFLoggingProvider -Name logfile -InstanceName 'FolderSizeReport' -Enabled $false -Wait + if ($ownLogWasEnabled) { + Set-PSFLoggingProvider -Name filesystem -Enabled $true -Wait + } +} +``` + +## The tests + +- A unit test replaces `Write-PSFMessage` with a mock, and asserts the messages that matter with + `Should-Invoke -ParameterFilter`, by `$Level`, `$Message`, `$Target`, and `$Tag`. The mock names + the module when the function is in a module (TST-21), and not when the test dot-sources the + function file. It takes the place of the mocks of `Write-Verbose` and `Write-Information` that + TST-20 asks for. +- Assert a failure twice: the message with the level `Error`, and the error that the caller gets + (TST-17). +- An integration test runs the script with a log folder under `$TestDrive` and reads the file back + line by line with `ConvertFrom-Json`. It also asserts that the `filesystem` provider has the + state after the script that it had before. A test that writes a message without running the + script disables that provider first, and puts its state back in `AfterAll`. + +## Report + +Say which mode applied and what step 2 found. List the files changed, the logging that was +replaced or removed, and where the log files go. Give the results of PSScriptAnalyzer and the +tests, and quote one line of the log file that the script wrote. Say that the project now depends +on PSFramework and that its assembly is not signed, because some organizations approve such a +dependency before it is used. Say plainly when PSFramework could not be loaded and the code is +therefore untested. diff --git a/.claude/skills/powershell-review/SKILL.md b/.claude/skills/powershell-review/SKILL.md index 0325569..cbc706d 100644 --- a/.claude/skills/powershell-review/SKILL.md +++ b/.claude/skills/powershell-review/SKILL.md @@ -26,10 +26,15 @@ loaded. Every rule has an ID such as `ERR-10`; cite it. 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. +5. A comment of the form `# Exception to ERR-11: reason` records a decision of the project (DOC-22). + Do not report the code under it as a finding of that rule. Do report the comment when its reason + is missing or no longer matches the code. A comment that names a security rule (SEC) excuses + nothing: report the finding, and the comment. Do not propose such a comment as the fix for a + finding. ## 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. +recommendations (SHOULD). List the recorded exceptions with their reasons, apart from the findings. +State what you ran and what you did not check. If nothing is wrong, say so; do not invent findings. diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 59b7a61..bbfe554 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -10,7 +10,8 @@ These are the rules for writing and reviewing PowerShell in this repository. **M - Apply them to code you write or change. Do not reformat or rewrite code the task does not touch. - An explicit instruction from the user takes precedence. If following it breaks a MUST, say which - one. + one. A departure that is meant to stay is recorded in the code (DOC-22). Leave a recorded + departure as it is, and do not record one that the user has not decided. - Do not invent facts: no made-up module names, version numbers, measurements, links, or authors. Ask, or leave it out. - When you can run commands, run PSScriptAnalyzer and the tests before you report the work as done, diff --git a/.github/instructions/pester-supporting-docs/cicd-integration.md b/.github/instructions/pester-supporting-docs/cicd-integration.md index ce8b586..8561091 100644 --- a/.github/instructions/pester-supporting-docs/cicd-integration.md +++ b/.github/instructions/pester-supporting-docs/cicd-integration.md @@ -43,11 +43,14 @@ Three more facts shape the jobs: without coverage for feedback, and a separate sequential job with the profiler for the gate. 2. A file that fails discovery adds nothing to `FailedCount`. Every gate checks `Result`, and a cheap discovery-only job runs first. -3. Pester 6.0 and 6.1 do not import on PowerShell 7.4.0 to 7.4.5. Their `net8.0` assembly referred - to a newer `System.Management.Automation` than those releases carry, so `Import-Module` failed - with `Cannot convert "PesterConfigurationDeserializer" from String to Type`. Pester 6.2 fixed it. - Hosted runners carry the latest patch release, so this bites self-hosted agents and pinned - container images; the pin on Pester 6.2.0 (CIC-02) avoids it. +3. Pester 6.0.0, 6.0.1, and 6.1.0 do not import on PowerShell 7.4.0 to 7.4.4. Their `net8.0` + assembly refers to `System.Management.Automation` 7.4.5.0, which those releases do not carry, so + `Import-Module` fails where the module registers its type converter. The error is + `Cannot convert the "PesterConfigurationDeserializer" value of type "System.String" to type "System.Type"`. + The three versions import on 7.4.5 and later. The assembly of Pester 6.2.0 refers to 7.4.0.0, + and that version imports on every 7.4 release. Measured on Linux, macOS, and Windows with + PowerShell 7.4.0 to 7.4.7 and 7.4.22. Hosted runners carry the latest patch release, so this + bites self-hosted agents and pinned container images; the pin on Pester 6.2.0 (CIC-02) avoids it. ```text validate (discovery only, fast) diff --git a/.github/instructions/pester-supporting-docs/v6-migration.md b/.github/instructions/pester-supporting-docs/v6-migration.md index 4c85381..0080deb 100644 --- a/.github/instructions/pester-supporting-docs/v6-migration.md +++ b/.github/instructions/pester-supporting-docs/v6-migration.md @@ -437,10 +437,13 @@ Describe 'Get-User' -Tag 'Unit' { reproducible, which was not checked for this guide. - `IO exception during a TestRegistry operation, retrying.` is a debug message. In 6.1 it was a warning, shown when the retry recovered. This was read from the source of both versions. -- Pester imports again on PowerShell 7.4.0 to 7.4.5. 6.0 and 6.1 failed there with - `Cannot convert "PesterConfigurationDeserializer" from String to Type`, because the `net8.0` - assembly referenced a newer `System.Management.Automation` than those releases carry. Those - PowerShell versions were not available, so this was not run for this guide. +- Pester imports again on PowerShell 7.4.0 to 7.4.4. 6.0.0, 6.0.1, and 6.1.0 fail there, because + their `net8.0` assembly refers to `System.Management.Automation` 7.4.5.0, which those releases do + not carry. The error is + `Cannot convert the "PesterConfigurationDeserializer" value of type "System.String" to type "System.Type"`. + The assembly of 6.2.0 refers to 7.4.0.0. Run for this guide on Linux, macOS, and Windows: the + three earlier versions failed on 7.4.0 to 7.4.4 and imported on 7.4.5, 7.4.6, 7.4.7, and 7.4.22, + and 6.2.0 imported and ran a test on all nine releases. ### Verifying the Upgrade to 6.2 diff --git a/.github/instructions/powershell-cicd.instructions.md b/.github/instructions/powershell-cicd.instructions.md index 9b949ca..a83c461 100644 --- a/.github/instructions/powershell-cicd.instructions.md +++ b/.github/instructions/powershell-cicd.instructions.md @@ -124,9 +124,11 @@ The runner and the Pester settings files are kept in the `Tests` folder. A `buil `Tests` is the alternative; both are one level below the repository root, so the scripts are the same in either. -**CIC-02.** The pin also avoids a known failure: Pester 6.0 and 6.1 do not import on PowerShell -7.4.0 to 7.4.5 (`Cannot convert "PesterConfigurationDeserializer" from String to Type`), which -bites self-hosted agents and pinned container images. Pester 6.2 fixed it. +**CIC-02.** The pin also avoids a known failure: Pester 6.0.0, 6.0.1, and 6.1.0 do not import on +PowerShell 7.4.0 to 7.4.4, which bites self-hosted agents and pinned container images. The error is +`Cannot convert the "PesterConfigurationDeserializer" value of type "System.String" to type "System.Type"`. +Pester 6.2.0 imports on every 7.4 release. Measured on Linux, macOS, and Windows with PowerShell +7.4.0 to 7.4.7 and 7.4.22. A commit ID is the stricter choice for CIC-09, because a tag can be moved. Write the tag after it in a comment, as in `actions/checkout@ # v7.0.1`, and look the ID up; do not invent one. diff --git a/.github/instructions/powershell-error-handling.instructions.md b/.github/instructions/powershell-error-handling.instructions.md index 15dcc5d..d15fe43 100644 --- a/.github/instructions/powershell-error-handling.instructions.md +++ b/.github/instructions/powershell-error-handling.instructions.md @@ -53,6 +53,8 @@ run directly, and a function, which a caller invokes and which must leave the ca error. A non-zero exit code does not raise a PowerShell error by default. - **ERR-24** In a script, pass `-ErrorAction Stop` to a module command whose non-terminating errors must stop the script. The script's own `$ErrorActionPreference` does not reach module functions. + Set the preference as well (ERR-01): `-ErrorAction Stop` on a call does not make a terminating + error of that command end the script. ### Streams @@ -222,9 +224,13 @@ carries. Each statement below was verified on PowerShell 7.6 and Windows PowerShell 5.1. -- `throw` is suppressed when any caller up the call stack passed `-ErrorAction SilentlyContinue` or - `-ErrorAction Ignore`. Execution then continues with the statement after the `throw`, and the - function returns as if it had succeeded. +- `throw` is suppressed when any caller up the call stack passed `-ErrorAction SilentlyContinue`, or + `-ErrorAction Ignore` on PowerShell 7. Execution then continues with the statement after the + `throw`, and the function returns as if it had succeeded. A bare `throw` that passes on an error + raised with `-ErrorAction Stop` is the exception, described under the table below. On Windows + PowerShell 5.1, `-ErrorAction Ignore` does not suppress a `throw`: the command that was given the + parameter ends with another error, + `The value Ignore is not supported for an ActionPreference variable`. - `Write-Error -ErrorAction Stop` ignores the caller's `-ErrorAction`, and unless `-ErrorRecord` is passed it replaces the original exception with a `WriteErrorException`. - `$PSCmdlet.ThrowTerminatingError()` always ends the function, and the caller's `-ErrorAction` does @@ -241,6 +247,41 @@ Each statement below was verified on PowerShell 7.6 and Windows PowerShell 5.1. - Under `$ErrorActionPreference = 'Stop'`, `Write-Error` terminates. Statements that follow it in the same block do not run. +### What a calling script sees (ERR-01, ERR-10, ERR-11, ERR-24) + +A module function fails in its `begin` block, in one of three ways, and the script that calls it is +started with `-File`. Measured on PowerShell 7.7.0, PowerShell 7.6.10, and Windows PowerShell 5.1: + +| The calling script | `$PSCmdlet.ThrowTerminatingError()` | `throw $_` | `Write-Error -ErrorRecord $_ -ErrorAction Stop` | +| --- | --- | --- | --- | +| Has no `try` and sets no preference | Goes on, exit code 0 | Ends, exit code 1 | Ends, exit code 1 | +| Passes `-ErrorAction Stop` | Goes on, exit code 0 | Ends, exit code 1 | Ends, exit code 1 | +| Passes `-ErrorAction SilentlyContinue` | Goes on, exit code 0 | Goes on, and so does the function | Ends, exit code 1 | +| Sets `$ErrorActionPreference = 'Stop'` | Ends, exit code 1 | Ends, exit code 1 | Ends, exit code 1 | +| Makes the call inside `try` | `catch` runs | `catch` runs | `catch` runs | +| Makes the call twice in a loop | Both calls run | Ends at the first | Ends at the first | + +`throw` with text or with an exception object behaves as `throw $_` does, and so does a bare `throw` +in `catch`, with one exception. A bare `throw` that passes on an error raised with +`-ErrorAction Stop` behaves as the last column does, and so does such an error that no `catch` +handles: the script ends under `-ErrorAction SilentlyContinue` as well. + +A compiled cmdlet that raises a terminating error, as `ConvertFrom-Json` does for invalid text, +behaves as the first column does. + +ERR-10 chooses the first column: the function fails as a cmdlet does, and the caller decides whether +the script stops. The last column ends the calling script whatever the caller asked for. `-ErrorAction` +no longer works for the caller, and a loop ends at its first failure, which is why ERR-11 rules that +form out even with `-ErrorRecord`. + +The first two rows are the price of that choice. A script that does not set +`$ErrorActionPreference = 'Stop'` goes on after the failure and ends with exit code 0, and +`-ErrorAction Stop` on the call does not change that. A script therefore needs both: the preference +for a terminating error (ERR-01), and `-ErrorAction Stop` for a non-terminating error of a module +command (ERR-24). Text for callers, such as a README, a runbook, or a help example, says the same. +It does not offer `-ErrorAction Stop` as the way to make a failed command end a script or fail a job +step. + ### Strict mode (ERR-02, ERR-03) `Set-StrictMode` applies to the scope where it runs and to the scopes below it. At the top of a @@ -320,6 +361,14 @@ non-zero exit code raise an error that follows `$ErrorActionPreference`. It does PowerShell 5.1, and some tools use non-zero exit codes for success (`robocopy` returns values up to 7 for normal outcomes), so an explicit `$LASTEXITCODE` test is the portable form. +### Log files (ERR-30) + +These rules send messages to the streams and add no logging module. A project that also wants log +files adds them with the `powershell-logging` skill, which uses the PSFramework module. Its code +calls `Write-PSFMessage` where these rules name `Write-Verbose`, `Write-Debug`, and `Write-Warning`, +and the message still reaches the stream. A project that requires PSFramework, in its manifest or +in a `#requires -Modules` line, has made that choice: do not turn those calls back. + ### Messages in a loop (ERR-32) PowerShell builds the message before `Write-Verbose` decides whether to show it. Measured with diff --git a/.github/instructions/powershell-help.instructions.md b/.github/instructions/powershell-help.instructions.md index b34e253..54a0909 100644 --- a/.github/instructions/powershell-help.instructions.md +++ b/.github/instructions/powershell-help.instructions.md @@ -72,6 +72,11 @@ in `.github/instructions/powershell-platyps.instructions.md`. code does, and commented-out code MUST NOT be left in a file. - **DOC-21** A comment MUST stay true when read on its own. References to a conversation, a review, or an earlier version of the code MUST NOT be written into a file. +- **DOC-22** A deliberate departure from a rule is recorded where the code is, in a comment directly + above the statement or at the end of its line: `# Exception to : `. One comment + names one rule, and the reason says why the rule does not fit there. The user decides an + exception. Such a comment MUST NOT be added to make a check pass or to settle a review finding, + and MUST NOT name a security rule (SEC): a security finding is always reported. ## Notes and examples @@ -268,3 +273,48 @@ $pageSize = 100 # Set page size to 100 $pageSize = 100 ``` + +**DOC-22.** The comment keeps the decision with the code, where every agent and every reviewer reads +it. A note in a project file that only one tool loads does not do that. + +```powershell +function Get-StaleRecord { + [CmdletBinding()] + [OutputType('Contoso.StaleRecord')] + param() + + try { + $session = Connect-RecordStore -ErrorAction Stop + } catch { + # Exception to ERR-11: the scheduled cleanup that calls this command sets no error + # preference, and it must end when the store cannot be reached. + Write-Error -ErrorRecord $_ -ErrorAction Stop + } + + Get-RecordStoreItem -Session $session -Stale +} +``` + +The reason can run over several comment lines. A blank line between the comment and the statement +separates the two, and the comment then excuses nothing. + +A review lists a recorded exception with its reason, apart from the findings, and reports one whose +reason is missing or is no longer true (DOC-21). The compliance check of the standards repository, +`Test-StandardsCompliance.ps1`, reports the excused finding with the severity Information and does +not fail on it. It reports the comment itself when the reason is missing, when the comment is not +in this form, and when it names a rule that the check covers and excuses nothing. + +A security rule is not excused this way. Under `# Exception to SEC-01: test data` a literal +password would pass the check, and that comment is what an agent with a failing check is tempted to +add. The check keeps a security finding at its severity and reports the comment as well. An +ordinary comment can still say why the code is as it is (DOC-20). + +The comment does not silence PSScriptAnalyzer. Suppress one of its findings with its own attribute +on the function, and give the attribute a justification: + +```powershell +[Diagnostics.CodeAnalysis.SuppressMessageAttribute( + 'PSAvoidUsingWriteHost', '', Justification = 'The menu needs colour.')] +[CmdletBinding()] +param() +``` diff --git a/.github/instructions/powershell-modules.instructions.md b/.github/instructions/powershell-modules.instructions.md index 1356e91..2458e4f 100644 --- a/.github/instructions/powershell-modules.instructions.md +++ b/.github/instructions/powershell-modules.instructions.md @@ -40,8 +40,7 @@ These rules apply to `.psm1` and `.psd1` files and to the function files a modul - **MOD-11** Before the upload, import the staged copy in a new process and compare what it exports with the manifest. - **MOD-12** `ReleaseNotes` in the manifest covers the current release and points to `CHANGELOG.md`. - Measure `ReleaseNotes`, `Description`, and the full tag list against the Gallery's limits before - the release. + Measure `ReleaseNotes` and `Description` against the Gallery's limits before the release. - **MOD-13** Leave a URI key such as `IconUri` or `HelpInfoURI` out of the manifest until it has a value. An empty string MUST NOT be assigned to it, and the release rehearsal checks for one. - **MOD-14** In a release script, only the publish step is guarded by `$PSCmdlet.ShouldProcess()`. @@ -210,9 +209,11 @@ InModuleScope ModuleName { ### Releasing to the PowerShell Gallery (MOD-10 to MOD-15) -A Gallery version is in use from the moment it uploads. It can be unlisted but not deleted, and the -`.nupkg` stays downloadable at its direct URL afterwards. Each rule here answers a release that -passed every local check and then shipped the wrong content or failed at the upload. +A Gallery version is in use from the moment it uploads. Its owner can unlist it but cannot delete +it, and the `.nupkg` stays downloadable at its direct URL afterwards: on 2026-11-19 four unlisted +versions each downloaded from that address. Only the Gallery's administrators delete a package, on +request, for a reason such as sensitive data in it. Each rule here answers a release that passed +every local check and then shipped the wrong content or failed at the upload. **MOD-10, MOD-11.** When the repository is the module root, publishing that folder packs the working tree. Measured with Microsoft.PowerShell.PSResourceGet 1.2.0 and 1.3.1: the package contains `.git`, the tests, @@ -258,56 +259,60 @@ if ($PSCmdlet.ShouldProcess($stagePath, 'Publish to the PowerShell Gallery')) { The script declares `[CmdletBinding(SupportsShouldProcess)]`, keeps `out/` in `.gitignore`, and takes the API key from an environment variable that the CI secret store fills (CIC-06). -**MOD-12.** Three manifest fields have limits that are enforced only at upload, so every local check -passes until the publish step is refused. The limits below were met in real releases; the release -notes limit is stated in the Gallery's error response. +**MOD-12.** Two manifest fields have limits that are enforced only at upload, so every local check +passes until the publish step is refused. | Field | Limit | | --- | --- | | `ReleaseNotes` | 10,600 characters | | `Description` | 4,000 characters | -| Tags | 4,000 characters for the whole list | - -The tag list that the Gallery stores is the manifest's `Tags` plus the tags the publish adds: -`PSModule`, `PSEdition_` for each compatible edition, `PSIncludes_Function`, and -`PSFunction_` and `PSCommand_` for every exported function. A module with 27 commands -carries 61 tags and about 1,900 characters, so each new command costs about twice its name. A module -that keeps adding commands therefore reaches the limit without its `Tags` key changing, and -`ReleaseNotes` grows the same way when every release adds a paragraph and none removes one. Two -modules built to these standards were refused at 11,319 and 12,699 characters, each after every -other check had passed and the tag had been pushed. Measure all three in the release script and in a -test: + +The Gallery states the first limit when it refuses an upload: +`A package's ReleaseNotes property extracted from the PowerShell manifest may not be more than 10600 characters long.` +Two modules built to these standards were refused with it, each after every other check had passed +and the tag had been pushed. Their release notes had 11,190 and 12,523 characters with LF line +endings, and 11,319 and 12,699 with CRLF. `ReleaseNotes` grows that far when every release adds a +paragraph and none removes one. The limit is the Gallery's to change: in April 2023 the same +refusal named 10,000 characters. + +The description limit was not met in a release. Both limits agree with the Gallery's feed as it was +on 2026-11-19. Of 776,860 package versions, none published after January 2016 has release notes of +more than 10,600 characters, and one has exactly 10,600. No description is longer than 4,000 +characters when a line break is counted as one character, and one has exactly 4,000. Measure both +fields in the release script and in a test: ```powershell $manifest = Import-PowerShellDataFile -LiteralPath $manifestPath -$psData = $manifest.PrivateData.PSData -$publishTags = @( - $psData.Tags - 'PSModule' - 'PSIncludes_Function' - foreach ($edition in $manifest.CompatiblePSEditions) { - "PSEdition_$edition" - } - foreach ($functionName in $manifest.FunctionsToExport) { - "PSFunction_$functionName" - "PSCommand_$functionName" - } -) - $measurements = @( - @{ Field = 'Description'; Length = $manifest.Description.Length; Limit = 4000 } - @{ Field = 'Tags'; Length = ($publishTags -join ' ').Length; Limit = 4000 } - @{ Field = 'ReleaseNotes'; Length = $psData.ReleaseNotes.Length; Limit = 10600 } + # The index reads a key that the manifest lacks as $null. Member access is a strict mode error. + @{ Field = 'Description'; Text = $manifest['Description']; Limit = 4000 } + @{ Field = 'ReleaseNotes'; Text = $manifest.PrivateData.PSData['ReleaseNotes']; Limit = 10600 } ) foreach ($measurement in $measurements) { - if ($measurement.Length -gt $measurement.Limit) { - $problem = "The manifest's $($measurement.Field) is $($measurement.Length) characters." + # A line break is counted as two characters, the larger of the two possible counts. + $length = ([string]$measurement.Text).Replace("`r`n", "`n").Replace("`n", "`r`n").Length + if ($length -gt $measurement.Limit) { + $problem = "The manifest's $($measurement.Field) is $length characters." throw "$problem The PowerShell Gallery accepts at most $($measurement.Limit)." } } ``` -A module that exports cmdlets or DSC resources gains further tags of the same kind. +The count depends on the line endings, and which text the Gallery counts was not determined. +PSResourceGet writes the release notes into the `.nuspec` of the package with the line endings of +the system that publishes, CRLF on Windows and LF on Linux and macOS, whatever the manifest has. +The manifest in the package keeps its own. Measured with PSResourceGet 1.2.1 and 1.3.1 on Windows, +1.2.1 on Linux, and 1.2.0 on macOS. + +Tags need no measurement. Those versions of PSResourceGet write the manifest's `Tags` and +`PSModule` into the package, and nothing for the commands. The rest of the list that +`Find-PSResource` shows is added by the Gallery: `PSEdition_` for each compatible edition, +`PSIncludes_Function`, and `PSFunction_` and `PSCommand_` for every exported function. +A module that exports cmdlets or DSC resources gains further tags of the same kind. That list is +not limited to 4,000 characters: a module with 100 functions, for which it has 6,709, was accepted, +and on 2026-11-19 the Gallery served a list of 9,031 characters for a package whose own tags have +92. A limit on the manifest's own `Tags` was not found either: no version published since 2025 has +more than 2,500 characters of them. **MOD-13.** `IconUri = ''` is not "no icon". Measured with PSResourceGet 1.2.0 and 1.3.1, the pack fails with `IconUrl cannot be empty`, and the message names neither the manifest nor the key. `ProjectUri = ''` @@ -332,7 +337,8 @@ if ($emptyKeys.Count -gt 0) { ``` Setting `IconUri` has no visible effect on the Gallery in any case: the package page renders the -default PowerShell logo and does not fetch the icon. +Gallery's default icon and does not refer to the address in the key. That was the state of the +pages of two modules that set the key, on 2026-11-19. **MOD-14.** `-WhatIf` sets `$WhatIfPreference`, and every cmdlet and script that the release script calls inherits it (FUN-33). Unless the other steps are pinned, a rehearsal copies nothing and builds @@ -356,7 +362,9 @@ folder left by an earlier run hides a step that now produces nothing. Run the release from a version tag. The workflow runs every check again, refuses a tag that differs from the manifest's `ModuleVersion`, stages, verifies, and publishes (CIC-08, CIC-10). When the upload fails for a reason the rehearsal did not measure, nothing has been consumed: fix the -manifest, move the tag to the new merge commit, and release under the same number. +manifest, move the tag to the new merge commit, and release under the same number. Both modules +that were refused for their release notes went out that way, under the number of the refused +upload. ### Module data and state (MOD-20 to MOD-22) diff --git a/.github/instructions/powershell-readme.instructions.md b/.github/instructions/powershell-readme.instructions.md index 2a12358..fd6f3bf 100644 --- a/.github/instructions/powershell-readme.instructions.md +++ b/.github/instructions/powershell-readme.instructions.md @@ -213,3 +213,8 @@ measured or when a dependency declares it; leave the row out otherwise (RDM-04). **RDM-11.** For an organization's own deployment system, show the command that system really uses. The verification step can be `Get-Module -Name ModuleName -ListAvailable`, and for a manual download `Get-AuthenticodeSignature`. + +**RDM-13.** An example that runs the commands unattended starts with +`$ErrorActionPreference = 'Stop'`. `-ErrorAction Stop` on a call does not end the script when the +command raises a terminating error; the measurements are under ERR-24 in +`.github/instructions/powershell-error-handling.instructions.md`. diff --git a/.github/skills/powershell-logging/SKILL.md b/.github/skills/powershell-logging/SKILL.md new file mode 100644 index 0000000..c02dd97 --- /dev/null +++ b/.github/skills/powershell-logging/SKILL.md @@ -0,0 +1,320 @@ +--- +name: powershell-logging +description: Add logging to a PowerShell module, script, or project with PSFramework, or bring the logging that it already has into one standard form. Use when asked to add, set up, standardize, unify, or clean up logging or log files. +--- + +# Add or standardize logging with PSFramework + +These standards write messages to the output streams and add no logging module (ERR-30). Use this +skill when a project also wants log files. The streams keep working: a message written with +`Write-PSFMessage` still reaches the caller's verbose or warning stream. + +Read these first, unless they are already loaded: + +- `.github/copilot-instructions.md`, or `AGENTS.md` if the repository has no such file +- `.github/instructions/powershell-error-handling.instructions.md` +- `.github/instructions/powershell-security.instructions.md` + +Every statement about PSFramework below was measured with PSFramework 1.15.479 on PowerShell 7.7.0, +PowerShell 7.6.10, and Windows PowerShell 5.1. + +## Steps + +1. Confirm that PSFramework loads, with `Import-Module -Name PSFramework`. Its assembly is not + signed. Windows Smart App Control refuses the import with "An Application Control policy has + blocked this file", and another application control policy can do the same. When the import + fails, stop and report it. Do not look for a way around the policy. When the code runs on + other computers, ask whether they have such a policy. +2. Find the logging that the files in scope already have. Search for `Write-Host`, `Write-Verbose`, + `Write-Warning`, `Write-Debug`, `Write-Information`, `Write-PSFMessage`, `Stop-PSFFunction`, + `Set-PSFLoggingProvider`, `Start-Transcript`, `Write-EventLog`, text appended to a file with + `Add-Content` or `Out-File`, and functions of the project whose name contains `Log`. +3. Choose the mode from what was found, and say which one applies: + - **Add.** Nothing writes a log file. Add the standard form below. + - **Standardize.** The code logs in one or more other ways. List each way with the number of + places, then replace them with the standard form. Keep the meaning of every message and move + it to the level in the table. Change the callers of a logging function of the project first, + and remove the function only when nothing calls it any more. Code that already uses + PSFramework is brought to the same form: other levels, `Stop-PSFFunction`, and a provider + that a module sets up are replaced. Ask before removing `Start-Transcript`, because a + transcript records console output that a log file does not. +4. Ask where the log files go and how long they are kept, unless the project already says so. Do + not invent a path or a retention time. +5. Change the code that does the work, then the script that runs it, then the tests, as the three + sections below say. +6. Run PSScriptAnalyzer and the tests, then run the script once and read the log file it wrote. + +## The code that does the work + +A module or a function only writes messages. It MUST NOT enable, change, or disable a logging +provider, and a module MUST NOT do so when it is imported (MOD-06). The script that runs the code +decides where the messages go. + +| The code has, or means | Write | +| --- | --- | +| `Write-Verbose`, progress detail | `Write-PSFMessage -Level Verbose` | +| `Write-Debug`, diagnostics | `Write-PSFMessage -Level Debug` | +| `Write-Warning`, a condition the caller should know about | `Write-PSFMessage -Level Warning` | +| `Write-Host` or `Write-Information` with status text | `Write-PSFMessage -Level Verbose` | +| A failure, in `catch` | `Write-PSFMessage -Level Error -ErrorRecord $_` with `3>$null`, then the error as ERR-10 or ERR-13 says | + +- These four levels are the only ones for a function or a module. PSFramework writes `Critical`, + `Important`, `Host`, `Output`, and `Significant` straight to the console, where the caller can + neither capture nor silence them (ERR-31). It has no level named `Information`. +- A `Verbose` message is shown when the caller passes `-Verbose`, and a `Warning` message follows + `-WarningAction`. Every message goes to the log whether it is shown or not, `Debug` included. +- Logging does not replace error handling. `-Level Error` writes a warning, not an error, and + `-ErrorRecord` does not end the function. Log the failure, then call `$PSCmdlet.WriteError()` or + `$PSCmdlet.ThrowTerminatingError()`. `Stop-PSFFunction` and `-EnableException` MUST NOT be used. +- Discard the warning of the `Error` level with `3>$null` on that call. The caller then gets the + failure once, as an error. Without it the caller also gets a warning, which + `-ErrorAction SilentlyContinue` does not silence. +- Put the item being processed in `-Target`, as its name or ID and not as a whole object, and a + category in `-Tag`. Secrets and personal data MUST NOT go into the message, the target, the + tags, or `-Data` (SEC-06). With `-ErrorRecord`, PSFramework adds the exception's message to the + logged message. +- Do not write a message for every item of a large input. One call took between 16 microseconds + and 1.5 milliseconds on the computers measured, whether the message was shown or not. Write one + for each step or batch. +- Declare the dependency. A module lists + `@{ ModuleName = 'PSFramework'; ModuleVersion = '1.15.479' }` in `RequiredModules`, with the + version that the project tested (MOD-04). Importing the module then loads PSFramework. Name it + in the README's requirements (RDM-02) and install it at a fixed version in CI (CIC-02). + +This function follows the form. It and the script below are files with tests in the standards +repository: + +```powershell +function Get-FolderSize { + <# + .SYNOPSIS + Gets the number of files in a folder and their total size. + + .DESCRIPTION + Emits one object for each folder, with the count and the total length of the files directly + in it. A folder that cannot be read is reported as a non-terminating error and the remaining + folders are still processed. + + The function writes its progress, its warnings, and its failures with Write-PSFMessage. A + script that has enabled a PSFramework logging provider gets them in its log, and a caller + still sees them on the verbose, warning, and error streams. The PSFramework module is + required. + + .PARAMETER LiteralPath + One or more folders to measure. Wildcard characters are not expanded. + + .EXAMPLE + Get-FolderSize -LiteralPath './reports' + + Gets the file count and the total size of the reports folder. + + .EXAMPLE + './reports', './archive' | Get-FolderSize + + Measures two folders, taking the paths from the pipeline. + + .INPUTS + System.String. You can pipe folder paths to this function. + + .OUTPUTS + Example.FolderSize. An object with Path, FileCount, and TotalBytes properties. + #> + [CmdletBinding()] + [OutputType('Example.FolderSize')] + param( + [Parameter(Mandatory, ValueFromPipeline)] + [string[]]$LiteralPath + ) + + process { + foreach ($item in $LiteralPath) { + Write-PSFMessage -Level Verbose -Message "Measuring '$item'." -Target $item -Tag 'measure' + + try { + $fullPath = Convert-Path -LiteralPath $item -ErrorAction Stop + $files = @(Get-ChildItem -LiteralPath $fullPath -File -ErrorAction Stop) + } catch { + $failure = @{ + Level = 'Error' + Message = "Could not measure '$item'." + ErrorRecord = $_ + Target = $item + Tag = 'measure', 'failure' + } + # PSFramework writes this level to the warning stream as well. That warning is + # discarded: the caller gets the failure once, as an error that -ErrorAction controls. + Write-PSFMessage @failure 3>$null + $PSCmdlet.WriteError($_) + continue + } + + $totalBytes = [long]0 + foreach ($file in $files) { + $totalBytes += $file.Length + } + + if ($files.Count -eq 0) { + $message = "'$fullPath' contains no files." + Write-PSFMessage -Level Warning -Message $message -Target $item -Tag 'measure' + } + + [PSCustomObject]@{ + PSTypeName = 'Example.FolderSize' + Path = $fullPath + FileCount = $files.Count + TotalBytes = $totalBytes + } + } + } +} +``` + +## The script that runs the code + +- Turn off the provider named `filesystem` for the run. It is on by default. On PowerShell 7 it + writes every message, shown or not, to the profile of the account, with the computer name, the + path of the script, and the target. On PowerShell 7 and on Windows PowerShell 5.1 it writes each + error there as an XML file, with the computer name and the script stack trace (SEC-06). +- Put it back. The provider belongs to the whole process, and other code in the same session may + use it. Read `(Get-PSFLoggingProvider -Name filesystem).Enabled` before turning it off, and in + `finally` enable it again when it was enabled. The messages of the run did not reach it + afterwards. PowerShell 7 creates an empty file in the profile when the provider is enabled again. +- Enable one instance of the `logfile` provider, with these settings: + - A full path (STY-31). `%Date%` in the file name gives one file for each day. It is the local + date, with `-UTC` as well, so a file can hold timestamps of two UTC dates. + - `-FileType Json` with `-JsonCompress` and `-JsonNoComma`, so that every line is one JSON + object, and `-JsonString`, so that the level is a word. Without them the file starts with a + comma and the level is a number. + - `-Headers` with the columns the project wants. The default headers add the computer name and + the user name to every line (SEC-06). + - `-TimeFormat` and `-UTC`. The default timestamp is written in the format of the session's + culture. + - `-LogRotatePath`, `-LogRetentionTime`, and `-LogRotateFilter`, to remove old log files. Set + the filter to the names of the project's log files. With the default filter, every file in + that folder that is older than the retention time is removed. +- Call `Wait-PSFMessage` in `finally`, then disable the instance, then put `filesystem` back. + Without the wait, the last message was missing from the file after the process had ended, on a + Windows 11 virtual machine. +- A message that the script writes itself has the module name `` and the name of the + script file as its function name. `-IncludeModules` limits an instance to the named modules, and + leaves those messages out. +- To follow one run or one request through the log, put its ID in `-Data`, as in + `-Data @{ CorrelationId = $correlationId }`, and add the header + `'Data.CorrelationId as CorrelationId'`. `-Data` is not written to the file unless a header + names it. + +```powershell +#requires -Version 7.6 +#requires -Modules @{ ModuleName = 'PSFramework'; ModuleVersion = '1.15.479' } + +<# +.SYNOPSIS +Measures folders and writes what happened to a log file. + +.DESCRIPTION +Turns on a PSFramework log file, measures each folder with Get-FolderSize, and writes the results +to the pipeline. The log is a file of JSON lines in the log folder, one file for each day, with +timestamps in UTC. Log files of this script that are older than 30 days are removed. PSFramework's +own log is off while the script runs and has its earlier state again when the script ends. + +The script stops at the first folder that cannot be measured. The failure is in the log file. + +.PARAMETER LiteralPath +One or more folders to measure. Wildcard characters are not expanded. + +.PARAMETER LogDirectory +Folder for the log files. It is created when it does not exist. + +.EXAMPLE +./Invoke-FolderSizeReport.ps1 -LiteralPath './reports', './archive' -LogDirectory './logs' + +Measures two folders and writes the log to the logs folder. + +.INPUTS +None. + +.OUTPUTS +Example.FolderSize. One object for each folder, with Path, FileCount, and TotalBytes properties. +#> +[CmdletBinding()] +[OutputType('Example.FolderSize')] +param( + [Parameter(Mandatory)] + [string[]]$LiteralPath, + + [Parameter(Mandatory)] + [string]$LogDirectory +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +. (Join-Path -Path $PSScriptRoot -ChildPath 'Get-FolderSize.ps1') + +$logFolder = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($LogDirectory) +$null = New-Item -Path $logFolder -ItemType Directory -Force + +# PSFramework's own log is on by default. It records every message, shown or not, in the profile +# of the account, with the computer name and the path of the script. It is off while this script +# runs. The setting belongs to the whole process, so it gets its state back at the end. +$ownLogWasEnabled = (Get-PSFLoggingProvider -Name filesystem).Enabled + +$logFile = @{ + Name = 'logfile' + InstanceName = 'FolderSizeReport' + FilePath = Join-Path -Path $logFolder -ChildPath 'FolderSizeReport-%Date%.jsonl' + FileType = 'Json' + # With these two, every line of the file is one JSON object. + JsonCompress = $true + JsonNoComma = $true + # Writes the level as a word. Without it the level is a number. + JsonString = $true + # The default headers add the computer name and the user name to every line. + Headers = 'Timestamp', 'Level', 'ModuleName', 'FunctionName', 'Message', 'Tags', 'TargetObject' + TimeFormat = 'yyyy-MM-ddTHH:mm:ss.fffZ' + UTC = $true + LogRotatePath = $logFolder + # Without a filter, every file in the folder that is older than the retention time is removed. + LogRotateFilter = 'FolderSizeReport-*.jsonl' + LogRetentionTime = '30d' + Enabled = $true + Wait = $true +} + +try { + Set-PSFLoggingProvider -Name filesystem -Enabled $false -Wait + Set-PSFLoggingProvider @logFile + Write-PSFMessage -Level Verbose -Message "Measuring $($LiteralPath.Count) folder(s)." -Tag 'start' + Get-FolderSize -LiteralPath $LiteralPath +} finally { + # The last message can be missing from the file when the process ends without this call. + Wait-PSFMessage + Set-PSFLoggingProvider -Name logfile -InstanceName 'FolderSizeReport' -Enabled $false -Wait + if ($ownLogWasEnabled) { + Set-PSFLoggingProvider -Name filesystem -Enabled $true -Wait + } +} +``` + +## The tests + +- A unit test replaces `Write-PSFMessage` with a mock, and asserts the messages that matter with + `Should-Invoke -ParameterFilter`, by `$Level`, `$Message`, `$Target`, and `$Tag`. The mock names + the module when the function is in a module (TST-21), and not when the test dot-sources the + function file. It takes the place of the mocks of `Write-Verbose` and `Write-Information` that + TST-20 asks for. +- Assert a failure twice: the message with the level `Error`, and the error that the caller gets + (TST-17). +- An integration test runs the script with a log folder under `$TestDrive` and reads the file back + line by line with `ConvertFrom-Json`. It also asserts that the `filesystem` provider has the + state after the script that it had before. A test that writes a message without running the + script disables that provider first, and puts its state back in `AfterAll`. + +## Report + +Say which mode applied and what step 2 found. List the files changed, the logging that was +replaced or removed, and where the log files go. Give the results of PSScriptAnalyzer and the +tests, and quote one line of the log file that the script wrote. Say that the project now depends +on PSFramework and that its assembly is not signed, because some organizations approve such a +dependency before it is used. Say plainly when PSFramework could not be loaded and the code is +therefore untested. diff --git a/.github/skills/powershell-review/SKILL.md b/.github/skills/powershell-review/SKILL.md index 0325569..cbc706d 100644 --- a/.github/skills/powershell-review/SKILL.md +++ b/.github/skills/powershell-review/SKILL.md @@ -26,10 +26,15 @@ loaded. Every rule has an ID such as `ERR-10`; cite it. 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. +5. A comment of the form `# Exception to ERR-11: reason` records a decision of the project (DOC-22). + Do not report the code under it as a finding of that rule. Do report the comment when its reason + is missing or no longer matches the code. A comment that names a security rule (SEC) excuses + nothing: report the finding, and the comment. Do not propose such a comment as the fix for a + finding. ## 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. +recommendations (SHOULD). List the recorded exceptions with their reasons, apart from the findings. +State what you ran and what you did not check. If nothing is wrong, say so; do not invent findings.