Skip to content

fix(logs)!: end the agent-log commands with terminating errors - #89

Merged
fadwen merged 3 commits into
mainfrom
fix/terminating-errors
Nov 23, 2026
Merged

fadwen merged 3 commits into
mainfrom
fix/terminating-errors

Conversation

@fadwen

@fadwen fadwen commented Nov 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

The first area of #64: the commands that read the agent's logs. Get-IntuneAgentLog, Get-IntuneAgentTimeline, Export-IntuneAgentDiagnostic and the two private functions that parse the logs ended on a failure with throw. A caller's -ErrorAction SilentlyContinue suppresses a throw and lets the function carry on, and a throw of a string has no error ID. They now end with $PSCmdlet.ThrowTerminatingError() and a record that has an ID and a category (ERR-10, ERR-11, ERR-14). Refs #64, which stays open for the other three areas.

Replacing the throw statements alone would have made the module worse. ThrowTerminatingError ends only the function that calls it: the module function that made the call goes on at its next statement with nothing where the result should be, unless the call is inside a try that has a catch. The measurements are in a comment on #64. So this change also guards the calls, and adds a test that holds the rule for the whole module.

This pull request is stacked on #87 (fix/process-tree-cleanup) and merges after it.

This changes what a caller sees. A script that calls one of the three commands without try and without $ErrorActionPreference = 'Stop' now goes on at its next statement after the command fails, where it used to end. That is the behaviour of a compiled cmdlet and the one ERR-10 chooses.

Changes

  • The four throw statements of the area are replaced, in Get-IntuneAgentLog, Export-IntuneAgentDiagnostic, ConvertFrom-IslCmTraceLog and ConvertTo-IslCmTraceTime. The IDs are UnknownAgentLogEvent (Get-IntuneAgentLog -EventName), CmTraceTimestampInvalid (both parsers) and DiagnosticPackageExists (Export-IntuneAgentDiagnostic without -Force).
  • Each call that can fail is inside a try with a catch that ends the function: the path resolution and the parse in Get-IntuneAgentLog, the read in Get-IntuneAgentTimeline, the file access in ConvertFrom-IslCmTraceLog, and the whole transaction of Export-IntuneAgentDiagnostic, whose try had only a finally.
  • Get-IntuneAgentLog reports a path that does not exist, and a log it cannot read or parse, with WriteError and goes on with the other paths and logs (ERR-13); the first such item used to end the command. -ErrorAction Stop ends it there. Get-IntuneAgentTimeline and Export-IntuneAgentDiagnostic read the logs through it, so the timelines are built from the logs that could be read and the package is still written, with every log in it. A path that cannot be resolved no longer draws the warning about a folder without logs as well.
  • New private function New-IslErrorRecord builds the record: message, ID, category, target, exception type and inner exception. It does not fail for any input, because it is called in the argument of ThrowTerminatingError, where an error would end only that statement and the function would go on as if it had detected nothing.
  • New test file Tests/Unit/Module.ErrorFlow.Tests.ps1 checks the rule on the syntax trees of Public, Private and Private/Rules, nested functions included: no call to a function that ends with ThrowTerminatingError outside a try with a catch. It also lists the 46 calls that still rely on a throw in the function they call, and that list has to match the code exactly, so it shrinks with each area and a new unguarded call fails the test.
  • New test helper Invoke-CallerScript runs statements as a script in a new process that has no try and the default error preference, and returns what the script wrote and the IDs of the errors the session recorded.
  • The tests of the three commands assert the error IDs with Should-Throw -FullyQualifiedErrorId, and each has a test through Invoke-CallerScript.
  • README.md has a troubleshooting row for a script that goes on after one of these commands failed, CHANGELOG.md has the entry under Changed with the consequence for callers, and CLAUDE.md records the invariant.

Verification

  • From a script without try, in a new process, on PowerShell 7.6.10 and Windows PowerShell 5.1, six failure cases (a missing folder, an unknown event, a log with a bad timestamp, an existing zip, and the last two through the timeline and the export). Before this change each ended the script with no output. After it, a bad argument and an existing package end the command with the one error of that failure, and the script goes on. A missing path and a log with a bad timestamp are reported once for that item, and the command returns what the other logs hold.
  • The contract test finds a missing guard where the behaviour does not: with the guard of Get-IntuneAgentTimeline removed, the 11 tests of that command still passed, because going on with no entries also returns no timelines, and Module.ErrorFlow.Tests.ps1 failed and named Get-IntuneAgentTimeline -> Get-IntuneAgentLog.
  • ./Tests/Invoke-Tests.ps1 -CodeCoverage on PowerShell 7.6.10: 1,086 passed, 3 failed, 7 skipped, coverage 95.22 percent. ./Tests/Invoke-Tests.ps1 on Windows PowerShell 5.1: 1,050 passed, 3 failed, 43 skipped. The three failures are the ones that fail on that computer without this change and pass in CI (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).
  • Invoke-ScriptAnalyzer at Error and Warning on the 13 changed script files: no findings. Test-StandardsCompliance.ps1 of ai-powershell-standards 2.0.0: no finding in the three new files, and no ERR-11 finding left in the five converted ones.
  • ./Build/Publish-Module.ps1 -WhatIf: the staged module imports, exports the declared commands and serves its help.
  • After the commit for ERR-13, the tests of the five functions and the contract test on both versions: 58 passed, 0 failed on each.
  • quality-gates.yml, dispatched on this branch because it triggers only for pull requests into main, run 45268336847: all five jobs passed. After the commit for ERR-13, run 45273313845: all five jobs passed.

Notes

  • One call to a function that ends with ThrowTerminatingError is listed in the test as a known exception: Invoke-IslProcess -> Stop-IslProcessTree, the cleanup after a timeout. Measured, a failure of it leaves the run with its TimedOut result and without its output. It is fixed with the runtime harness, the next area.
  • ERR-13 is applied to the paths and the log files, which are the items of the command's input. An entry with a bad timestamp still ends the reading of its file: that log gives no entries, not the ones before the bad one. Export-IntuneAgentDiagnostic reads the logs twice, for the events and for the timelines, so it reports a log that cannot be parsed twice.
  • The 7 throw statements in nested and plain functions are untouched; they stay allowed until Nested helper functions have no CmdletBinding, help or parameter types (FUN-01, DOC-01, FUN-20, MOD-01) #65 makes those functions advanced.
  • The three remaining areas are the runtime harness, the tenant commands, and the analysis and rule commands, in the order of the comment on Advanced functions end with throw instead of ThrowTerminatingError (ERR-10, ERR-11, ERR-14) #64.

Get-IntuneAgentLog, Get-IntuneAgentTimeline and
Export-IntuneAgentDiagnostic, and the two private functions that parse
the logs, ended on a failure with throw. A throw is suppressed by a
caller's -ErrorAction SilentlyContinue, after which the function carries
on as if it had succeeded, and it carries no error ID. They now end with
$PSCmdlet.ThrowTerminatingError() and a record that has an ID and a
category of its own (ERR-10, ERR-11, ERR-14).

That change is not safe by itself. ThrowTerminatingError ends only the
function that calls it: the module function that made the call goes
on at its next statement, with nothing where the result should be,
unless the call is inside a try that has a catch. So each of the five
functions also guards its calls that way: the read of the logs in
Get-IntuneAgentLog and Get-IntuneAgentTimeline, the file access in
ConvertFrom-IslCmTraceLog, and the whole transaction of
Export-IntuneAgentDiagnostic, which had a try with only a finally.

New, for this area and the ones that follow (#64):

- New-IslErrorRecord builds the record. It does not fail for any
  input, because it is called in the argument of ThrowTerminatingError
  and an error there would end only that statement.
- Tests/Unit/Module.ErrorFlow.Tests.ps1 checks the rule on the syntax
  trees: no call to a function that ends with ThrowTerminatingError
  outside a try with a catch. It lists the 46 calls that still rely
  on a throw, and the list has to match the code. Behaviour does not
  show a missing guard reliably: with the guard of
  Get-IntuneAgentTimeline removed, its tests still passed, and this
  test failed and named the call.
- Invoke-CallerScript, a test helper, runs statements from a script
  in a new process that has no try, for what such a caller sees.

BREAKING CHANGE: a script that calls Get-IntuneAgentLog,
Get-IntuneAgentTimeline or Export-IntuneAgentDiagnostic without try
and without $ErrorActionPreference = 'Stop' now goes on at its next
statement after the command fails, where it used to end. Set the
preference at the top of the script, or make the call inside try.

Refs #64

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

# statement, and the timelines would be built from nothing
try {
$entries = @(Get-IntuneAgentLog @logSplat)
} catch {

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 guard changes nothing a test of behaviour can see. Without it the command goes on with no entries and returns no timelines, which is also what it returns when it stops here; the 11 tests of this command passed with the guard removed. It is here because the rule has to hold everywhere to hold where it matters, and Module.ErrorFlow.Tests.ps1 is what fails when it is missing.

}
$entryCount = Compress-Staging -Folder $staging -Destination $zip
}
catch {

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 try had only a finally. A terminating error raised by a function called inside it, such as the read of a log with a bad timestamp for the timeline, ended that one statement, and the command went on to write the manifest and the zip. With the catch the command ends, and the finally still removes the staging folder. Measured from a script without try: no zip is written, and an existing one is left as it was.

$kept = @(ConvertFrom-IslCmTraceLog -Path $file @parseSplat)
try {
$kept = @(ConvertFrom-IslCmTraceLog -Path $file @parseSplat)
} catch {

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 log that cannot be parsed still ends the whole command, as the throw in the parser did. ERR-13 would report the file with WriteError and go on with the other logs. That would be a change of behaviour of its own, so it is left as a question in the description.

$exception = $ExceptionType::new($Message, $InnerException) -as [System.Exception]
} catch {
# The type has no such constructor. The record is still built: see the description
Write-Debug "No $($ExceptionType.FullName) could be built for error $ErrorId."

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.

An earlier form of this function validated the ID with a pattern and ended with an error for a type it could not build. Both made it possible for the function to fail in the argument of ThrowTerminatingError, which ends that statement only: the caller would have gone on past the failure it had just detected. So it accepts anything and falls back to InvalidOperationException. The typo that validation would have caught is caught by the tests that assert each ID.

# The caller would carry on with nothing where the result should be. The one exception is
# the cleanup after a timeout: measured, a failure of it leaves the run with its TimedOut
# result and without its output. It goes with the runtime harness, the next area of #64
$known = @(

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 known exception, from #87. Stop-IslProcessTree ends with ThrowTerminatingError when taskkill.exe cannot be started, and Invoke-IslProcess calls it outside a try with a catch. Measured, the run then returns its TimedOut result without its output. Guarding it means deciding what a timed-out run returns when its cleanup fails, which belongs with the rest of Invoke-IslProcess in the next area.

Wait = $true
PassThru = $true
}
$process = Start-Process @startParameters

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.

Start-Process with the streams redirected to files, not the call operator: the script is expected to write errors, and Windows PowerShell 5.1 turns what a native command writes to a redirected error stream into error records, which end the test under the error preference of a CI step. That is the mechanism of #86.

Get-IntuneAgentLog ended at the first path that did not exist and at
the first log it could not read or parse. Each path and each log is
one item of its input, and the others can still be read, so such an
item is now reported with WriteError and the command goes on (ERR-13).
A caller that wants the command to end there passes -ErrorAction Stop.

A path that cannot be resolved no longer draws the warning about a
folder without logs as well: the error has said why nothing came back.

Get-IntuneAgentTimeline and Export-IntuneAgentDiagnostic read the logs
through this command. The timelines are built from the logs that could
be read, and the package is still written, with every log in it,
which is what a ticket needs most when one log is damaged.

Refs #64
@fadwen

fadwen commented Nov 23, 2026

Copy link
Copy Markdown
Owner Author

ERR-13 is now applied in bd4cf8a, as decided: Get-IntuneAgentLog reports a path that does not exist and a log it cannot read or parse for that one item, and goes on with the others. The line note on Get-IntuneAgentLog.ps1 that called this an open question is settled by that commit, and the description above is updated. The run after it, 45273313845, passed all five jobs.

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

Verdict: approve. No blockers or should-fixes, one nit.

Reviewed against ai-powershell-standards (ERR-10, ERR-11, ERR-13, ERR-14). Checked in a Linux sandbox with pwsh 7.6.0 and Pester 6.2.0.

Verified

  • No regressions (differential run): full unit suites on #87 and on this branch, same seed.
    • Passes went from 871 to 886.
    • The 5 new failures on Linux are all platform-related: Start-Process -WindowStyle in the new Invoke-CallerScript helper is not supported on Linux, and Windows paths give DriveNotFound. None of them is a logic failure.
    • No test that passed on #87 fails here.
  • Module.ErrorFlow.Tests.ps1 catches a missing guard, as claimed: I removed the try/catch around Get-IntuneAgentLog in Get-IntuneAgentTimeline. The test then failed and named Get-IntuneAgentTimeline -> Get-IntuneAgentLog. With the guard back it passes 3/3.
  • New-IslErrorRecord.Tests.ps1: 8/8. The fallback to InvalidOperationException means building a record can't itself fail inside the argument of ThrowTerminatingError.
  • The four throw statements: each is replaced with an ID and a category. The IDs match the description.
  • The ! and the CHANGELOG: both mark the behaviour change for callers.
  • ERR-13 in Get-IntuneAgentLog: a path that can't be resolved and a log that can't be parsed are each reported with WriteError, and the command goes on with the rest.
    • The warning about a folder without logs is now skipped only when every path failed, which is right.
    • Under -ErrorAction Stop given to Get-IntuneAgentTimeline, the inner WriteError becomes terminating and reaches the outer catch, so the timeline ends as documented.

Unverified (needs Windows or CI): the caller-script runs on 5.1 and 7.6, and CI runs 45268336847 and 45273313845. This PR has no checks because its base isn't main.

Nit: Tests/TestHelpers/TestHelpers.ps1, Invoke-CallerScript. It uses Start-Process -WindowStyle, which exists only on Windows. That's fine for a suite that is Windows-only, but splatting WindowStyle only when $IsWindows is true (or on 5.1) would let the error-flow tests run on the Linux help job too, if you ever want that.

Invoke-CallerScript started its child process with -WindowStyle Hidden. Start-Process has that parameter on Windows only, so the helper failed on Linux before it ran anything. The suites are Windows-only, but the Linux job imports the module and could run the tests of the error flow one day. The parameter is now added to the call on Windows alone.

Refs #64
@fadwen

fadwen commented Nov 23, 2026

Copy link
Copy Markdown
Owner Author

The nit is addressed in 07f7f5f.

  • Invoke-CallerScript and -WindowStyle: the parameter is added to the call on Windows only, so the helper no longer fails on Linux before it has run anything. The suites stay Windows-only for now; the paths in these tests are Windows paths, as the review's DriveNotFound failures show.
  • Checked: the 37 tests of the three commands that use the helper pass on PowerShell 7.6.10 and on Windows PowerShell 5.1. CI on this branch after the commit: run 45282676367 passed all five jobs.

Base automatically changed from fix/process-tree-cleanup to main November 23, 2026 23:44
@fadwen
fadwen merged commit bb3f31b into main Nov 23, 2026
5 checks passed
@fadwen
fadwen deleted the fix/terminating-errors branch November 23, 2026 23:44
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