Repository navigation
Conversation
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
left a comment
There was a problem hiding this comment.
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' } |
There was a problem hiding this comment.
-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 |
There was a problem hiding this comment.
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($_) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
-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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 = @{} |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 } |
There was a problem hiding this comment.
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.
Summary
The runtime harness is the second area of #64. The five
Invoke-Intune*Testcommands and the private functions they launch scripts through ended on a failure withthrow. A caller's-ErrorAction SilentlyContinuesuppresses athrowand 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 atrywith acatch.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
tryand 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
throw.Get-IslHostPath(HostArchitectureUnavailable,HostNotFound),Grant-IslFolderAccess(FolderAccessNotGranted),Invoke-IslProcess(ProcessStartFailed,ScheduledTaskNotRegistered,ScheduledTaskNotStarted), the-Credentialwith-Context Systemcheck of all five commands (CredentialWithSystemContext) and the argument checks ofInvoke-IntuneWin32AppTest(DetectionMissing,IntentCommandMissing,RelatedAppNameMissing,RelatedAppDetectionMissing). The messages are unchanged.Get-IslOemEncodingused athrowto jump to its owncatch; it is anifnow.Invoke-IntuneDetectionTest,Invoke-IntuneRequirementTestandInvoke-IntunePlatformScriptTesttake 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 Stopends the command there.Invoke-IntuneRemediationTestandInvoke-IntuneWin32AppTestrun several steps that depend on each other, so their flow is onetryand a step that cannot be run ends the command. The two nested functions ofInvoke-IntuneWin32AppTesthave nocatchof their own and rely on thattry. 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.Invoke-IslScriptRunthe run folder, the copy of the script, the folder access and the launch are onetry, andNew-ItemandCopy-Itemhave-ErrorAction Stop.Invoke-ContentCommandinInvoke-IntuneWin32AppTestdoes the same for the content folder. Thefinallythat removes the run folder now covers a failed copy as well.Invoke-IslProcessends with the error of aStop-IslProcessTreethat 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, runstaskkill.exeandicacls.exeas a process whose streams .NET redirects and returns the exit code and both texts.Stop-IslProcessTreehad that code inline.Grant-IslFolderAccesscalledicacls.exewith 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 atrycovers everything called below it. The list of calls that still rely on athrowgoes from 46 to 33, and the list of calls to a function that ends quietly is empty with no exception.Should-Throw -FullyQualifiedErrorId. New cases: two scripts through the pipeline with the first one failing, under-ErrorAction ContinueandStop, 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 inTests/Integration/RuntimeHarness.Tests.ps1that run a calling script withouttryin a new process against real launches.Tests/Unit/Private/Invoke-IslNativeCommand.Tests.ps1is new.docs/IntuneScriptLab/with the rebuilten-US/IntuneScriptLab-Help.xml, and two paragraphs inCLAUDE.md.Verification
./Tests/Invoke-Tests.ps1 -CodeCoverageon PowerShell 7.6.10: 1,132 passed, 7 skipped, 95.46 percent coverage. 3 failed, the three that fail on this computer onmainas 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.ps1on 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 ofInvoke-IslProcessand to the layout of two functions; the files those touch, 33 tests, passed on both versions afterwards.NT AUTHORITY\SYSTEMunder 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. NoIntuneScriptLab-*task and no run folder was left. The tree on the device was the one before the same last change.-ErrorAction Stopon the copy, the test with the script held open fails ("Expected an exception"), and without-ErrorAction Stopon the detection inside the Win32 flow, the uninstall case fails (no result: False).Invoke-ScriptAnalyzer -Path . -Recurse -Severity Error, Warning -ExcludeRule PSAvoidLongLines: 0 findings.PublicandPrivate: 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.ymlon the last commit, 8a4dc4a: run 45301781578 passed all five jobs.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.FolderAccessNotGranted; the tests ofGrant-IslFolderAccessandInvoke-IslScriptRunpassed on both versions afterwards.Notes
main. The next areas of Advanced functions end with throw instead of ThrowTerminatingError (ERR-10, ERR-11, ERR-14) #64, the tenant commands and then the analysis and rule commands, will be stacked on this branch.beginwould make it one terminating error; the unit tests mock the launch with architectures the test computer may not have, so that is left as it is.throwstatements in nested functions without[CmdletBinding()]stay until Nested helper functions have no CmdletBinding, help or parameter types (FUN-01, DOC-01, FUN-20, MOD-01) #65 gives those functions a$PSCmdlet.