The office tool has tests. Two things are missing before it may enter a pipeline: a tool should check every run for known mistakes without a person looking (that is what the analyzer does), and it must never write a secret into an output, a log or a command line. After that comes Azure: which tool, which sign-in, and how the script stays free of passwords there too.
Everything was run in PowerShell 7.6.9 with PSScriptAnalyzer 1.25.0. Whatever has to do with an Azure account, a Key Vault or a tenant is marked not run, read against Learn; every such section has a part that runs without a service.
PSScriptAnalyzer: the checker for scripts
PSScriptAnalyzer reads your script without running it and reports violations of a collection of rules: discouraged patterns, mistakes in construction, security risks. You install the module like
Pester: Install-PSResource -Name PSScriptAnalyzer -Scope CurrentUser. A script with deliberate mistakes, bad.ps1:
param(
[string]$Password,
[string]$Folder
)
$unused = 1
gci $Folder | ForEach-Object { Write-Host $_.Name }
Invoke-Expression "Get-Date"
function Remove-Everything {
Remove-Item $Folder -Recurse
}
Invoke-ScriptAnalyzer -Path .\bad.ps1 | Format-Table Line, Severity, RuleName -AutoSize
Line Severity RuleName
---- -------- --------
8 Warning PSAvoidUsingInvokeExpression
2 Warning PSAvoidUsingPlainTextForPassword
2 Warning PSReviewUnusedParameter
9 Warning PSUseShouldProcessForStateChangingFunctions
6 Warning PSUseDeclaredVarsMoreThanAssignments
7 Warning PSAvoidUsingCmdletAliases
Each line names line, severity and rule. What the rules say here:
PSAvoidUsingInvokeExpression:Invoke-Expressionruns a string as code. If a foreign value gets in, your script runs foreign code.PSAvoidUsingPlainTextForPassword: a parameter namedPasswordwith typestring. Learn names the names the rule looks for (among themPassword,Pass,Passphrase) and asks for the typeSecureString.PSUseShouldProcessForStateChangingFunctions: the functionRemove-Everythingchanges something (its verb isRemove) but knows noSupportsShouldProcess. This is the analyzer's mirror of PS.3.1.PSAvoidUsingCmdletAliases:gciis an alias; scripts use the full name.PSUseDeclaredVarsMoreThanAssignmentsandPSReviewUnusedParameter: something is assigned or declared and never read. In the example the latter belongs to the function that uses the script's parameter$Folderwithout declaring it itself.
With -Fix the analyzer writes into the file what it can repair safely. Run on a copy of the file:
Copy-Item .\bad.ps1 .\fixed.ps1
Invoke-ScriptAnalyzer -Path .\fixed.ps1 -Fix | Out-Null
Afterwards fixed.ps1 held [SecureString]$Password instead of [string]$Password and Get-ChildItem instead of gci. The four other messages remained because they require a decision. Never take the
parameter change from -Fix into your script unseen: string became SecureString, but every caller that hands the script a text now breaks. Run -Fix on a copy and read the difference (git diff).
A settings file
Which rules apply is decided by a settings file, so that everyone on the team and the pipeline run the same check. PSScriptAnalyzerSettings.psd1, a hashtable:
@{
Severity = @('Error', 'Warning')
ExcludeRules = @('PSAvoidUsingWriteHost')
}
Severity limits to errors and warnings (no mere information); ExcludeRules switches off a rule that makes no sense in your project. Every excluded rule deserves a reason, best in a line above it.
Call: Invoke-ScriptAnalyzer -Path . -Recurse -Settings .\PSScriptAnalyzerSettings.psd1. For a script that violates a rule in a single line you deliberately keep, a suppression attribute at that spot
fits better than the settings file (Learn describes it under "Suppressing rules").
The gate in the pipeline
Invoke-ScriptAnalyzer sets no exit code; it emits objects. A pipeline needs a gate that fails the run when there are messages. gate.ps1:
param([Parameter(Mandatory)][string]$Path)
$findings = @(Invoke-ScriptAnalyzer -Path $Path -Recurse -Settings "$PSScriptRoot\PSScriptAnalyzerSettings.psd1")
$findings | Format-Table Line, RuleName, ScriptName -AutoSize | Out-String -Width 160
"findings: $($findings.Count)"
if ($findings.Count -gt 0) { exit 1 }
@(…) always turns the result into an array, so .Count is right for zero or one finding (remember @($null).Count from PS.2). With pwsh -NoProfile -File .\gate.ps1 -Path .\bad.ps1 the run ended
with exit code 1 and six findings; on the module OfficeTools.psm1 from the last lesson with 0 and findings: 0. That the module is clean was no accident: it has SupportsShouldProcess,
no alias and no plain-text passwords. The manifest file OfficeTools.psd1, by contrast, got a warning PSUseBOMForUnicodeEncodedFile when checked: New-ModuleManifest had (with the German language
setting) written comments with umlauts, and the rule asks for a file with a byte-order mark for that. Whoever checks the manifest after generating it sees this message first. Solutions: delete the
comments, save the file with a BOM, or exclude the rule for the file with a reason.