Skip to content

fix(tenant)!: end the tenant commands with terminating errors - #95

Open
fadwen wants to merge 1 commit into
fix/terminating-errors-harnessfrom
fix/terminating-errors-tenant
Open

fadwen wants to merge 1 commit into
fix/terminating-errors-harnessfrom
fix/terminating-errors-tenant

Conversation

@fadwen

@fadwen fadwen commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

The tenant commands are the third area of #64. Test-IntuneDeployedScript, Compare-IntuneDeployedScript, Get-IntuneScriptHealth and Test-IntuneAssignmentFilter, and the Graph seam and the export reader below them, ended on a failure with throw (ERR-10, ERR-11, ERR-14). Each failure the module detects is now an error record with an ID and a category, raised with $PSCmdlet.ThrowTerminatingError(), and every call of a function that can end that way is inside a try with a catch.

This pull request is stacked on #92 and merges after it.

This changes what a calling script sees. A script that calls one of the four commands without try and without $ErrorActionPreference = 'Stop' goes on at its next statement after a failure, where it used to end. What the commands return for a tenant they can read is unchanged.

Changes

  • Invoke-IslGraphRequest ends with the error Graph gave, unchanged, so a caller still reads the status code and the response from it; the retry logic is as it was. The module's own check has the ID GraphModuleNotLoaded.
  • Get-IslExportReport is one try from the export job to the rows, with -ErrorAction Stop on the download (ERR-12). Its three failures have the IDs ExportJobTimedOut, ExportJobFailed and ExportHasNoCsv.
  • Test-IntuneDeployedScript and Compare-IntuneDeployedScript write one result after another. Each list of policies is read inside a try, each policy is read and judged inside a try, and what the policy gave is written after that try (ERR-15). The output stays a stream, and an error of a command further down the pipeline is not caught as theirs. The outer try with the finally that removes the work folder is unchanged. Compare-IntuneDeployedScript has the ID LocalPathNotFolder for a -Path that is a file.
  • Get-IntuneScriptHealth collects its reports for the Markdown file, so its two reading parts are each one try. A file of -MarkdownPath that cannot be written is reported with WriteError, and the reports are still returned; see the first note below.
  • Test-IntuneAssignmentFilter ends in begin when the facts of this device cannot be read (DeviceFactsNeedWindows on another operating system), and process does not run.
  • Tests/Unit/Module.ErrorFlow.Tests.ps1: the list of calls that still rely on a throw goes from 33 to 13. The 13 are all in the analysis and rule commands.
  • Tests: IDs asserted for each record; a download without a CSV file, with the download removed; a download that fails; a policy read that fails after earlier policies were written; a caller's own error further down the pipeline; and for the three commands that read Graph, a calling script without try in a new process, with a stand-in for Invoke-MgGraphRequest that fails every request.
  • Docs: CHANGELOG, the README's troubleshooting row, the descriptions of the three commands in docs/IntuneScriptLab/ with the rebuilt en-US/IntuneScriptLab-Help.xml, and the Graph paragraph of CLAUDE.md.
  • Eleven lines of the three commands went over 115 characters when the try indented them and were split. The read of enforceSignatureCheck moved out of the hashtable that held it, in four places.

Verification

  • The lab tenant, read-only. Test-IntuneDeployedScript, Compare-IntuneDeployedScript and Get-IntuneScriptHealth were run from main and from this branch against the same tenant, with GET requests only (-SkipRunState for the apps, whose install counts need an export job). Both gave 1,027 findings, 183 drift results and 151 health reports, and the two JSON files of 647,685 characters are identical.
  • A script without try, every Graph request failing, on PowerShell 7.6.10 and Windows PowerShell 5.1: each of the three commands leaves one error, Graph is down, returns nothing, and the script reaches its end. On main the script ends at the command.
  • ./Tests/Invoke-Tests.ps1 -CodeCoverage on PowerShell 7.6.10: 1,142 passed, 7 skipped, 95.27 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,106 passed, 43 skipped, the same 3 failed.
  • CI's analysis step run locally: PSScriptAnalyzer 0 findings, no line over 115 characters.
  • The standards' compliance check on the seven changed files of Public and Private: the 6 ERR-11 findings are gone, one STY-02 with them, and nothing is added.
  • ./Build/Publish-Module.ps1 -WhatIf: staged, imported in a new process and verified; nothing published.
  • quality-gates.yml, started by hand on this branch because the pull request is not based on main: run 45310065917 passed all five jobs.
  • Not run on the lab device: this area starts no process and registers no task.

Notes

  • The Markdown file. On main, Get-IntuneScriptHealth -MarkdownPath with a folder that does not exist returns its reports and leaves a DirectoryNotFoundException behind, because a .NET exception ends only the statement. Putting the write inside the try of the reads would have ended the command without the reports, after everything had been read. The write has a try of its own instead, and the behaviour is the one main has, now stated in the code, the help and a test.
  • One policy among many. A read that fails for one policy ends the command; it is not reported for that policy with the rest still read. A failed Graph request is most often a failure of the session or of a permission, and would repeat for every policy. The two lookups that already degrade with a warning, group members and assignment filters, still do.
  • Test-PolicyScript calls Test-IntuneScript without -ErrorAction Stop. That is right while Test-IntuneScript ends on a failure; the analysis area, next, has to revisit it if that command starts to report a file it cannot read without ending.

Test-IntuneDeployedScript, Compare-IntuneDeployedScript,
Get-IntuneScriptHealth and Test-IntuneAssignmentFilter, and the Graph
seam and the export reader below them, ended on a failure with throw
(ERR-10, ERR-11, ERR-14). Each failure the module detects is now an
error record with an ID and a category, raised with
ThrowTerminatingError, and every call of a function that can end that
way is inside a try with a catch.

Invoke-IslGraphRequest ends with the error Graph gave, unchanged, so a
caller still reads the status code and the response from it. The
tenant commands end with it in turn.

The two commands that write one result after another read each policy
inside a try and write what it gave after that try (ERR-15), so the
output is still a stream and an error of a command further down the
pipeline is not caught as theirs. Get-IslExportReport is one try from
the job to the rows, and its download has -ErrorAction Stop.

Get-IntuneScriptHealth returned its reports when only the file of
-MarkdownPath could not be written, because a .NET exception ends
just the statement. It still does, now on purpose: the failed write is
reported with WriteError and -ErrorAction Stop ends the command.

The contract test's list of calls that still rely on a throw loses the
twenty of this area; thirteen remain, all in the analysis and rule
commands.

Refs #64.

BREAKING CHANGE: a script that calls one of the four tenant commands
without try and without $ErrorActionPreference = 'Stop' goes on at its
next statement after a failure, where it used to end. Set the
preference, or make the call inside try.

@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.

foreach ($summary in $summaries) {
# A read that fails ends the command. What one policy gives is written after its try, so
# that an error of a command further down the pipeline is not caught here
$policyOutput = try {

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.

Most of the diff of this file and of Compare-IntuneDeployedScript.ps1 is this: the body of each loop moved four spaces to the right, into a try whose output is assigned. Hide whitespace to see what else changed. The alternative with no indentation at all was to assign the output of the outer try and write it after the finally, which would have turned the stream into one batch at the end of a run that can take minutes.

}
Test-Assignment -PolicyKind 'Remediation' -Policy $policy -RunAsAccount $runAsAccount
Test-AssignmentFilter -PolicyKind 'Remediation' -Policy $policy
$policyOutput

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.

Written after the try, not inside it (ERR-15). A caller's | ForEach-Object { throw ... } raises its error at this statement, where no catch of this command is in the way; the test "does not take the error of a command further down the pipeline for its own" holds that.

Test-PolicyScript @remediateSplat @policySettings
}
else {
$detectOnlyEvidence = ('A remediation created without remediationScriptContent ran ' +

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 text is unchanged. It moved out of the hashtable because, four spaces further right, it needed a third line, and each continuation line inside a hashtable entry is one more indentation finding for #73 to clear. docs/Rules.md is built from Private/Rules only, so it does not read this.

$policyOutput = try {
$summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id'
$policy = Invoke-IslGraphRequest -Uri "$remediations/$summaryId"
$enforceSignature = Get-IslPropertyValue -InputObject $policy -Name 'enforceSignatureCheck'

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.

Moved out of the hashtable below for its length alone: inside the try the entry had 119 characters, and CI refuses more than 115. The same was done in three other places.

)
foreach ($counter in $counters) {
$runCount[$counter] = [int](Get-IslPropertyValue -InputObject $run -Name "${counter}DeviceCount")
# A policy that cannot be read ends the command: a report with gaps would read as health

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.

One try for all three kinds here, where the two commands above have one for each policy. This command already collected its reports in a list, because the Markdown file needs all of them, so nothing is lost by it.

} catch {
# The reports were read and are returned below. A file that could not be written is
# reported, and the caller decides with -ErrorAction whether that ends the command
$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 one place in this pull request where a failure does not end the command, and it is the behaviour main has by accident: a .NET exception ends only the statement, so the reports were returned with the error beside them. Measured on main and here with a folder that does not exist: 1 report and one DirectoryNotFoundException in both.

$PSCmdlet.ThrowTerminatingError($_)
}

if (-not $All) { return $reply }

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 reply is held in a variable for the length of the try and returned here. For a reply that is one object, a hashtable or the text of a $count, that is what return Invoke-Once ... gave. The comparison against the lab tenant is the check that nothing changed for real replies.

$PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat -TargetObject $ReportName))
}

Invoke-WebRequest -Uri $jobUrl -OutFile $zip -UseBasicParsing -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.

-ErrorAction Stop is new (ERR-12). Without it a download that failed was reported and the function went on to open a zip that was not there. The request carries no credential, the address is a signed one from the job, so SEC-09's -MaximumRedirection 0 does not apply.

Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force
. (Join-Path $script:ModuleRoot 'Tests\TestHelpers\TestHelpers.ps1')
# Stands in for the Graph module in a calling script: every request fails
$script:GraphDown = 'function global:Invoke-MgGraphRequest { ' +

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 function named Invoke-MgGraphRequest in the calling script, because a mock does not reach a new process. A function is found before a module's command of the same name, so the case does the same on a computer that has Microsoft.Graph.Authentication installed and on a runner that has not.

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