Skip to content

fix(analysis)!: end the analysis and rule commands the cmdlet way - #96

Open
fadwen wants to merge 1 commit into
fix/terminating-errors-tenantfrom
fix/terminating-errors-analysis
Open

fadwen wants to merge 1 commit into
fix/terminating-errors-tenantfrom
fix/terminating-errors-analysis

Conversation

@fadwen

@fadwen fadwen commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Summary

Closes #64. The analysis and rule commands are its last area. Test-IntuneWin32Rule, Test-IntuneWin32Requirement, Get-IntuneAnalyzerRulePath, the Should- assertions and the private functions below them ended on a failure with throw (ERR-10, ERR-11, ERR-14). Each failure is now an error record with an ID and a category, raised with $PSCmdlet.ThrowTerminatingError(), and every call of a function that can fail is inside a try with a catch. With this, no command of the module ends with throw.

This pull request is stacked on #95, which is stacked on #92. The three merge in that order.

This changes what a calling script sees, in two ways. Test-IntuneScript and Repair-IntuneScript report a path that is not there, or a script they cannot analyze, as a non-terminating error and go on with the other scripts (ERR-13), so a script that gates a build on Test-IntuneScript has to pass -ErrorAction Stop. The other commands end with a terminating error, after which a script without try and without $ErrorActionPreference = 'Stop' goes on at its next statement.

Changes

  • One path and one script among several (ERR-13). In Test-IntuneScript and Repair-IntuneScript each path is resolved in a try, each script is processed in a try, a failure is written with $PSCmdlet.WriteError(), and what the script gave is written after the try. -ErrorAction Stop ends the command at the first such error.
  • -Settings is read once. Test-IntuneScript reads a -Settings argument in begin and uses that object for every script. An argument that is wrong ends the command before any script is analyzed, where it would otherwise have failed every script in turn. It was read and validated again for each script before.
  • Callers that need the findings ask the analysis to stop. With nothing returned, a script reads as one without findings. Test-PolicyScript in Test-IntuneDeployedScript, Repair-IntuneScript, Should-PassIntuneAnalysis, the PSScriptAnalyzer rule module and Examples/Invoke-IntuneScriptGate.ps1 pass -ErrorAction Stop.
  • Error records in place of throw: Test-IntuneWin32Rule (RuleOperatorMissing, RuleValueMissing, RuleValueNameMissing, RegistryHiveUnknown), ConvertFrom-IslRuleSpec (RuleIsScript, RuleTypeUnknown), Get-IslWindowsReleaseBuild (WindowsReleaseUnknown), Get-IntuneAnalyzerRulePath (AnalyzerRulesMissing) and Test-IslPesterAssertionSupport (PesterAssertionNotSupported), which is an advanced function with help now. The messages are unchanged.
  • Get-IslSetting is one try from the search to the settings object. The five checks of its nested function give one record, SettingsInvalid, for the first value that is wrong, in the order the checks had. The nested function has no [CmdletBinding()] and so no $PSCmdlet; it throws the record, and Get-IslSetting ends with it.
  • Tests/Unit/Module.ErrorFlow.Tests.ps1 has no list left. It fails for any call of a function that can fail that is not inside a try with a catch, and a second Describe checks the analysis itself on a sample module of four functions: a call with only a finally is reported, a call in a nested function is accepted when every call of that function is guarded, and reported when one is not.
  • Tests: two paths with the first not there, and two scripts with a settings file that is wrong above the first, for Test-IntuneScript; a path that is not there and a read-only script for Repair-IntuneScript; the assertion on a path that is not there; the gate, started from a command as another script starts it, on a folder whose settings file is wrong; IDs for every record.
  • Docs: CHANGELOG, the README's troubleshooting row, the descriptions of Test-IntuneScript, Repair-IntuneScript and Assert-PassIntuneAnalysis with the rebuilt en-US/IntuneScriptLab-Help.xml, and the error-flow section of CLAUDE.md.

Verification

  • ./Tests/Invoke-Tests.ps1 -CodeCoverage on PowerShell 7.6.10: 1,157 passed, 7 skipped, 95.25 percent coverage. 3 failed, the three that fail on this computer on main as well (Repair-IntuneScript corrupts an ANSI script on a host with a UTF-8 system code page #75 twice, In-box module table does not list UOPProviders, present on Windows 11 26H2 #76).
  • ./Tests/Invoke-Tests.ps1 on Windows PowerShell 5.1.26100: 1,121 passed, 43 skipped, the same 3 failed.
  • Three tests against the code with a stop request taken out. Without -ErrorAction Stop in the gate, the gate test fails: exit code 0 for the folder whose script was not analyzed. Without it in Should-PassIntuneAnalysis, the assertion on a path that is not there passes, and its test fails. The gate test started with -File did not fail without the fix, which is why it starts the gate from a command.
  • The lab tenant, read-only, as for fix(tenant)!: end the tenant commands with terminating errors #95: the three tenant commands from main and from this branch give 1,027 findings, 183 drift results and 151 health reports, and the two JSON files are identical. The pre-flight is the caller of the analysis that matters there.
  • CI's analysis step run locally: PSScriptAnalyzer 0 findings, no line over 115 characters.
  • The standards' compliance check on the changed files of Public, Private, PSScriptAnalyzer and Examples: the 8 ERR-11 findings are gone, DOC-01 and FUN-01 are gone for Test-IslPesterAssertionSupport, and nothing is added. No file of the shipped module has an ERR-11 finding left.
  • ./Build/Publish-Module.ps1 -WhatIf: staged, imported in a new process and verified, with the changed gate and rule module in the package; nothing published.
  • quality-gates.yml, started by hand on this branch because the pull request is not based on main: the result is added below when the run ends.
  • Not run on the lab device: this area starts no process and registers no task.

Notes

  • The risk in this pull request is a gate of the caller's own. A script that calls Test-IntuneScript and fails a build on the findings, written before this change, relied on the command ending the script for a path it could not read. After it, such a script goes on with the findings of the other scripts unless it passes -ErrorAction Stop or runs in the global scope with $ErrorActionPreference = 'Stop', as one started with pwsh -File or from a GitHub Actions pwsh step does. The shipped gate was affected in the remaining case, called with & from another script: with the fix taken out, the new gate test gets exit code 0 for a folder whose script was never analyzed. The CHANGELOG says this in bold. If that risk is not wanted, the alternative is to keep Test-IntuneScript ending on the first such item and apply ERR-13 to Repair-IntuneScript alone.
  • Two throw statements are left in the module, both in nested functions without [CmdletBinding()]: the retry loop of Invoke-IslGraphRequest passes on the error it caught, and Get-IslSetting's nested function throws its record. Nested helper functions have no CmdletBinding, help or parameter types (FUN-01, DOC-01, FUN-20, MOD-01) #65 gives those functions a $PSCmdlet.
  • Test-IntuneWin32Rule -Rule calls itself with the parameters the hashtable gives. That call is inside the try as well, so a hashtable that leaves a value out ends with RuleOperatorMissing, as the same parameters do.

The last area of #64. Test-IntuneWin32Rule,
Test-IntuneWin32Requirement, Get-IntuneAnalyzerRulePath, the Should-
assertions and the private functions below them ended on a failure
with throw (ERR-10, ERR-11, ERR-14). Each failure is now an error
record with an ID and a category, raised with ThrowTerminatingError,
and every call of a function that can fail is inside a try with a
catch. No command of the module ends with throw any more.

Test-IntuneScript and Repair-IntuneScript take several paths. A path
that is not there, and a script that cannot be analyzed or written, is
reported for that one item and the other scripts are still processed
(ERR-13). A -Settings argument is read once in begin, so one that is
wrong still ends the command before any script is analyzed.

A caller that needs the findings must now ask the analysis to stop:
with nothing returned, a script reads as one without findings. The
tenant pre-flight, Repair-IntuneScript, Should-PassIntuneAnalysis, the
PSScriptAnalyzer rule module and Examples/Invoke-IntuneScriptGate.ps1
pass -ErrorAction Stop. The gate, called from another script, passed
on a script that was never analyzed without it.

The contract test has no list of exceptions left. It fails for any
call of a function that can fail outside a try with a catch, and
checks its own analysis on a sample module of four functions.

Closes #64.

BREAKING CHANGE: Test-IntuneScript and Repair-IntuneScript report a
path that is not there, or a script they cannot analyze, as a
non-terminating error and go on with the other scripts. A script that
gates a build on Test-IntuneScript has to pass -ErrorAction Stop. The
other commands of this area end with a terminating error, after which
a script without try and without $ErrorActionPreference = 'Stop' goes
on at its next statement, where it used to end.

@fadwen fadwen left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Notes on the lines whose reason the diff does not show.

$givenSettings = $null
if ($PSBoundParameters.ContainsKey('Settings')) {
try {
$givenSettings = Get-IslSetting -Path $PWD.Path -Settings $Settings

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Read here, once, because of ERR-13 below. With every script in its own try, a -Settings argument that is wrong would have been reported once for each script and the command would have returned nothing with a list of identical errors. -Path is mandatory on Get-IslSetting and is not used when -Settings is given, so the current location stands in for it.

($IncludeSuppressed -or -not $_.Suppressed)
})
} catch {
$PSCmdlet.WriteError($_)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The decision this pull request carries: one script that cannot be analyzed is an error for that script, and the next one is still analyzed. It follows the earlier decision for the log files (#89). The cost is in the Notes of the description: a caller that needs every script analyzed has to pass -ErrorAction Stop.

# with no findings this command would call the script repaired
$testSplat = @{
Path = $file; ScriptType = $ScriptType; Context = $Context; Architecture = $Architecture
ErrorAction = 'Stop'

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needed because the analysis changed in this same pull request. Without it, a script that could not be analyzed would come back with no findings and be reported as Applied 0, Remaining 0: repaired. The error ends this script's try, is written for this script, and the next script is still repaired.

# such a path and goes on, and with nothing analyzed there is no finding: the assertion
# would pass
$analysisSplat = @{
Path = $paths; ScriptType = $ScriptType; MinimumSeverity = $MinimumSeverity; ErrorAction = 'Stop'

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without ErrorAction = 'Stop' here, 'no-such-file.ps1' | Should-PassIntuneAnalysis passes. The test "fails for a path that is not there" fails when the entry is taken out.

# -ErrorAction Stop: the analysis reports a script it cannot read and goes on with the others,
# and a gate must not pass on scripts that were not analyzed. The preference set above does not
# reach a module's command unless this script runs in the global scope
$testSplat = @{ Path = $scriptFiles; ScriptType = $ScriptType; ErrorAction = 'Stop' }

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The preference this script sets at its top reaches the module only when the script runs in the global scope, as it does when started with -File. Called with & from another script it does not, and the gate went on to print 0 finding(s) and exit 0 for a folder whose script was never analyzed. The new test in ScriptGate.Tests.ps1 starts the gate that way for this reason.

$architecture = $Table['Architecture']
$severityTable = $Table['Severity']
# The first value that is wrong is the one reported
$problem = $null

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Five throw statements became one. The order of the checks is kept, so the value named for a table with several wrong values is the one that was named before; the test with Context = 'Admin'; ScriptType = 'Script' holds that.

Category = [System.Management.Automation.ErrorCategory]::InvalidData
TargetObject = $Source
}
throw (New-IslErrorRecord @recordSplat)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A throw on purpose. This nested function has no [CmdletBinding()], so it has no $PSCmdlet to end with (#65). Throwing the record instead of a string keeps the ID and the category: the catch of Get-IslSetting ends with this same record.

$splat = ConvertFrom-IslRuleSpec -Rule $Rule
if ($Rule.ContainsKey('RuleType') -and $Rule.RuleType) { $splat.RuleType = $Rule.RuleType }
else { $splat.RuleType = $RuleType }
$ruleResult = Test-IntuneWin32Rule @splat

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The command calls itself with the parameters the hashtable gives. The contract test does not look at a call of a function to itself, so this one was put inside the try by hand: otherwise the inner call would end and the outer one would return nothing, which happens to look the same but only by luck.

'Test-IntuneWin32Rule -> ConvertFrom-IslRuleSpec'
)
$relying = @($script:Unguarded | Where-Object { -not $_.EndsQuietly } | ForEach-Object { $_.Call })
Describe 'The analysis itself, on a module of four functions' -Tag 'Unit', 'Contract' {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New because the list of exceptions was this file's proof that the analysis finds anything: a list that had to match the code could not be satisfied by a scan that found nothing. With the list empty, the proof is a module of four functions in the test drive with one unguarded call of each kind.

# of it into an error record of this test
$outFile = Join-Path $TestDrive 'gate-out.txt'
$errFile = Join-Path $TestDrive 'gate-err.txt'
$call = "& '$($script:Gate)' -Path '$folder'"

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With -File, as the other tests of this file start the gate, this test passed with and without the fix. It also keeps the error stream in a file: under Windows PowerShell 5.1, 2>&1 on the child process turned the gate's error text into error records of the test itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant