Skip to content

refactor(helpers): move the log, diagnostic and Graph helpers out - #101

Open
fadwen wants to merge 6 commits into
mainfrom
refactor/helpers-logs-graph
Open

fadwen wants to merge 6 commits into
mainfrom
refactor/helpers-logs-graph

Conversation

@fadwen

@fadwen fadwen commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

The second part of #65. Eight functions nested in Get-IslAgentLogEvent, Export-IntuneAgentDiagnostic and Invoke-IslGraphRequest are private functions in files of their own, each an advanced function with full comment-based help and an output type, taking as parameters what it read from the function around it. Behaviour does not change.

Stacked on #100; it merges after it.

Changes

Was Now Notes
Get-LiteralPrefix in Get-IslAgentLogEvent Get-IslRegexLiteralPrefix
ConvertTo-NamedGroup in Get-IslAgentLogEvent ConvertTo-IslNamedGroupPattern
Write-Section in Export-IntuneAgentDiagnostic Write-IslTextFile the staging folder as -Root; no lines still writes an empty file
Copy-SharedFile Copy-IslSharedFile
Get-RegistryText Get-IslRegistryText -Depth validated as 0 to 64; the callers pass 1 to 6
Compress-Staging Compress-IslFolder
Get-RetryDelay in Invoke-IslGraphRequest Get-IslGraphRetryDelay
Invoke-Once in Invoke-IslGraphRequest Invoke-IslGraphRequestOnce ends with ThrowTerminatingError where Invoke-Once used throw
  • ShouldProcess. The three that write files, Write-IslTextFile, Copy-IslSharedFile and Compress-IslFolder, declare SupportsShouldProcess (FUN-30), as Stop-IslProcessTree does. Export-IntuneAgentDiagnostic asks once for the whole package and calls them with @script:IslInternal; Tests/Unit/Module.WhatIf.Tests.ps1 finds every module function that declares SupportsShouldProcess and checks that each call of it has both pins.
  • No throw left. With Invoke-Once gone, no function of the module uses throw. Invoke-IslGraphRequest already called it inside a try with a catch, which the error-flow test checks, and Graph's error still reaches the caller unchanged.
  • Tests: a file for each new function under Tests/Unit/Private. The registry reader is tested against keys in Pester's TestRegistry: drive, the shared copy against a file held open for writing, the archive's entry names for forward slashes, and the retry delay against the same stand-in for Graph's exception that Invoke-IslGraphRequest.Tests.ps1 uses. The tests of the three callers are unchanged and pass.
  • CLAUDE.md says that no function uses throw, and the CHANGELOG entry of refactor(helpers): move four nested helpers into their own files #100 names the three further files.

Verification

Notes

  • Two mistakes in the first draft of the new help were caught before this was pushed, and are worth knowing about for the parts that follow. A .DESCRIPTION line that starts with .NET is read as a help keyword, and Get-Help then finds no help at all for the function; the standards' check reported it as DOC-01. And the help of Copy-IslSharedFile first said that Copy-Item refuses a file another process holds open for writing; measured, it copies it. What the shared-read stream is for is that a reader allowing only other readers is refused, which the test shows.

The second part of #65. Eight functions nested in
Get-IslAgentLogEvent, Export-IntuneAgentDiagnostic and
Invoke-IslGraphRequest are private functions in files of their own,
advanced functions with full help and output types, taking as
parameters what they read from the function around them:

- Get-LiteralPrefix -> Get-IslRegexLiteralPrefix
- ConvertTo-NamedGroup -> ConvertTo-IslNamedGroupPattern
- Write-Section -> Write-IslTextFile, with the staging folder as
  -Root; it takes no lines as an empty file, as the nested copy did
- Copy-SharedFile -> Copy-IslSharedFile
- Get-RegistryText -> Get-IslRegistryText
- Compress-Staging -> Compress-IslFolder
- Get-RetryDelay -> Get-IslGraphRetryDelay
- Invoke-Once -> Invoke-IslGraphRequestOnce

The three that write files declare SupportsShouldProcess (FUN-30), and
the diagnostic export calls them with -WhatIf:$false and
-Confirm:$false, as it does every internal operation after its own
question. Invoke-IslGraphRequestOnce ends with ThrowTerminatingError
where Invoke-Once passed Graph's error on with throw, so no function
of the module uses throw any more. Each new function has a test file
of its own; the tests of the three callers are unchanged.

Refs #65.

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

Verified (Linux sandbox, pwsh 7.6.0, Pester 6.2.0)

  • No regressions (differential run): full unit suites on #100 and on this branch, same seed.
    • Passes went from 973 to 1,012.
    • The 4 new failures on Linux are in the new tests and are environmental. Get-IslRegistryText uses Pester's TestRegistry: drive, which exists only on Windows. The shared-copy test expects a reader that allows only other readers to be refused, and Linux has no mandatory file locks.
    • Nothing that passed on #100 fails here.
  • Graph path unchanged:
    • Invoke-IslGraphRequest.Tests.ps1 passes 10/10, unchanged, and the new Invoke-IslGraphRequestOnce.Tests.ps1 passes 3/3.
    • Get-IslGraphRetryDelay now returns nothing instead of $null, and the caller still tests $null -eq $delay, so the retry decision is the same.
    • ThrowTerminatingError($_) with Graph's own record keeps the status code and response that the caller reads.
  • No throw left: a search of Public and Private finds throw only in comments and in the rule text of Find-IslExitCodeIssue.
  • Module.WhatIf.Tests.ps1's AST pin test passes: the three new SupportsShouldProcess helpers are only ever called with @script:IslInternal.
  • Module.ErrorFlow.Tests.ps1: passes 5/5.
  • The new tests for the file and zip helpers: Write-IslTextFile (4/4) and Compress-IslFolder (2/2) pass. That includes an empty -Line, which you guard against unrolling with the [string[]]$text = @() assignment, and forward-slash entry names.

Unverified: CI on this branch. Its base isn't main, so there are no checks, and the description gives no run ID.

Useful lessons in the notes:

  • A .DESCRIPTION line that starts with .NET silently kills Get-Help.
  • The Copy-Item claim was measured and corrected.

Both are worth a line in CLAUDE.md for the rest of #65.

@fadwen

fadwen commented Nov 24, 2026

Copy link
Copy Markdown
Owner Author

Both points are addressed.

…n failure

Write-IslTextFile, Copy-IslSharedFile and Compress-IslFolder declared
SupportsShouldProcess and asked ShouldProcess themselves, which
CLAUDE.md reserves for the commands that run a script or write a
report. Export-IntuneAgentDiagnostic asks for the whole package before
it calls them, so they no longer ask, and their calls lose the
-WhatIf:$false -Confirm:$false splat that pinned them.

The three helpers made .NET calls that can fail outside any try. They
now end with ThrowTerminatingError, so the error-flow contract test
counts them as able to fail and checks their callers.

Get-IslRegistryText read the key itself without -ErrorAction, so a key
that exists but denies reading wrote an access error, where its help
says such a key is passed over.
@fadwen-ai

fadwen-ai commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

6c636f0 addresses three findings of a review of the diagnostic export helpers. It is merged into #102, #103 and #104.

  • ShouldProcess: Write-IslTextFile, Copy-IslSharedFile and Compress-IslFolder no longer declare SupportsShouldProcess. CLAUDE.md limits ShouldProcess to the commands that run a script or write a report, and Export-IntuneAgentDiagnostic has asked for the whole package before it calls them. Their calls lose the @script:IslInternal splat, which only pins a command that asks. The tests that previewed each helper with -WhatIf now set $WhatIfPreference inside the module and check that the helper still writes, which is the case Under a WhatIf preference the harness skips its preparation and still starts the host #88 was about.
  • Errors: the three helpers do their work inside try and end with $PSCmdlet.ThrowTerminatingError($_), so Module.ErrorFlow.Tests.ps1 counts them as able to fail and holds every caller to a try with a catch. All their calls are inside the one try of Export-IntuneAgentDiagnostic. New tests cover a file that cannot be written, a source that is not there, and an archive that is there already.
  • Registry key that cannot be read: Get-IslRegistryText reads the key itself with -ErrorAction SilentlyContinue, as its help says and as it already read the subkeys. A new test makes a key in Pester's test registry that the current user may not read, checks that the function writes no error, and restores the key's ACL. It fails on the code before the change, with the access error.

🤖 Generated with Claude Code

Base automatically changed from refactor/helpers-small to main November 25, 2026 01:56
Comment thread Private/Get-IslRegistryText.ps1 Outdated
$values = Get-ItemProperty -LiteralPath $item.PSPath -ErrorAction SilentlyContinue
if (-not $values) { continue }
foreach ($property in $values.PSObject.Properties) {
if ($property.Name -like 'PS*') { continue }

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Pre-existing (not from this change, not blocking): -like 'PS*' drops every registry value whose name starts with PS, not only the provider's own PSPath, PSParentPath, PSChildName, PSDrive and PSProvider that the help says are left out. A real value such as PSVersion or PSScriptPolicy under the agent's keys never reaches the diagnostic package, and nothing says it was dropped. Fix: skip the five provider names explicitly, for example if ($property.Name -in 'PSPath', 'PSParentPath', 'PSChildName', 'PSDrive', 'PSProvider') { continue }.

🤖 Generated with Claude Code

$index += 2
continue
}
if ('()[]{}.*+?|^$'.IndexOf($character) -ge 0) { break }

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Pre-existing (not from this change, not blocking): the help now states that a matching message must contain the returned text, but a pattern with a top-level alternation breaks that. For abc|def the loop stops at | and returns abc, yet def matches without containing it; with three or more characters this becomes the event's Needle, which Get-IntuneAgentLog -EventName uses to prefilter lines, so those events would be skipped. No pattern in the table has a top-level | today. Fix: return an empty string when the pattern has an unescaped | outside any group or class, or document the restriction in the help and the table.

🤖 Generated with Claude Code

Comment thread Private/Copy-IslSharedFile.ps1 Outdated
$in = $null
$out = $null
try {
$in = [System.IO.File]::Open($Source, 'Open', 'Read', 'ReadWrite')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Pre-existing (not from this change, not blocking): one log that cannot be opened ends the whole diagnostic package. The share mode ReadWrite leaves out Delete, so a writer that holds its file with delete access (rename-based rotation) causes a sharing violation, and a log rotated or removed between the Get-ChildItem in Export-IntuneAgentDiagnostic and this copy fails with FileNotFound; either way the caller's catch ends the command without a zip. Fix: open with [System.IO.FileShare]'ReadWrite, Delete', and consider having the caller report a log it could not copy with a warning and a manifest line instead of failing the package.

🤖 Generated with Claude Code

$archive = [System.IO.Compression.ZipFile]::Open($Destination, 'Create')
foreach ($file in $files) {
$relative = $file.FullName.Substring($Folder.Length).TrimStart('\', '/') -replace '\\', '/'
$null = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Pre-existing (not from this change, not blocking): when CreateEntryFromFile fails part-way (a file locked or removed in the staging folder, a full disk), the finally disposes the archive and leaves a valid but incomplete zip at Destination. Export-IntuneAgentDiagnostic has already removed the previous package under -Force and then ends with an error, so the path holds a zip that opens and looks like a package. Fix: in the catch, remove Destination when this function created it (dispose first), and say in the help that a failure leaves no archive.

🤖 Generated with Claude Code

Comment thread Private/Get-IslGraphRetryDelay.ps1 Outdated
if ($status -notin 429, 503, 504) { return }

$delay = 0
$retryAfter = if ($response) { $response.Headers.RetryAfter } else { $null }

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Pre-existing (not from this change, not blocking): $response.Headers.RetryAfter assumes an HttpResponseMessage. If the exception carries a Response of another shape, for example the HttpWebResponse of a WebException, whose WebHeaderCollection has no RetryAfter member, strict mode raises a property-not-found error inside the caller's catch, and Invoke-IslGraphRequestOnce ends with that error instead of Graph's own. Fix: read Headers and RetryAfter through Get-IslPropertyValue (or check PSObject.Properties first) and fall back to the exponential delay.

🤖 Generated with Claude Code

continue
}
if ($character -eq '[') { $inClass = $true }
$opensCapture = $character -eq '(' -and ($index + 1 -ge $Pattern.Length -or $Pattern[$index + 1] -ne '?')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Pre-existing (not from this change, not blocking): after renaming, a numbered backreference in a pattern (\1, \k<1>) no longer points at that pattern's own group. In the combined alternation every group is named, and .NET numbers named groups after all others in the whole expression, so \1 in the fifth pattern refers to the first named group of the combined regex. No pattern in the table uses a backreference today, and the help does not say this. Fix: rewrite \<n> to \k<prefix<n>> while renaming, or state in the help that patterns must not use numbered backreferences.

🤖 Generated with Claude Code

Comment thread Private/Get-IslRegistryText.ps1 Outdated
HKLM:\SOFTWARE\Microsoft\IntuneManagementExtension.

.PARAMETER Depth
How many levels of subkeys below the key are included.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (optional): the help says Depth is how many levels of subkeys are included, but Get-ChildItem -Recurse -Depth 0 already returns the immediate subkeys, so Depth N gives N+1 levels; the test 'goes down as many levels as asked' confirms Depth 0 yields the key and its child. DOC-05 in .github/copilot-instructions.md: "Help MUST describe what the code does." Fix: describe it as the number of levels below the immediate subkeys, or pass -Depth ($Depth - 1) and keep the wording.

🤖 Generated with Claude Code

Comment thread Private/Get-IslGraphRetryDelay.ps1 Outdated
$retryAfter = if ($response) { $response.Headers.RetryAfter } else { $null }
if ($retryAfter) {
if ($null -ne $retryAfter.Delta) { $delay = [Math]::Ceiling($retryAfter.Delta.TotalSeconds) }
elseif ($null -ne $retryAfter.Date) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (optional): elseif starts its own line after the closing brace of the if, and the same in Private/Get-IslRegistryText.ps1 line 55, where else starts the line after { "byte[...]" }. These are new files, so the rule applies to them. STY-02 in .github/copilot-instructions.md: "else, elseif, catch, and finally follow that closing brace on the same line." Fix: move elseif/else onto the line of the preceding } and break the blocks over lines.

🤖 Generated with Claude Code

A review of the helpers moved out of Export-IntuneAgentDiagnostic,
Get-IslAgentLogEvent and Invoke-IslGraphRequest found older bugs that
the moved code carried along.

- Get-IslRegistryText dropped every value whose name starts with PS.
  It now leaves out only the five provider properties. Its help also
  says what -Depth counts: N gives N + 1 levels of subkeys.
- Copy-IslSharedFile shared the source for reading and writing only,
  so a writer holding a log with delete access kept it out, and a log
  could not be renamed while it was copied. It shares Delete as well,
  and removes a part copy when the copy fails.
- Export-IntuneAgentDiagnostic ended with no package when one log
  could not be copied. Following ERR-13, it reports that log with
  WriteError, names it in the manifest, and writes the rest;
  -ErrorAction Stop still ends it there.
- Compress-IslFolder left a valid but incomplete zip at the
  destination when it failed part way. It removes the archive it
  created; one that was there before is left alone.
- Get-IslRegexLiteralPrefix gave the first alternative's text for a
  pattern with a top-level |, so the needle of Get-IntuneAgentLog
  -EventName would have skipped lines of the other alternatives. Such
  a pattern now gives an empty string.
- ConvertTo-IslNamedGroupPattern left \1 and \k<1> as they were, and
  in the joined expression they named another pattern's group. They
  now name the pattern's own renamed group.
- Get-IslGraphRetryDelay read Headers.RetryAfter with member syntax,
  which under strict mode wrote an error for a response without that
  member and ended the request under -ErrorAction Stop. It reads the
  members by name and falls back to the doubling delay.
- STY-02: elseif and else follow the closing brace in the new files.
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.

2 participants