Skip to content

fix(module): run under strict mode and fail the import on a load error - #84

Merged
fadwen merged 3 commits into
mainfrom
fix/strict-mode-root-module
Nov 23, 2026
Merged

fadwen merged 3 commits into
mainfrom
fix/strict-mode-root-module

Conversation

@fadwen

@fadwen fadwen commented Nov 23, 2026

Copy link
Copy Markdown
Owner

Summary

The root module set no strict mode, and its loader carried on when a function file failed to load: a file that did not parse wrote an error and the module still imported, without the commands of that file. ai-powershell-standards 2.0.0 requires strict mode in the root module (ERR-02), code that runs without errors under it (ERR-03), and an import that fails when a file fails to load (MOD-05). This change sets strict mode, replaces the loader, and fixes every read the suites then reported. Closes #63.

This pull request is stacked on #82 (ci/line-endings) and merges after it.

Changes

  • IntuneScriptLab.psm1 sets Set-StrictMode -Version Latest and loads Private, Private/Rules and Public in one loop that builds each path with Join-Path, fails on a missing folder and rethrows when a file fails to load.
  • New private function Get-IslPropertyValue: returns a named value from a dictionary or an object, and nothing for a missing input, key or property. It is the one accessor for data with optional members (FUN-26).
  • Graph replies are read through the accessor in Test-IntuneDeployedScript, Compare-IntuneDeployedScript, Get-IntuneScriptHealth, Get-IslExportReport and Invoke-IslGraphRequest. So are the result of a CIM method in Get-IslLogonSession and the two shapes of finding that Export-IntuneFindingSarif takes.
  • Hashtables that the module's caller writes are read with an index, which gives $null for a key that is not there: the settings table in Get-IslSetting, the directive in Get-IslScriptContext, a rule in ConvertFrom-IslRuleSpec, and the -DependsOn and -Supersedes entries of Invoke-IntuneWin32AppTest.
  • Find-IslModuleDependency no longer reads the required modules of a script that has no #Requires line, and the event table of Get-IslAgentLogEvent is assigned before its first read.
  • Tests: fakes of a run result go through the new ConvertTo-FakeRunResult helper, which gives them every member the real result has. The Graph mock of the health tests no longer answers a run summary URI with two objects. Module.Contract.Tests.ps1 checks that the module's functions run under strict mode and that the import fails for a file that throws, a file that does not parse, and a missing Private\Rules or Public folder. Get-IslPropertyValue.Tests.ps1 covers the accessor against a hashtable, an ordered dictionary and an object.
  • CLAUDE.md records the invariant, and CHANGELOG.md has the two entries under Changed.

Verification

  • ./Tests/Invoke-Tests.ps1 -CodeCoverage on PowerShell 7.6.10, shuffled: 1,062 passed, 3 failed, 8 skipped, coverage 95.19 percent. The three failures are the ones that fail on that computer before this change and pass in CI: two because its code pages are 65001 (Repair-IntuneScript corrupts an ANSI script on a host with a UTF-8 system code page #75), one because its Windows build has a module the in-box table lacks (In-box module table does not list UOPProviders, present on Windows 11 26H2 #76).

  • powershell -NoProfile -File ./Tests/Invoke-Tests.ps1 -TestType Unit on Windows PowerShell 5.1.26100, shuffled: 979 passed, 2 failed, 38 skipped. The two failures are Repair-IntuneScript corrupts an ANSI script on a host with a UTF-8 system code page #75 and In-box module table does not list UOPProviders, present on Windows 11 26H2 #76 again. The integration suites on 5.1: 47 passed, 1 failed (Repair-IntuneScript corrupts an ANSI script on a host with a UTF-8 system code page #75), 6 skipped.

  • Invoke-ScriptAnalyzer with -Severity Error, Warning -ExcludeRule PSAvoidLongLines, and with -Settings ScriptSecurity, on the 26 changed script files: no findings. Test-StandardsCompliance.ps1 of ai-powershell-standards 2.0.0 reports no finding in the two new files, and no file has more findings than before.

  • ./Build/Publish-Module.ps1 -WhatIf: the staged module imports in a new process, exports the declared commands and serves its help; nothing was published.

  • quality-gates.yml, dispatched on this branch because it triggers only for pull requests into main: all five jobs passed (run 45137082728).

  • Against a tenant, read-only, on PowerShell 7.6.10: Test-IntuneDeployedScript, Compare-IntuneDeployedScript and Get-IntuneScriptHealth return the same output from the base branch and from this one, byte for byte as JSON: 1,027 findings, 183 drift results and 151 health reports.

  • On a lab device, as NT AUTHORITY\SYSTEM under Windows PowerShell 5.1.26100.9818, every suite of this branch: 1,022 passed, 0 failed, 51 skipped. The user-context suite ran there with the harness account, which no hosted runner does. Of the skipped, 47 are tests that need PowerShell 7 or PSScriptAnalyzer, which the device does not have.

  • The other four skipped tests are skipped on every machine, by a defect in their skip condition that this change does not touch (Four tests never run: their -Skip condition reads a variable that BeforeAll sets after discovery #83). Three of them are the SYSTEM-context suite, so a copy of that file with the condition evaluated at discovery was run on the same device against this branch: 3 passed. They launch a script through a scheduled task as SYSTEM, time one out and remove the task.

  • Not verified: the tenant comparison under Windows PowerShell 5.1, because Microsoft.Graph.Authentication is not installed for it on the computer that ran the checks. Get-IntuneScriptHealth was run with -SkipRunState for Win32 apps, because their install counts come from an export job, which is a write to the tenant; Get-IslExportReport is covered by its unit tests only.

Notes

The root module set no strict mode, so a read of a member that was not
there gave $null with no error anywhere in the module. Its loader
dot-sourced each file without a try and read the folders with
-ErrorAction SilentlyContinue: a file that did not parse wrote an error
and the module still imported, without the commands of that file, and
a missing Private or Public folder was not an error at all.

The root module now sets Set-StrictMode -Version Latest and loads
Private, Private/Rules and Public in one loop that fails on a missing
folder and rethrows when a file fails to load.

With strict mode on, 415 of the 998 unit tests failed, for a small
number of causes, all of them reads of a member that is optional:

- Hashtables that the module's caller writes (a settings table, a
  directive, a detection rule, a -DependsOn entry) are read with an
  index, which gives $null for a key that is not there.
- Data from outside is read through Get-IslPropertyValue, a new
  private accessor that returns nothing for a missing input, key or
  property and takes a dictionary and an object alike: Graph replies in
  Test-IntuneDeployedScript, Compare-IntuneDeployedScript,
  Get-IntuneScriptHealth, Get-IslExportReport and
  Invoke-IslGraphRequest, the result of a CIM method in
  Get-IslLogonSession, and the two shapes of finding that
  Export-IntuneFindingSarif takes.
- Find-IslModuleDependency no longer reads the required modules of a
  script that has no #Requires line, and the event table of
  Get-IslAgentLogEvent is assigned before its first read.

The tests needed three kinds of change. Fakes of a run result named
only the members their test was about; they go through
ConvertTo-FakeRunResult, which adds the rest. The Graph mock of the
health tests matched a run summary URI with two patterns and returned
two objects, which member enumeration had hidden. Test code inside
InModuleScope runs under the module's strict mode and reads no
variable that was never set.

Tests/Invoke-Tests.ps1 still turns strict mode off around the Pester
run, for the suites and the validation kit. The module no longer
depends on that.

Refs #63

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

Comment thread IntuneScriptLab.psm1
try {
Write-Verbose "Loading $($functionFile.FullName)"
. $functionFile.FullName
} 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 catch that only rethrows is what makes a file that does not parse fail the import. Dot-sourcing such a file raises an error that ends only that statement, so without the try the loop went on and the module imported without the commands of the file. Rethrown from catch, the error ends the root module. Module.Contract.Tests.ps1 imports a copy with such a file in a new process and checks that the module is not loaded afterwards.

if ($Table.MinimumSeverity -and "$($Table.MinimumSeverity)" -notin $validSeverities) {
# Every key is optional. An index reads a key that is not there as $null, where member
# access is an error under strict mode
$minimumSeverity = $Table['MinimumSeverity']

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 index here, not Get-IslPropertyValue: $Table is typed [hashtable], so the question of dictionary or object does not arise, and an index reads a key that is not there as $null. The accessor is for data whose shape the module does not control.

'detectionScriptPending'
'detectionScriptNotApplicable'
)
foreach ($counter in $counters) {

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.

Eight reads of the same shape, so they are made in one loop. [int] of a value that is not there is 0 on PowerShell 7 and on Windows PowerShell 5.1, which is what [int]$run.noIssueDetectedDeviceCount gave before for a summary that was absent or lacked the counter.

$tenant.runSummaries[$Matches[1]]
}
'^/beta/deviceManagement/deviceHealthScripts/([^?/]+)' {
'^/beta/deviceManagement/deviceHealthScripts/([^?/]+)(\?|$)' {

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 the end of the pattern this clause also matched a .../runSummary address, and switch -Regex runs every clause that matches, so the mock answered a run summary request with two objects: the summary and the policy. The command read the counters from that pair by member enumeration, which took them from the element that had them. Read through the accessor, the pair has no counters, so three tests failed until the mock returned one object, as Graph does.

Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'detect' } {
if (Test-Path (Join-Path (Split-Path $Path -Parent) 'fixed.marker')) {
[pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'present'; StdErr = '' }
ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'present'; StdErr = '' }

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 commands these fakes feed are unchanged. A real run result always has RunAs, Host, ScriptPath and Duration; the fakes did not, and the commands' reads of them were a silent $null until strict mode made them errors. Completing the fake keeps the commands free of guards against a shape they never receive. The helper can be called here because a mock body runs in the scope of the test file, not in the module's.

if ($null -ne $Settings) { $parameters.Settings = $Settings }
# Settings is always passed, as $null when the test gives none: the block below runs under
# the module's strict mode, where a variable that was never set cannot be read
$parameters = @{ Path = (Join-Path $script:Tree $Relative); Cache = $Cache; 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.

The block passed to InModuleScope runs under the module's strict mode. $Settings existed in it only when the test gave settings, so the $null -ne $Settings below read a variable that had never been set.

Comment thread Tests/Invoke-Tests.ps1
# written for strict mode (#63, #70, #71), so it is off for the run and on again after it.
# mode. The module sets its own in its root module and does not depend on this one, but the
# suites and the validation kit are not yet written for strict mode (#70, #71), so it is off for
# the run and on again after it.

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 toggle stays for now. The module is strict-clean and sets its own mode, but the test files and the validation kit would inherit this script's strict mode and are not written for it yet (#70, #71).

@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. One should-fix (small), and nits.

Reviewed against ai-powershell-standards (ERR-02, ERR-03, MOD-05, FUN-26). Checked in a Linux sandbox with pwsh 7.6.0 and Pester 6.2.0.

Verified

  • No regressions (differential run): I ran the full unit suites (Tests/Unit and Validation/Tests/Unit, shuffle seed 12345) on #82 and on this branch.
    • The set of failures is identical: 135 tests, all Linux-only (HKLM, icacls, CIM, Windows hosts).
    • This branch has 21 more passing tests (849 → 870): the new tests in Module.Contract and Get-IslPropertyValue.Tests.ps1, all passing.
  • IntuneScriptLab.psm1: sets strict mode at the top and loads the folders with -LiteralPath. A missing folder throws, and a load failure is rethrown. The try { . $file } catch { throw } is needed: without it, a statement-terminating error in a module script lets the import go on.
  • Get-IslPropertyValue: returns nothing for $null, for a missing key and for a missing property. It works with a Hashtable, an ordered dictionary and a PSCustomObject, and is case-insensitive for Hashtables and objects, as member access was.
  • Script content: the policies' script content is a base64 string, so the accessor unrolling its output doesn't touch it (Test-PolicyScript takes [string]$Content).
  • Lists: every list read I found goes through @(...): assignments, value, detectionRules, requirementRules.

Unverified (needs Windows, a tenant or a lab device): the tenant output being byte-identical, the run as SYSTEM on the lab device, and CI run 45137082728. This PR has no checks because its base isn't main.

Should-fix: Private/Get-IslPropertyValue.ps1 line 55, $InputObject.Contains($Name)

  • On a generic Dictionary[string,object] this throws "Cannot find an overload for Contains". That type implements IDictionary.Contains explicitly, so PowerShell doesn't bind it. Reproduced.
  • Nothing passes such a dictionary today: Graph replies are Hashtables, and JSON gives ordered hashtables or objects. But the help says the function takes any dictionary.
  • Fix: ([System.Collections.IDictionary]$InputObject).Contains($Name), plus one test case.

Nits

  • Loader: a one-line comment on the try/catch saying why it's there would stop someone from removing it as dead code.
  • Accessor output: it unrolls a collection on the way out (documented). A future caller that reads a byte[] or a one-element array without @() gets object[] or a scalar. Write-Output -NoEnumerate would remove that trap, if no caller relies on the unrolling.

Get-IslPropertyValue called Contains on the dictionary itself. A
generic Dictionary[string, object] implements that method of
IDictionary explicitly, so PowerShell does not find it there and the
call failed with "Cannot find an overload for Contains" for a key that
is present and for one that is not. Nothing passes such a dictionary
today, but the help says the function takes any dictionary. The method
is now called through the interface, and a test covers the type.

The catch in the root module's loader gets a comment that says why it
only rethrows, so that it is not removed as dead code.

Refs #63
@fadwen

fadwen commented Nov 23, 2026

Copy link
Copy Markdown
Owner Author

The should-fix and the first nit are addressed in 35fd3e7. The second nit is not taken, for the reason below.

$InputObject.Contains($Name) on a generic dictionary: fixed.

  • Reproduced on PowerShell 7.6.10 and on Windows PowerShell 5.1: with a Dictionary[string, object] the accessor failed with Cannot find an overload for "Contains", for a key that is present and for one that is not.
  • The method is now called through the interface, ([System.Collections.IDictionary]$InputObject).Contains($Name).
  • Get-IslPropertyValue.Tests.ps1 has the case: a present key, a value of 0 and a missing key on a Dictionary[string, object].

Comment on the loader's try/catch: added. It says that the catch is not dead code and what it is there for.

Write-Output -NoEnumerate in the accessor: not changed. The callers rely on the unrolling.

  • Every list read is written @(Get-IslPropertyValue ...). With -NoEnumerate, @() around the call gives an array of one element, which is the list (the note on STY-42 describes this), so all of those call sites would have to change with it.
  • Four call sites pipe the result straight into Where-Object, in Compare-IntuneDeployedScript, Get-IntuneScriptHealth and Test-IntuneDeployedScript, which needs the elements.
  • The trap for a future caller is real, and the function's help states it: wrap the call in @() where the value is a list.

The checks that could not be made in the sandbox

  • CI on this branch after the commit: run 45151983245 passed all five jobs.
  • The run on the lab device and the tenant comparison were made before this commit. The commit changes the accessor only for a type that no caller passes; the accessor's tests and the suites of the commands that read Graph replies pass on both PowerShell versions (60 of 60).

Base automatically changed from ci/line-endings to main November 23, 2026 10:11
@fadwen
fadwen merged commit 6252f02 into main Nov 23, 2026
5 checks passed
@fadwen
fadwen deleted the fix/strict-mode-root-module branch November 23, 2026 10:12
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.

Root module does not set strict mode or fail the import on a load error (ERR-02, ERR-03, MOD-05)

1 participant