Skip to content

fix(harness)!: raise run failures as terminating errors with IDs - #92

Open
fadwen wants to merge 3 commits into
mainfrom
fix/terminating-errors-harness
Open

fadwen wants to merge 3 commits into
mainfrom
fix/terminating-errors-harness

Conversation

@fadwen

@fadwen fadwen commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

The runtime harness is the second area of #64. The five Invoke-Intune*Test commands and the private functions they launch scripts through ended on a failure with throw. A caller's -ErrorAction SilentlyContinue suppresses a throw and lets the function carry on past it, and a string carries no ID to tell one failure from another (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 end that way is inside a try with a catch.

Closes #91: reading the launch path for this turned up a run that went on after its script could not be copied.

This changes what a calling script sees. A script that calls one of the five commands without try and without $ErrorActionPreference = 'Stop' goes on at its next statement after a failure, where it used to end. The CHANGELOG and the README's troubleshooting table say so.

Changes

  • Error records in place of throw. Get-IslHostPath (HostArchitectureUnavailable, HostNotFound), Grant-IslFolderAccess (FolderAccessNotGranted), Invoke-IslProcess (ProcessStartFailed, ScheduledTaskNotRegistered, ScheduledTaskNotStarted), the -Credential with -Context System check of all five commands (CredentialWithSystemContext) and the argument checks of Invoke-IntuneWin32AppTest (DetectionMissing, IntentCommandMissing, RelatedAppNameMissing, RelatedAppDetectionMissing). The messages are unchanged. Get-IslOemEncoding used a throw to jump to its own catch; it is an if now.
  • One script among several (ERR-13). Invoke-IntuneDetectionTest, Invoke-IntuneRequirementTest and Invoke-IntunePlatformScriptTest take scripts from the pipeline. A script that cannot be run, such as one that is not there or one asked to run in a host the device does not have, is reported with $PSCmdlet.WriteError() and the next script still runs. -ErrorAction Stop ends the command there.
  • One flow. Invoke-IntuneRemediationTest and Invoke-IntuneWin32AppTest run several steps that depend on each other, so their flow is one try and a step that cannot be run ends the command. The two nested functions of Invoke-IntuneWin32AppTest have no catch of their own and rely on that try. The detection inside the flow is called with -ErrorAction Stop: without it a detection that could not be run returned nothing, which the flow read as "detected", and an uninstall would have run.
  • The launch is one transaction (Runtime harness starts the host when the script could not be copied #91). In Invoke-IslScriptRun the run folder, the copy of the script, the folder access and the launch are one try, and New-Item and Copy-Item have -ErrorAction Stop. Invoke-ContentCommand in Invoke-IntuneWin32AppTest does the same for the content folder. The finally that removes the run folder now covers a failed copy as well.
  • The cleanup after a timeout. Invoke-IslProcess ends with the error of a Stop-IslProcessTree that could not be run, in the direct path and in the scheduled-task path. The contract test no longer has an exception for that call.
  • Invoke-IslNativeCommand, a new private function, runs taskkill.exe and icacls.exe as a process whose streams .NET redirects and returns the exit code and both texts. Stop-IslProcessTree had that code inline. Grant-IslFolderAccess called icacls.exe with the call operator and set $ErrorActionPreference = 'Continue' to survive Windows PowerShell 5.1 turning the redirected error stream into error records; it no longer sets the preference (ERR-02).
  • Tests/Unit/Module.ErrorFlow.Tests.ps1. A call made in a nested function counts as guarded when every call of that nested function is guarded, because a try covers everything called below it. The list of calls that still rely on a throw goes from 46 to 33, and the list of calls to a function that ends quietly is empty with no exception.
  • Tests. Error IDs are asserted with Should-Throw -FullyQualifiedErrorId. New cases: two scripts through the pipeline with the first one failing, under -ErrorAction Continue and Stop, for each of the three commands; a script held open so that it cannot be copied, with the host not started; a process that cannot be started; a cleanup that fails; and three cases in Tests/Integration/RuntimeHarness.Tests.ps1 that run a calling script without try in a new process against real launches. Tests/Unit/Private/Invoke-IslNativeCommand.Tests.ps1 is new.
  • Docs. CHANGELOG, the README's troubleshooting row, the description of the five commands in docs/IntuneScriptLab/ with the rebuilt en-US/IntuneScriptLab-Help.xml, and two paragraphs in CLAUDE.md.

Verification

  • ./Tests/Invoke-Tests.ps1 -CodeCoverage on PowerShell 7.6.10: 1,132 passed, 7 skipped, 95.46 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,096 passed, 43 skipped, the same 3 failed. That run was made before a last change to one test of Invoke-IslProcess and to the layout of two functions; the files those touch, 33 tests, passed on both versions afterwards.
  • On the lab device as NT AUTHORITY\SYSTEM under Windows PowerShell 5.1.26100.9818, every suite: 1,095 passed, 0 failed, 47 skipped (they need PowerShell 7, PSScriptAnalyzer or the Proxmox host). The SYSTEM-context tests and the tests that run as another account were among those that ran. No IntuneScriptLab-* task and no run folder was left. The tree on the device was the one before the same last change.
  • Two of the new tests were run against the code with its fix taken out: without -ErrorAction Stop on the copy, the test with the script held open fails ("Expected an exception"), and without -ErrorAction Stop on the detection inside the Win32 flow, the uninstall case fails (no result: False).
  • Invoke-ScriptAnalyzer -Path . -Recurse -Severity Error, Warning -ExcludeRule PSAvoidLongLines: 0 findings.
  • The standards' compliance check on the twelve changed files of Public and Private: the 16 ERR-11 findings are gone, and what remains in each file is the layout (Source layout does not follow the standards and CI does not check it (STY-01, STY-02, STY-04, STY-07) #73) and nested-function (Nested helper functions have no CmdletBinding, help or parameter types (FUN-01, DOC-01, FUN-20, MOD-01) #65) findings it had before, with one STY-02 fewer.
  • ./Build/Publish-Module.ps1 -WhatIf: staged, imported in a new process and verified; nothing published.
  • quality-gates.yml on the last commit, 8a4dc4a: run 45301781578 passed all five jobs.
  • Two earlier runs failed. Both failed the analysis job for one line of 124 characters in a test file, which the local analyzer call leaves out and CI checks; 8a4dc4a wraps it. The first run also failed one test on the ARM64 runner: Module.WhatIf.Tests.ps1, "does not ask again inside a run the caller agreed to", where a run in the emulated x86 host did not end within its 60 seconds. The same test passed on ARM64 in the two runs after it, with the same harness code, and it passed in every earlier run of that job. It is recorded here as seen once, not explained.
  • After the first push, 5ae4ea0 put the reason before the count of files in the message of FolderAccessNotGranted; the tests of Grant-IslFolderAccess and Invoke-IslScriptRun passed on both versions afterwards.

Notes

The five Invoke-Intune*Test commands and the private functions they
launch scripts through ended on a failure with throw. A caller's
-ErrorAction SilentlyContinue suppresses a throw and lets the function
carry on past it, and a string carries no ID to tell one failure from
another (ERR-10, ERR-11, ERR-14). Each throw 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, so that no caller goes on with nothing where a result should
be.

Invoke-IntuneDetectionTest, Invoke-IntuneRequirementTest and
Invoke-IntunePlatformScriptTest take scripts from the pipeline. A
script that cannot be run is reported for that script and the next one
still runs (ERR-13). Invoke-IntuneWin32AppTest calls the detection
with -ErrorAction Stop for that reason: a detection that returned
nothing read as detected, and an uninstall would have run.

The run folder, the copy of the script, the folder access and the
launch are one try in Invoke-IslScriptRun, and the copy has
-ErrorAction Stop. Under PowerShell 7 a copy that failed was reported
and the host was started on a file that was not there (#91). A cleanup
after a timeout that could not be run ends the run with its error,
where the run returned a TimedOut result and left the process running.

taskkill.exe and icacls.exe run through Invoke-IslNativeCommand, which
starts a process and reads its streams, so Grant-IslFolderAccess no
longer sets $ErrorActionPreference (ERR-02).

The contract test counts a call made in a nested function as guarded
when every call of that nested function is inside a try with a catch,
and its list of calls that still rely on a throw loses the thirteen of
this area.

Refs #64. Closes #91.

BREAKING CHANGE: a script that calls one of the five Invoke-Intune*Test
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. The three commands that
take scripts from the pipeline report a script that cannot be run as a
non-terminating error; pass -ErrorAction Stop to end the command
there.

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

$script = $null
if ($Path) {
$script = Invoke-IntuneDetectionTest -Path $Path @detectionSplat @script:IslInternal
$detectionRun = @{ Path = $Path; 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 here because the detection command changed in this pull request: it now reports a script it cannot run without ending. Without the parameter the call returns nothing, $null -eq $script below reads as detected, and an uninstall runs. The integration test "ends a Win32 uninstall at the detection that is not there" fails with no result: False when the parameter is taken out.

# A script that cannot be run is reported, and the next one from the pipeline still runs
try {
if ($EnforceSignatureCheck) {
$scriptPath = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath

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 path is resolved only where the signature check needs the file, as before. A first version resolved it for every call, and ten unit tests failed: they mock the launch and pass C:\lab\detect.ps1, which does not exist. Invoke-IslScriptRun resolves the path for a real run.

try {
$run = Invoke-IslScriptRun @scriptRunSplat
} 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.

ERR-13: one script from the pipeline that cannot be run is an error for that script. An architecture the device does not have arrives here too, once for each script, although it is the same for all of them; the Notes of the description say why it is not checked once in begin.


try {
$null = New-Item -ItemType Directory -Path $cache -Force -ErrorAction Stop @script:IslInternal
Copy-Item -LiteralPath $source -Destination $scriptCopy -ErrorAction Stop @script:IslInternal

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 the fix for #91. Under PowerShell 7 Copy-Item reports a file it cannot read without ending, and the function went on to start the host. The copy also moved inside the try, so the finally removes the run folder when the copy fails.

$timedOut = $true
# The cleanup is not the caller's to preview or confirm. A function of this module
# sees a global $WhatIfPreference, and under it the tree would stay and the wait
# below would not end. A cleanup that could not be run ends the function with its

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 decision more than a conversion. Before, a Stop-IslProcessTree that could not start taskkill.exe ended only itself, and the run returned TimedOut with no output while the process went on. The alternative was to keep the TimedOut result and add a warning; an error was chosen because the result would claim a cleanup that did not happen.

while ($state -eq 'Running' -and (Get-Date) -lt $settleUntil)
}
} catch {
# The task that did not start, and a cleanup after a timeout that could not be run

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.

This catch also receives the ScheduledTaskNotStarted record that is raised a few lines up inside the same try, and passes it on unchanged. The test "reports a logon the scheduler refuses" asserts that the ID survives.

$recordSplat = @{
Message = "Could not grant $Account access to ${Path}: $output"
ErrorId = 'FolderAccessNotGranted'
Category = [System.Management.Automation.ErrorCategory]::PermissionDenied

@fadwen fadwen Nov 24, 2026 •

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 message is the one the function had, so that the two existing tests of it, under error action Continue and Stop, hold as they were. icacls.exe writes its reason to the error stream ("No mapping between account names and security IDs was done.") and a count of files to the output stream, so the message takes both, the reason first.

# A try covers what the nested functions called inside it call in turn. A nested function
# is covered when it is called at all and every call of it is guarded, or made by a nested
# function that is covered itself
$covered = @{}

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.

This loosens the rule in one direction only. A nested function is covered when it is called at least once and every call of it is inside a try with a catch, or made by a nested function that is itself covered. One unguarded call of the helper removes it from the set, and the calls it makes are reported again. The 33 lines that stay in the list below are unchanged by it.

# asked to end, and the test ends it afterwards
$script:LeftRunning = $null
Mock Stop-IslProcessTree -ModuleName IntuneScriptLab {
$script:LeftRunning = $ProcessId

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 mock stands in for a cleanup that cannot run, so the real process is still there when the function ends. A first version of this test let it end by itself; started in the test folder, it kept that folder from being removed when the shuffled order put this test last in the file. The test now starts it in the system folder and ends it in finally.

It 'refuses the 64-bit host that does not exist on this CPU' {
$path = New-TestScript 'noop.ps1' 'exit 0' -Bom
{ Invoke-IntunePlatformScriptTest -Path $path -Architecture $script:Missing } | Should-Throw
$refused = { Invoke-IntunePlatformScriptTest -Path $path -Architecture $script:Missing -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 expectation moved with ERR-13: the refused architecture is a non-terminating error of this command now, so the test asks it to stop and names the ID.

icacls.exe writes why it failed to its error stream and a count of
files to its output stream. The message of FolderAccessNotGranted
joined them output first, so it read "Successfully processed 0 files;
Failed processing 1 files" before the reason.
The analysis job refuses a line of more than 115 characters in the
test files as well. The two expectations of the assertion move into a
splat.
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.

Runtime harness starts the host when the script could not be copied

1 participant