From 71d8c00af2e6a14167fb0e3cf326929966ce79a9 Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:51:59 -0800 Subject: [PATCH 1/3] fix(harness)!: raise run failures as terminating errors with IDs 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. --- CHANGELOG.md | 26 ++ CLAUDE.md | 20 +- Private/Get-IslHostPath.ps1 | 36 +- Private/Get-IslOemEncoding.ps1 | 10 +- Private/Grant-IslFolderAccess.ps1 | 23 +- Private/Invoke-IslNativeCommand.ps1 | 75 ++++ Private/Invoke-IslProcess.ps1 | 73 +++- Private/Invoke-IslScriptRun.ps1 | 22 +- Private/Stop-IslProcessTree.ps1 | 35 +- Public/Invoke-IntuneDetectionTest.ps1 | 60 ++-- Public/Invoke-IntunePlatformScriptTest.ps1 | 18 +- Public/Invoke-IntuneRemediationTest.ps1 | 74 ++-- Public/Invoke-IntuneRequirementTest.ps1 | 18 +- Public/Invoke-IntuneWin32AppTest.ps1 | 333 ++++++++++-------- README.md | 2 +- Tests/Integration/RuntimeHarness.Tests.ps1 | 63 +++- Tests/Unit/Module.ErrorFlow.Tests.ps1 | 52 +-- Tests/Unit/Private/Get-IslHostPath.Tests.ps1 | 9 + .../Private/Grant-IslFolderAccess.Tests.ps1 | 1 + .../Private/Invoke-IslNativeCommand.Tests.ps1 | 71 ++++ .../Unit/Private/Invoke-IslProcess.Tests.ps1 | 34 ++ .../Private/Invoke-IslScriptRun.Tests.ps1 | 14 + .../Invoke-IntuneDetectionTest.Tests.ps1 | 40 ++- .../Invoke-IntunePlatformScriptTest.Tests.ps1 | 29 +- .../Invoke-IntuneRemediationTest.Tests.ps1 | 15 +- .../Invoke-IntuneRequirementTest.Tests.ps1 | 42 +++ .../Invoke-IntuneWin32AppTest.Tests.ps1 | 56 ++- .../Invoke-IntuneDetectionTest.md | 5 + .../Invoke-IntunePlatformScriptTest.md | 5 + .../Invoke-IntuneRemediationTest.md | 5 + .../Invoke-IntuneRequirementTest.md | 5 + .../Invoke-IntuneWin32AppTest.md | 6 + en-US/IntuneScriptLab-Help.xml | 36 +- 33 files changed, 1006 insertions(+), 307 deletions(-) create mode 100644 Private/Invoke-IslNativeCommand.ps1 create mode 100644 Tests/Unit/Private/Invoke-IslNativeCommand.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 33b2038..f0ddd15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -82,6 +82,24 @@ entries are carried over from the manifest's release notes. read the logs through it: the timelines are built from the logs that could be read, and the package is still written, with every log in it. `-ErrorAction Stop` ends the command at the first such error. +- The five `Invoke-Intune*Test` commands end on a failure with a terminating error raised the + way a compiled cmdlet raises one, where they used `throw`. The messages are the same, and each + failure the harness detects has an ID of its own in `FullyQualifiedErrorId`: + `CredentialWithSystemContext`, `HostArchitectureUnavailable`, `HostNotFound`, + `ProcessStartFailed`, `ScheduledTaskNotRegistered`, `ScheduledTaskNotStarted` and + `FolderAccessNotGranted`, and for the arguments of `Invoke-IntuneWin32AppTest` `DetectionMissing`, + `IntentCommandMissing`, `RelatedAppNameMissing` and `RelatedAppDetectionMissing`. **A script + that calls one of them without `try` and without `$ErrorActionPreference = 'Stop'` now goes on + at its next statement after the failure, where it used to end.** In return, + `-ErrorAction SilentlyContinue` on the call no longer lets the command carry on past its own + failure. +- `Invoke-IntuneDetectionTest`, `Invoke-IntuneRequirementTest` and `Invoke-IntunePlatformScriptTest` + report 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, as an error for that script, and go on with the next one from the + pipeline, where the first such script ended the command. `-ErrorAction Stop` ends the command at + that error. `Invoke-IntuneRemediationTest` and `Invoke-IntuneWin32AppTest` run one flow, and a + step of it that cannot be run ends the command: no result is returned, and the steps that would + have followed do not run. - The module's functions run under strict mode, set once in the root module. A read of a variable that was never assigned, or of a member that is not there, is an error where it was a silent `$null`. Graph replies, export rows and the other data with optional members are read through one @@ -102,6 +120,14 @@ entries are carried over from the manifest's release notes. - A test of `Get-IslAgentLogEvent` read the event table before anything had built it, so it failed whenever the shuffled order of the CI run put it first in its file. It builds the table first. +- Under PowerShell 7, a run whose script could not be copied to its run folder went on: the host + was started on a file that was not there, and its complaint came back as the result of the + script, with exit code -196608. The run now ends with the error of the copy, as it did under + Windows PowerShell 5.1, and so does an install or uninstall of `Invoke-IntuneWin32AppTest` whose + content folder cannot be copied. The run folder is removed in either case. +- A run that timed out and whose cleanup could not be run, because `taskkill.exe` could not be + started, returned a `TimedOut` result without output and left the process running. It now ends + with the error of the cleanup. - With `$WhatIfPreference` set in the caller's session, the runtime harness did neither a preview nor a run: it skipped copying the script, started the host on the file that was not there, and returned the host's complaint as the result of the script, with exit code -196608. A run through diff --git a/CLAUDE.md b/CLAUDE.md index 0461b08..6e64c90 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -63,9 +63,13 @@ declares it, the contract test expects it, and the command is still not exported The manifest declares `CompatiblePSEditions = Desktop, Core` and the root module carries `#Requires -Version 5.1`, because the agent runs scripts with 5.1 and so do the harness hosts. A ternary, `??`, `ForEach-Object -Parallel` or `Join-Path` with more than one child path parses on -7 and breaks every command on 5.1. Two 5.1 traps the suites already hit: `Group-Object` orders -groups differently (sort explicitly), and .NET Framework's `ZipFile::CreateFromDirectory` writes -backslash entry names (build zips entry by entry with forward slashes). +7 and breaks every command on 5.1. Three 5.1 traps the suites already hit: `Group-Object` orders +groups differently (sort explicitly), .NET Framework's `ZipFile::CreateFromDirectory` writes +backslash entry names (build zips entry by entry with forward slashes), and a line that a native +command writes to a redirected error stream becomes an error record, which ends the caller under +an error preference of `Stop`. `taskkill.exe` and `icacls.exe` therefore run through +`Invoke-IslNativeCommand`, which starts a process and reads its streams, and module code never +sets `$ErrorActionPreference` to get round it. The harness launches `powershell.exe` hosts by architecture, reads the registry and registers scheduled tasks, so the suites run on Windows only: the `desktop` job under 5.1 and the `arm64` @@ -116,7 +120,15 @@ function it calls is converted. `Tests/Unit/Module.ErrorFlow.Tests.ps1` holds the rule on the syntax trees, because behaviour does not show it: a caller that goes on with nothing often returns nothing too, and `Should-Throw` calls inside a `try`, where every error travels all the way up. The test lists the calls that still rely -on a `throw`, and the list must match the code exactly. `Invoke-CallerScript` in the test helpers +on a `throw`, and the list must match the code exactly. A `try` with a `catch` covers everything +called below it, so a nested function needs no `catch` of its own when every call of it is inside +one, as in `Invoke-IntuneWin32AppTest`; the test accepts that and nothing less. + +A command that takes several items reports one that fails with `$PSCmdlet.WriteError($_)` in that +`catch` and goes on with the next, and `-ErrorAction Stop` ends it there. A module function that +calls such a command and needs its result passes `-ErrorAction Stop`: without it the call returns +nothing and no error ends anything. In `Invoke-IntuneWin32AppTest` a detection that returned +nothing read as "detected". `Invoke-CallerScript` in the test helpers runs statements from a script without `try` in a new process, for what such a caller sees. A failure the module detects itself is raised with a record from `New-IslErrorRecord`, which gives diff --git a/Private/Get-IslHostPath.ps1 b/Private/Get-IslHostPath.ps1 index 10f1e85..66b64de 100644 --- a/Private/Get-IslHostPath.ps1 +++ b/Private/Get-IslHostPath.ps1 @@ -28,16 +28,31 @@ function Get-IslHostPath { } 'x64' { if ($osArchitecture -ne 'X64') { - throw ("No x64 PowerShell host on this $osArchitecture device. On Windows on ARM the 64-bit " + - "host " + - "is the native ARM64 one: use -Architecture arm64") + $message = ("No x64 PowerShell host on this $osArchitecture device. On Windows on ARM " + + 'the 64-bit host is the native ARM64 one: use -Architecture arm64') + $recordSplat = @{ + Message = $message + ErrorId = 'HostArchitectureUnavailable' + Category = [System.Management.Automation.ErrorCategory]::InvalidArgument + TargetObject = $Architecture + ExceptionType = [System.PlatformNotSupportedException] + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } $folder = 'System32' } 'arm64' { if ($osArchitecture -ne 'Arm64') { - throw ("This is an $osArchitecture device; there is no ARM64 PowerShell host here. Use " + - "-Architecture x64 (or x86)") + $message = ("This is an $osArchitecture device; there is no ARM64 PowerShell host " + + 'here. Use -Architecture x64 (or x86)') + $recordSplat = @{ + Message = $message + ErrorId = 'HostArchitectureUnavailable' + Category = [System.Management.Automation.ErrorCategory]::InvalidArgument + TargetObject = $Architecture + ExceptionType = [System.PlatformNotSupportedException] + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } $folder = 'System32' } @@ -47,7 +62,16 @@ function Get-IslHostPath { if ($folder -eq 'System32' -and -not [Environment]::Is64BitProcess -and $deviceIs64) { $folder = 'Sysnative' } $path = Join-Path -Path (Join-Path -Path $env:WINDIR -ChildPath $folder) -ChildPath $relative - if (-not (Test-Path -LiteralPath $path)) { throw "PowerShell host not found: $path" } + if (-not (Test-Path -LiteralPath $path)) { + $recordSplat = @{ + Message = "PowerShell host not found: $path" + ErrorId = 'HostNotFound' + Category = [System.Management.Automation.ErrorCategory]::ObjectNotFound + TargetObject = $path + ExceptionType = [System.IO.FileNotFoundException] + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) + } [pscustomobject]@{ PSTypeName = 'IntuneScriptLab.Host' diff --git a/Private/Get-IslOemEncoding.ps1 b/Private/Get-IslOemEncoding.ps1 index 9703db7..27a9e83 100644 --- a/Private/Get-IslOemEncoding.ps1 +++ b/Private/Get-IslOemEncoding.ps1 @@ -29,11 +29,13 @@ } catch { Write-Verbose "$valueName not readable from the registry, assuming $codePage" } - try { - if (-not ('System.Text.CodePagesEncodingProvider' -as [type])) { throw 'no provider type' } - [System.Text.Encoding]::RegisterProvider([System.Text.CodePagesEncodingProvider]::Instance) + # Windows PowerShell has the code pages built in and no provider type to register + if ('System.Text.CodePagesEncodingProvider' -as [type]) { + try { + [System.Text.Encoding]::RegisterProvider([System.Text.CodePagesEncodingProvider]::Instance) + } + catch { Write-Verbose "Code page provider not registered: $($_.Exception.Message)" } } - catch { Write-Verbose 'Code page provider not registered (Windows PowerShell has the code pages built in)' } try { [System.Text.Encoding]::GetEncoding($codePage) } catch { diff --git a/Private/Grant-IslFolderAccess.ps1 b/Private/Grant-IslFolderAccess.ps1 index e454d57..2eb7cc7 100644 --- a/Private/Grant-IslFolderAccess.ps1 +++ b/Private/Grant-IslFolderAccess.ps1 @@ -36,10 +36,23 @@ function Grant-IslFolderAccess { $trustee = if ($resolved) { "*$($resolved.Sid)" } else { $Account } # Windows PowerShell turns a native command's redirected stderr into error records, and under # a caller's -ErrorAction Stop the first one ends the function with icacls' bare line instead - # of the message below - $ErrorActionPreference = 'Continue' - $output = & icacls.exe $Path /grant "${trustee}:(OI)(CI)M" 2>&1 - if ($LASTEXITCODE -ne 0) { - throw "Could not grant $Account access to ${Path}: $($output -join ' ')" + # of the message below. Invoke-IslNativeCommand reads the streams without that + $icacls = Join-Path -Path ([System.Environment]::SystemDirectory) -ChildPath 'icacls.exe' + $arguments = '"{0}" /grant "{1}:(OI)(CI)M"' -f $Path, $trustee + try { + $result = Invoke-IslNativeCommand -FilePath $icacls -Arguments $arguments + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } + + if ($result.ExitCode -ne 0) { + $output = @($result.StdOut, $result.StdErr | Where-Object { $_ }) -join ' ' + $recordSplat = @{ + Message = "Could not grant $Account access to ${Path}: $output" + ErrorId = 'FolderAccessNotGranted' + Category = [System.Management.Automation.ErrorCategory]::PermissionDenied + TargetObject = $Path + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } } diff --git a/Private/Invoke-IslNativeCommand.ps1 b/Private/Invoke-IslNativeCommand.ps1 new file mode 100644 index 0000000..c81ab7c --- /dev/null +++ b/Private/Invoke-IslNativeCommand.ps1 @@ -0,0 +1,75 @@ +function Invoke-IslNativeCommand { + <# + .SYNOPSIS + Runs a Windows executable to its end and returns its exit code and what it wrote. + + .DESCRIPTION + For the small system tools the module calls for a side effect, such as taskkill.exe and + icacls.exe, whose error text is needed when they fail. The executable is started as a process + whose streams .NET redirects, not with the call operator: Windows PowerShell 5.1 turns a line + that a native command writes to a redirected error stream into an error record, and with an + error preference of Stop in the caller's scope the first such line ends the caller. + + The exit code is returned, not judged. What a code means differs from tool to tool, so the + caller decides. + + .PARAMETER FilePath + The full path of the executable. + + .PARAMETER Arguments + The arguments, as one string in the form the executable parses. An argument that can hold a + space is quoted by the caller. + + .EXAMPLE + $taskkill = Join-Path -Path ([System.Environment]::SystemDirectory) -ChildPath 'taskkill.exe' + $result = Invoke-IslNativeCommand -FilePath $taskkill -Arguments '/PID 4711 /T /F' + + Ends process 4711 and what it started. $result.ExitCode is 128 when there is no such process. + + .INPUTS + None. + + .OUTPUTS + IntuneScriptLab.NativeCommandResult. ExitCode, StdOut and StdErr. + #> + [CmdletBinding()] + [OutputType('IntuneScriptLab.NativeCommandResult')] + param( + [Parameter(Mandatory)] + [string]$FilePath, + + [Parameter()] + [string]$Arguments = '' + ) + + $startInfo = [System.Diagnostics.ProcessStartInfo]::new() + $startInfo.FileName = $FilePath + $startInfo.Arguments = $Arguments + $startInfo.UseShellExecute = $false + $startInfo.CreateNoWindow = $true + $startInfo.RedirectStandardOutput = $true + $startInfo.RedirectStandardError = $true + $process = [System.Diagnostics.Process]::new() + $process.StartInfo = $startInfo + try { + $null = $process.Start() + # Both streams are read while the process runs, so that neither fills and blocks it + $outputTask = $process.StandardOutput.ReadToEndAsync() + $errorTask = $process.StandardError.ReadToEndAsync() + $process.WaitForExit() + $exitCode = $process.ExitCode + $outputText = "$($outputTask.GetAwaiter().GetResult())".Trim() + $errorText = "$($errorTask.GetAwaiter().GetResult())".Trim() + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } finally { + $process.Dispose() + } + + [pscustomobject]@{ + PSTypeName = 'IntuneScriptLab.NativeCommandResult' + ExitCode = $exitCode + StdOut = $outputText + StdErr = $errorText + } +} diff --git a/Private/Invoke-IslProcess.ps1 b/Private/Invoke-IslProcess.ps1 index e9bf60f..acc6311 100644 --- a/Private/Invoke-IslProcess.ps1 +++ b/Private/Invoke-IslProcess.ps1 @@ -92,23 +92,43 @@ $process = [System.Diagnostics.Process]::new() $process.StartInfo = $startInfo - $null = $process.Start() - $process.StandardInput.Close() - $stdoutTask = $process.StandardOutput.ReadToEndAsync() - $stderrTask = $process.StandardError.ReadToEndAsync() - if (-not $process.WaitForExit($TimeoutSeconds * 1000)) { - $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 - Stop-IslProcessTree -ProcessId $process.Id -Confirm:$false -WhatIf:$false - $process.WaitForExit() + try { + $null = $process.Start() + } catch { + $process.Dispose() + $recordSplat = @{ + Message = "Could not start '$FilePath': $($_.Exception.GetBaseException().Message)" + ErrorId = 'ProcessStartFailed' + Category = [System.Management.Automation.ErrorCategory]::ResourceUnavailable + TargetObject = $FilePath + InnerException = $_.Exception + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) + } + + try { + $process.StandardInput.Close() + $stdoutTask = $process.StandardOutput.ReadToEndAsync() + $stderrTask = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit($TimeoutSeconds * 1000)) { + $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 + # error: the wait would not end either, and a TimedOut result would say that the + # tree is gone + Stop-IslProcessTree -ProcessId $process.Id -Confirm:$false -WhatIf:$false + $process.WaitForExit() + } + $stopwatch.Stop() + $stdout = $stdoutTask.GetAwaiter().GetResult() + $stderr = $stderrTask.GetAwaiter().GetResult() + $exitCode = $process.ExitCode + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } finally { + $process.Dispose() } - $stopwatch.Stop() - $stdout = $stdoutTask.GetAwaiter().GetResult() - $stderr = $stderrTask.GetAwaiter().GetResult() - $exitCode = $process.ExitCode - $process.Dispose() } else { $runId = Split-Path -Path $WorkFolder -Leaf @@ -182,7 +202,15 @@ $null = Register-ScheduledTask @registerTaskSplat } catch { - throw "${refusal}: $($_.Exception.Message)" + $recordSplat = @{ + Message = "${refusal}: $($_.Exception.Message)" + ErrorId = 'ScheduledTaskNotRegistered' + Category = [System.Management.Automation.ErrorCategory]::PermissionDenied + TargetObject = $userName + ExceptionType = [System.UnauthorizedAccessException] + InnerException = $_.Exception + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } try { Start-ScheduledTask -TaskName $taskName @@ -228,7 +256,13 @@ 'account holds a session)' } else { '' } - throw "The scheduled task for $userName did not start: $code$hint" + $recordSplat = @{ + Message = "The scheduled task for $userName did not start: $code$hint" + ErrorId = 'ScheduledTaskNotStarted' + Category = [System.Management.Automation.ErrorCategory]::InvalidOperation + TargetObject = $userName + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } if (-not (Test-Path -LiteralPath $exitFile)) { $timedOut = $true @@ -256,6 +290,9 @@ } 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 + $PSCmdlet.ThrowTerminatingError($_) } finally { # Of the task cmdlets used here only this one has -WhatIf. Under a preference the diff --git a/Private/Invoke-IslScriptRun.ps1 b/Private/Invoke-IslScriptRun.ps1 index d2aa5fc..293ba2d 100644 --- a/Private/Invoke-IslScriptRun.ps1 +++ b/Private/Invoke-IslScriptRun.ps1 @@ -51,8 +51,13 @@ function Invoke-IslScriptRun { [string]$WorkingDirectory = (Join-Path -Path $env:WINDIR -ChildPath 'System32') ) - $hostInfo = Get-IslHostPath -Architecture $Architecture - $source = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath + # No host for the architecture, or no script at the path: nothing has been started yet + try { + $hostInfo = Get-IslHostPath -Architecture $Architecture + $source = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } # Like IMECache: the script runs from a copy, so $PSScriptRoot is not the source folder $runId = [guid]::NewGuid().ToString('N') @@ -65,12 +70,12 @@ function Invoke-IslScriptRun { # The run folder and the copy are this function's own bookkeeping. The command that asked for # the run has had its -WhatIf and its -Confirm answered before it called; with a preference # still in effect here, the copy would be skipped and the host started on a file that is not - # there - $null = New-Item -ItemType Directory -Path $cache -Force @script:IslInternal + # there. For the same reason a copy that fails ends the function here: the catch below sees + # it only with -ErrorAction Stop $scriptCopy = Join-Path -Path $cache -ChildPath "$Phase.ps1" - Copy-Item -LiteralPath $source -Destination $scriptCopy @script:IslInternal - try { + $null = New-Item -ItemType Directory -Path $cache -Force -ErrorAction Stop @script:IslInternal + Copy-Item -LiteralPath $source -Destination $scriptCopy -ErrorAction Stop @script:IslInternal $processSplat = @{ FilePath = $hostInfo.Path Arguments = "-NoProfile -ExecutionPolicy Bypass -File `"$scriptCopy`"" @@ -85,8 +90,9 @@ function Invoke-IslScriptRun { $processSplat.LogonType = $LogonType } $run = Invoke-IslProcess @processSplat - } - finally { + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } finally { Remove-Item -LiteralPath $cache -Recurse -Force -ErrorAction SilentlyContinue @script:IslInternal } diff --git a/Private/Stop-IslProcessTree.ps1 b/Private/Stop-IslProcessTree.ps1 index 301ed93..69a9b7d 100644 --- a/Private/Stop-IslProcessTree.ps1 +++ b/Private/Stop-IslProcessTree.ps1 @@ -4,12 +4,12 @@ function Stop-IslProcessTree { Ends a process and every process it started. .DESCRIPTION - The cleanup after a run that timed out. taskkill.exe ends the tree, and it is started as a - process whose streams .NET redirects, not with the call operator: Windows PowerShell 5.1 - turns a line that a native command writes to a redirected error stream into an error record, - and with an error preference of Stop in the caller's scope that record ends the command. A - process that is already gone is such a line ("The process ... not found", exit code 128), and - it is the state the cleanup wants. + The cleanup after a run that timed out. taskkill.exe ends the tree, and it is run through + Invoke-IslNativeCommand, not with the call operator: Windows PowerShell 5.1 turns a line that + a native command writes to a redirected error stream into an error record, and with an error + preference of Stop in the caller's scope that record ends the command. A process that is + already gone is such a line ("The process ... not found", exit code 128), and it is the state + the cleanup wants. Nothing is reported when taskkill succeeds or finds no such process. When it fails for another reason and the process is still there, a warning says so, because then the run left @@ -46,29 +46,14 @@ function Stop-IslProcessTree { return } - $startInfo = [System.Diagnostics.ProcessStartInfo]::new() - $startInfo.FileName = Join-Path -Path ([System.Environment]::SystemDirectory) -ChildPath 'taskkill.exe' - $startInfo.Arguments = "/PID $ProcessId /T /F" - $startInfo.UseShellExecute = $false - $startInfo.CreateNoWindow = $true - $startInfo.RedirectStandardOutput = $true - $startInfo.RedirectStandardError = $true - $taskkill = [System.Diagnostics.Process]::new() - $taskkill.StartInfo = $startInfo + $taskkill = Join-Path -Path ([System.Environment]::SystemDirectory) -ChildPath 'taskkill.exe' try { - $null = $taskkill.Start() - # Both streams are read while the process runs, so that neither fills and blocks it - $outputTask = $taskkill.StandardOutput.ReadToEndAsync() - $errorTask = $taskkill.StandardError.ReadToEndAsync() - $taskkill.WaitForExit() - $exitCode = $taskkill.ExitCode - $null = $outputTask.GetAwaiter().GetResult() - $errorText = "$($errorTask.GetAwaiter().GetResult())".Trim() + $result = Invoke-IslNativeCommand -FilePath $taskkill -Arguments "/PID $ProcessId /T /F" } catch { $PSCmdlet.ThrowTerminatingError($_) - } finally { - $taskkill.Dispose() } + $exitCode = $result.ExitCode + $errorText = $result.StdErr Write-Verbose "taskkill.exe /PID $ProcessId /T /F ended with exit code $exitCode. $errorText" # 0 is success and 128 is "no such process". After any other answer the process itself decides: diff --git a/Public/Invoke-IntuneDetectionTest.ps1 b/Public/Invoke-IntuneDetectionTest.ps1 index 889bd3f..4c28be5 100644 --- a/Public/Invoke-IntuneDetectionTest.ps1 +++ b/Public/Invoke-IntuneDetectionTest.ps1 @@ -33,7 +33,14 @@ function Invoke-IntuneDetectionTest { process { if ($Credential -and $Context -eq 'System') { - throw '-Credential applies to -Context User; System runs as NT AUTHORITY\SYSTEM' + $recordSplat = @{ + Message = '-Credential applies to -Context User; System runs as NT AUTHORITY\SYSTEM' + ErrorId = 'CredentialWithSystemContext' + Category = [System.Management.Automation.ErrorCategory]::InvalidArgument + TargetObject = $Context + ExceptionType = [System.ArgumentException] + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } Write-Verbose "Starting $($MyInvocation.MyCommand.Name) for $($PSBoundParameters.Keys -join ', ')" # The agent's default host is the device's 64-bit one: arm64 on Windows on ARM, where no x64 @@ -49,27 +56,40 @@ function Invoke-IntuneDetectionTest { $reasons = [System.Collections.Generic.List[string]]::new() $signatureStatus = '' $run = $null - if ($EnforceSignatureCheck) { - # With the check on, AgentExecutor returns exit 1 for an unsigned script without running it: - # no probe record, "EnforceSignatureCheck: 1 ... applicationDetected: False" (W32-DET-SIGCHECK) - $signature = Get-AuthenticodeSignature -FilePath (Resolve-Path -LiteralPath $Path).ProviderPath - $signatureStatus = "$($signature.Status)" - if ($signature.Status -ne 'Valid') { - $reasons.Add("Signature status ${signatureStatus}: with the signature check enforced the agent " + - 'does not run the script and reports not detected (exit 1 from AgentExecutor)') + $scriptPath = $null + # 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 + # With the check on, AgentExecutor returns exit 1 for an unsigned script without running + # it: no probe record, "EnforceSignatureCheck: 1 ... applicationDetected: False" + # (W32-DET-SIGCHECK) + $signature = Get-AuthenticodeSignature -FilePath $scriptPath -ErrorAction Stop + $signatureStatus = "$($signature.Status)" + if ($signature.Status -ne 'Valid') { + $reasons.Add("Signature status ${signatureStatus}: with the signature check enforced " + + 'the agent does not run the script and reports not detected (exit 1 from ' + + 'AgentExecutor)') + } } - } - if ($reasons.Count -eq 0) { - $scriptRunSplat = @{ - Path = $Path - Architecture = $Architecture - Context = $Context - Phase = 'detect' - TimeoutSeconds = $TimeoutSeconds + if ($reasons.Count -eq 0) { + $scriptRunSplat = @{ + Path = $Path + Architecture = $Architecture + Context = $Context + Phase = 'detect' + TimeoutSeconds = $TimeoutSeconds + } + if ($Credential) { $scriptRunSplat.Credential = $Credential } + $run = Invoke-IslScriptRun @scriptRunSplat } - if ($Credential) { $scriptRunSplat.Credential = $Credential } - $run = Invoke-IslScriptRun @scriptRunSplat + } catch { + $PSCmdlet.WriteError($_) + return + } + + if ($null -ne $run) { $hasStdOut = -not [string]::IsNullOrWhiteSpace($run.StdOut) $hasStdErr = -not [string]::IsNullOrWhiteSpace($run.StdErr) @@ -102,7 +122,7 @@ function Invoke-IntuneDetectionTest { Context = $Context RunAs = if ($run) { $run.RunAs } else { '' } Host = if ($run) { $run.Host } else { '' } - ScriptPath = if ($run) { $run.ScriptPath } else { (Resolve-Path -LiteralPath $Path).ProviderPath } + ScriptPath = if ($run) { $run.ScriptPath } else { $scriptPath } } } } diff --git a/Public/Invoke-IntunePlatformScriptTest.ps1 b/Public/Invoke-IntunePlatformScriptTest.ps1 index 305e1ac..38ab6f1 100644 --- a/Public/Invoke-IntunePlatformScriptTest.ps1 +++ b/Public/Invoke-IntunePlatformScriptTest.ps1 @@ -40,7 +40,14 @@ function Invoke-IntunePlatformScriptTest { } if ($Credential) { if ($Context -eq 'System') { - throw '-Credential applies to -Context User; System runs as NT AUTHORITY\SYSTEM' + $recordSplat = @{ + Message = '-Credential applies to -Context User; System runs as NT AUTHORITY\SYSTEM' + ErrorId = 'CredentialWithSystemContext' + Category = [System.Management.Automation.ErrorCategory]::InvalidArgument + TargetObject = $Context + ExceptionType = [System.ArgumentException] + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } $scriptRunSplat.Credential = $Credential } @@ -50,7 +57,14 @@ function Invoke-IntunePlatformScriptTest { return } - $run = Invoke-IslScriptRun @scriptRunSplat + # A script that cannot be run is reported, and the next one from the pipeline still runs + try { + $run = Invoke-IslScriptRun @scriptRunSplat + } catch { + $PSCmdlet.WriteError($_) + return + } + $runState = if ($run.TimedOut) { 'TimedOut' } elseif ($run.ExitCode -eq 0) { 'Success' } else { 'Failed' } # What happens next under Intune, from the PS-FAIL experiments: a failed script is fetched and diff --git a/Public/Invoke-IntuneRemediationTest.ps1 b/Public/Invoke-IntuneRemediationTest.ps1 index 9692f1d..df582b5 100644 --- a/Public/Invoke-IntuneRemediationTest.ps1 +++ b/Public/Invoke-IntuneRemediationTest.ps1 @@ -39,7 +39,14 @@ function Invoke-IntuneRemediationTest { } if ($Credential) { if ($Context -eq 'System') { - throw '-Credential applies to -Context User; System runs as NT AUTHORITY\SYSTEM' + $recordSplat = @{ + Message = '-Credential applies to -Context User; System runs as NT AUTHORITY\SYSTEM' + ErrorId = 'CredentialWithSystemContext' + Category = [System.Management.Automation.ErrorCategory]::InvalidArgument + TargetObject = $Context + ExceptionType = [System.ArgumentException] + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } $scriptRunSplat.Credential = $Credential } @@ -54,44 +61,49 @@ function Invoke-IntuneRemediationTest { return } - $pre = Invoke-IslScriptRun -Path $DetectionPath -Phase 'detect' @scriptRunSplat - $remediation = $null - $post = $null + # A run that could not be started ends the flow: there is no result to judge the next step by + try { + $pre = Invoke-IslScriptRun -Path $DetectionPath -Phase 'detect' @scriptRunSplat + $remediation = $null + $post = $null - if ($pre.TimedOut) { - $status = 'TimedOut' - } - elseif ($pre.ExitCode -eq 0) { - $status = 'Without issues' - } - else { - if ($pre.ExitCode -ne 1) { - $warnings.Add("Detection exited $($pre.ExitCode): Intune treats any non-zero exit as 'issue found' " + - "(observed with 2 and -1); use 1 to be explicit") + if ($pre.TimedOut) { + $status = 'TimedOut' } - if (-not $RemediationPath) { - $status = 'Issue detected (no remediation script)' + elseif ($pre.ExitCode -eq 0) { + $status = 'Without issues' } else { - $remediation = Invoke-IslScriptRun -Path $RemediationPath -Phase 'remediate' @scriptRunSplat - # Anything on the remediation's stderr is a script error to the agent, whatever the exit - # code: RemediationStatus 3, Graph scriptError, no post-detection (REM-STDERR-EXIT0) - $remediationStdErr = -not [string]::IsNullOrWhiteSpace($remediation.StdErr) - if ($remediation.TimedOut) { $status = 'TimedOut' } - elseif ($remediation.ExitCode -ne 0) { $status = 'Failed' } - elseif ($remediationStdErr) { - $status = 'Failed' - $warnings.Add('Remediation exited 0 but wrote to stderr: Intune reports the run as a script ' + - 'error (Failed, Graph scriptError) with the error text attached, and skips the ' + - 'post-detection. Silence the error or exit non-zero on purpose') + if ($pre.ExitCode -ne 1) { + $warnings.Add("Detection exited $($pre.ExitCode): Intune treats any non-zero exit as " + + "'issue found' (observed with 2 and -1); use 1 to be explicit") + } + if (-not $RemediationPath) { + $status = 'Issue detected (no remediation script)' } else { - $post = Invoke-IslScriptRun -Path $DetectionPath -Phase 'detect' @scriptRunSplat - $status = if ($post.TimedOut) { 'TimedOut' } - elseif ($post.ExitCode -eq 0) { 'Fixed' } - else { 'Recurred' } + $remediation = Invoke-IslScriptRun -Path $RemediationPath -Phase 'remediate' @scriptRunSplat + # Anything on the remediation's stderr is a script error to the agent, whatever the exit + # code: RemediationStatus 3, Graph scriptError, no post-detection (REM-STDERR-EXIT0) + $remediationStdErr = -not [string]::IsNullOrWhiteSpace($remediation.StdErr) + if ($remediation.TimedOut) { $status = 'TimedOut' } + elseif ($remediation.ExitCode -ne 0) { $status = 'Failed' } + elseif ($remediationStdErr) { + $status = 'Failed' + $warnings.Add('Remediation exited 0 but wrote to stderr: Intune reports the run as a script ' + + 'error (Failed, Graph scriptError) with the error text attached, and skips the ' + + 'post-detection. Silence the error or exit non-zero on purpose') + } + else { + $post = Invoke-IslScriptRun -Path $DetectionPath -Phase 'detect' @scriptRunSplat + $status = if ($post.TimedOut) { 'TimedOut' } + elseif ($post.ExitCode -eq 0) { 'Fixed' } + else { 'Recurred' } + } } } + } catch { + $PSCmdlet.ThrowTerminatingError($_) } $intune = Get-IslIntuneOutput -StdOut $pre.StdOut -StdErr $pre.StdErr diff --git a/Public/Invoke-IntuneRequirementTest.ps1 b/Public/Invoke-IntuneRequirementTest.ps1 index 7052ae7..97c5e59 100644 --- a/Public/Invoke-IntuneRequirementTest.ps1 +++ b/Public/Invoke-IntuneRequirementTest.ps1 @@ -55,7 +55,14 @@ function Invoke-IntuneRequirementTest { } if ($Credential) { if ($Context -eq 'System') { - throw '-Credential applies to -Context User; System runs as NT AUTHORITY\SYSTEM' + $recordSplat = @{ + Message = '-Credential applies to -Context User; System runs as NT AUTHORITY\SYSTEM' + ErrorId = 'CredentialWithSystemContext' + Category = [System.Management.Automation.ErrorCategory]::InvalidArgument + TargetObject = $Context + ExceptionType = [System.ArgumentException] + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } $scriptRunSplat.Credential = $Credential } @@ -65,7 +72,14 @@ function Invoke-IntuneRequirementTest { return } - $run = Invoke-IslScriptRun @scriptRunSplat + # A script that cannot be run is reported, and the next one from the pipeline still runs + try { + $run = Invoke-IslScriptRun @scriptRunSplat + } catch { + $PSCmdlet.WriteError($_) + return + } + $compareSplat = @{ StdOut = $run.StdOut StdErr = $run.StdErr diff --git a/Public/Invoke-IntuneWin32AppTest.ps1 b/Public/Invoke-IntuneWin32AppTest.ps1 index c998266..9547972 100644 --- a/Public/Invoke-IntuneWin32AppTest.ps1 +++ b/Public/Invoke-IntuneWin32AppTest.ps1 @@ -69,21 +69,44 @@ function Invoke-IntuneWin32AppTest { # host exists, and x64 elsewhere if (-not $Architecture) { $Architecture = Get-IslHostArchitecture } + $argumentError = @{ + Category = [System.Management.Automation.ErrorCategory]::InvalidArgument + ExceptionType = [System.ArgumentException] + } if (-not $DetectionPath -and -not $DetectionRule) { - throw 'Give a detection script (-DetectionPath), detection rules (-DetectionRule), or both' + $message = 'Give a detection script (-DetectionPath), detection rules (-DetectionRule), or both' + $record = New-IslErrorRecord -Message $message -ErrorId 'DetectionMissing' @argumentError + $PSCmdlet.ThrowTerminatingError($record) } $command = if ($Intent -eq 'Install') { $InstallCommand } else { $UninstallCommand } - if (-not $command) { throw "Intent $Intent needs -${Intent}Command" } - $null = Resolve-Path -LiteralPath $ContentPath -ErrorAction Stop + if (-not $command) { + $message = "Intent $Intent needs -${Intent}Command" + $record = New-IslErrorRecord -Message $message -ErrorId 'IntentCommandMissing' @argumentError + $PSCmdlet.ThrowTerminatingError($record) + } foreach ($related in @($DependsOn) + @($Supersedes)) { if (-not $related) { continue } - if (-not $related['Name']) { throw 'Every -DependsOn and -Supersedes entry needs a Name' } + if (-not $related['Name']) { + $message = 'Every -DependsOn and -Supersedes entry needs a Name' + $record = New-IslErrorRecord -Message $message -ErrorId 'RelatedAppNameMissing' @argumentError + $PSCmdlet.ThrowTerminatingError($record) + } if (-not $related['DetectionPath'] -and -not $related['DetectionRule']) { - throw "$($related['Name']) needs a DetectionPath, DetectionRule entries, or both" + $message = "$($related['Name']) needs a DetectionPath, DetectionRule entries, or both" + $record = New-IslErrorRecord -Message $message -ErrorId 'RelatedAppDetectionMissing' @argumentError + $PSCmdlet.ThrowTerminatingError($record) } - if ($related['ContentPath']) { - $null = Resolve-Path -LiteralPath $related['ContentPath'] -ErrorAction Stop + } + # A content folder that is not there is found before anything runs + try { + $null = Resolve-Path -LiteralPath $ContentPath -ErrorAction Stop + foreach ($related in @($DependsOn) + @($Supersedes)) { + if ($related -and $related['ContentPath']) { + $null = Resolve-Path -LiteralPath $related['ContentPath'] -ErrorAction Stop + } } + } catch { + $PSCmdlet.ThrowTerminatingError($_) } $warnings = [System.Collections.Generic.List[string]]::new() @@ -101,7 +124,9 @@ function Invoke-IntuneWin32AppTest { } if ($Credential) { if ($Context -eq 'System') { - throw '-Credential applies to -Context User; System runs as NT AUTHORITY\SYSTEM' + $message = '-Credential applies to -Context User; System runs as NT AUTHORITY\SYSTEM' + $record = New-IslErrorRecord -Message $message -ErrorId 'CredentialWithSystemContext' @argumentError + $PSCmdlet.ThrowTerminatingError($record) } $detectionSplat.Credential = $Credential } @@ -119,14 +144,20 @@ function Invoke-IntuneWin32AppTest { else { [Environment]::UserName } # One detection pass for this app or a related one: the script (if any) and every rule; all of - # them must say installed (W32-MULTI-ONEFALSE, W32-MULTI-BOTHTRUE) + # them must say installed (W32-MULTI-ONEFALSE, W32-MULTI-BOTHTRUE). A script that cannot be run + # or a rule that cannot be read ends the flow, through the try around every call of this + # function. The detection reports such a script without ending, so it is called with + # -ErrorAction Stop: with nothing returned, the app would read as detected below function Invoke-DetectionPass { param([string]$Phase, [string]$Path, [hashtable[]]$Rule, [string]$Label) $script = $null if ($Path) { - $script = Invoke-IntuneDetectionTest -Path $Path @detectionSplat @script:IslInternal + $detectionRun = @{ Path = $Path; ErrorAction = 'Stop' } + $script = Invoke-IntuneDetectionTest @detectionRun @detectionSplat @script:IslInternal } - $rules = @(foreach ($entry in $Rule) { Test-IntuneWin32Rule -Rule $entry -RuleType Detection }) + $rules = @(foreach ($entry in $Rule) { + Test-IntuneWin32Rule -Rule $entry -RuleType Detection -ErrorAction Stop + }) $unmet = @($rules | Where-Object { -not $_.Met }) $detected = ($null -eq $script -or $script.Detected) -and $unmet.Count -eq 0 $timedOut = $null -ne $script -and $script.TimedOut @@ -146,10 +177,11 @@ function Invoke-IntuneWin32AppTest { } # Runs an install or uninstall command line from a copy of a content folder through the 32-bit - # cmd.exe, as the agent's own 32-bit process does + # cmd.exe, as the agent's own 32-bit process does. A copy or a launch that fails ends the flow, + # through the try around every call of this function function Invoke-ContentCommand { param([string]$Phase, [string]$Content, [string]$CommandLine) - $source = (Resolve-Path -LiteralPath $Content).ProviderPath + $source = (Resolve-Path -LiteralPath $Content -ErrorAction Stop).ProviderPath $hostPattern = '(?i)(^|[\s"])powershell(\.exe)?([\s"]|$)' if ($CommandLine -match $hostPattern) { $warnings.Add("powershell.exe in the $Phase command runs the 32-bit host (the agent is a 32-bit " + @@ -181,11 +213,12 @@ function Invoke-IntuneWin32AppTest { Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "IntuneScriptLab\$runId" } $copy = Join-Path -Path $cache -ChildPath 'content' - $null = New-Item -ItemType Directory -Path $copy -Force @script:IslInternal - $contentItems = Join-Path -Path $source -ChildPath '*' - Copy-Item -Path $contentItems -Destination $copy -Recurse -Force @script:IslInternal - if ($Credential) { Grant-IslFolderAccess -Path $cache -Account $Credential.UserName } try { + $null = New-Item -ItemType Directory -Path $copy -Force -ErrorAction Stop @script:IslInternal + $contentItems = Join-Path -Path $source -ChildPath '*' + $copySplat = @{ Path = $contentItems; Destination = $copy; Recurse = $true; Force = $true } + Copy-Item @copySplat -ErrorAction Stop @script:IslInternal + if ($Credential) { Grant-IslFolderAccess -Path $cache -Account $Credential.UserName } $cmdFolder = if ([Environment]::Is64BitOperatingSystem) { 'SysWOW64' } else { 'System32' } $cmd = Join-Path -Path (Join-Path -Path $env:WINDIR -ChildPath $cmdFolder) -ChildPath 'cmd.exe' $processSplat = @{ @@ -238,154 +271,162 @@ function Invoke-IntuneWin32AppTest { } } - $pre = Invoke-DetectionPass -Phase 'Pre' -Path $DetectionPath -Rule $DetectionRule -Label '' - $execution = $null - $post = $null - $dependencies = [System.Collections.Generic.List[object]]::new() - $superseded = [System.Collections.Generic.List[object]]::new() - $status = $null + # The whole flow is one transaction. A step that could not be run ends it with that step's + # error; the two nested functions above have no catch of their own and depend on this one + try { + $pre = Invoke-DetectionPass -Phase 'Pre' -Path $DetectionPath -Rule $DetectionRule -Label '' + $execution = $null + $post = $null + $dependencies = [System.Collections.Generic.List[object]]::new() + $superseded = [System.Collections.Generic.List[object]]::new() + $status = $null - if ($pre.TimedOut) { $status = 'TimedOut' } - elseif ($Intent -eq 'Install' -and $pre.Detected) { $status = 'Installed' } - elseif ($Intent -eq 'Uninstall' -and -not $pre.Detected) { $status = 'Not installed' } + if ($pre.TimedOut) { $status = 'TimedOut' } + elseif ($Intent -eq 'Install' -and $pre.Detected) { $status = 'Installed' } + elseif ($Intent -eq 'Uninstall' -and -not $pre.Detected) { $status = 'Not installed' } - # Dependencies come after this app's first detection: the child's detection, install and - # detection, then this app again (W32-DEP-PARENT). A detect-only dependency that is absent stops - # the parent with "1 or more dependent apps are configured to not automatically install." - # (W32-DEPD-PARENT) - if (-not $status -and $Intent -eq 'Install') { - foreach ($dependency in @($DependsOn | Where-Object { $_ })) { - $type = if ($dependency['Type']) { "$($dependency['Type'])" } else { 'autoInstall' } - $name = "$($dependency['Name'])" - $detect = @{ - Path = $dependency['DetectionPath'] - Rule = $dependency['DetectionRule'] - Label = " for dependency $name" - } - $childPre = Invoke-DetectionPass -Phase 'Pre' @detect - $childInstall = $null - $childPost = $null - $childStatus = if ($childPre.TimedOut) { 'TimedOut' } - elseif ($childPre.Detected) { 'Installed' } - elseif ($type -ne 'autoInstall') { 'Not detected (detect-only dependency)' } - elseif (-not $dependency['InstallCommand'] -or -not $dependency['ContentPath']) { - 'Not detected (no InstallCommand or ContentPath)' - } - else { - $childRun = @{ - Phase = 'install' - Content = $dependency['ContentPath'] - CommandLine = $dependency['InstallCommand'] + # Dependencies come after this app's first detection: the child's detection, install and + # detection, then this app again (W32-DEP-PARENT). A detect-only dependency that is absent stops + # the parent with "1 or more dependent apps are configured to not automatically install." + # (W32-DEPD-PARENT) + if (-not $status -and $Intent -eq 'Install') { + foreach ($dependency in @($DependsOn | Where-Object { $_ })) { + $type = if ($dependency['Type']) { "$($dependency['Type'])" } else { 'autoInstall' } + $name = "$($dependency['Name'])" + $detect = @{ + Path = $dependency['DetectionPath'] + Rule = $dependency['DetectionRule'] + Label = " for dependency $name" } - $childInstall = Invoke-ContentCommand @childRun - switch (Get-Outcome -Run $childInstall) { - 'timedOut' { 'TimedOut' } - 'retry' { 'Retry' } - 'failed' { "Install failed (exit $($childInstall.ExitCode))" } - default { - $childPost = Invoke-DetectionPass -Phase 'Post' @detect - if ($childPost.Detected) { 'Installed after install' } - else { 'Not detected after install' } + $childPre = Invoke-DetectionPass -Phase 'Pre' @detect + $childInstall = $null + $childPost = $null + $childStatus = if ($childPre.TimedOut) { 'TimedOut' } + elseif ($childPre.Detected) { 'Installed' } + elseif ($type -ne 'autoInstall') { 'Not detected (detect-only dependency)' } + elseif (-not $dependency['InstallCommand'] -or -not $dependency['ContentPath']) { + 'Not detected (no InstallCommand or ContentPath)' + } + else { + $childRun = @{ + Phase = 'install' + Content = $dependency['ContentPath'] + CommandLine = $dependency['InstallCommand'] + } + $childInstall = Invoke-ContentCommand @childRun + switch (Get-Outcome -Run $childInstall) { + 'timedOut' { 'TimedOut' } + 'retry' { 'Retry' } + 'failed' { "Install failed (exit $($childInstall.ExitCode))" } + default { + $childPost = Invoke-DetectionPass -Phase 'Post' @detect + if ($childPost.Detected) { 'Installed after install' } + else { 'Not detected after install' } + } } } - } - $relatedSplat = @{ - Name = $name; Relationship = "dependency ($type)"; Status = $childStatus - Pre = $childPre; Install = $childInstall; Uninstall = $null; Post = $childPost - } - $dependencies.Add((ConvertTo-RelatedResult @relatedSplat)) - if ($childStatus -notin 'Installed', 'Installed after install') { - $status = 'Not installed (dependency)' - $warnings.Add("Dependency $name ($type): $childStatus. The agent does not run this app's " + - 'install; an absent detect-only dependency reports Not installed with "1 or more ' + - 'dependent apps are configured to not automatically install." (W32-DEPD-PARENT)') - break + $relatedSplat = @{ + Name = $name; Relationship = "dependency ($type)"; Status = $childStatus + Pre = $childPre; Install = $childInstall; Uninstall = $null; Post = $childPost + } + $dependencies.Add((ConvertTo-RelatedResult @relatedSplat)) + if ($childStatus -notin 'Installed', 'Installed after install') { + $status = 'Not installed (dependency)' + $warnings.Add("Dependency $name ($type): $childStatus. The agent does not run this app's " + + 'install; an absent detect-only dependency reports Not installed with "1 or more ' + + 'dependent apps are configured to not automatically install." (W32-DEPD-PARENT)') + break + } } } - } - # Superseded apps are detected before this app installs; a replace target that is present is - # uninstalled first (W32-SUP-OLD-B: old uninstall, then new install), an update target stays - # installed (W32-SUP-OLD-A) - if (-not $status -and $Intent -eq 'Install') { - foreach ($old in @($Supersedes | Where-Object { $_ })) { - $type = if ($old['Type']) { "$($old['Type'])" } else { 'update' } - $name = "$($old['Name'])" - $detect = @{ - Path = $old['DetectionPath'] - Rule = $old['DetectionRule'] - Label = " for superseded app $name" - } - $oldPre = Invoke-DetectionPass -Phase 'Pre' @detect - $oldUninstall = $null - $oldPost = $null - $oldStatus = if ($oldPre.TimedOut) { 'TimedOut' } - elseif (-not $oldPre.Detected) { 'Not installed' } - elseif ($type -ne 'replace') { 'Installed (left in place by update)' } - elseif (-not $old['UninstallCommand'] -or -not $old['ContentPath']) { - 'Installed (no UninstallCommand or ContentPath)' - } - else { - $oldRun = @{ - Phase = 'uninstall' - Content = $old['ContentPath'] - CommandLine = $old['UninstallCommand'] + # Superseded apps are detected before this app installs; a replace target that is present is + # uninstalled first (W32-SUP-OLD-B: old uninstall, then new install), an update target stays + # installed (W32-SUP-OLD-A) + if (-not $status -and $Intent -eq 'Install') { + foreach ($old in @($Supersedes | Where-Object { $_ })) { + $type = if ($old['Type']) { "$($old['Type'])" } else { 'update' } + $name = "$($old['Name'])" + $detect = @{ + Path = $old['DetectionPath'] + Rule = $old['DetectionRule'] + Label = " for superseded app $name" } - $oldUninstall = Invoke-ContentCommand @oldRun - switch (Get-Outcome -Run $oldUninstall) { - 'timedOut' { 'TimedOut' } - 'retry' { 'Retry' } - 'failed' { "Uninstall failed (exit $($oldUninstall.ExitCode))" } - default { - $oldPost = Invoke-DetectionPass -Phase 'Post' @detect - if ($oldPost.Detected) { 'Still detected after uninstall' } else { 'Uninstalled' } + $oldPre = Invoke-DetectionPass -Phase 'Pre' @detect + $oldUninstall = $null + $oldPost = $null + $oldStatus = if ($oldPre.TimedOut) { 'TimedOut' } + elseif (-not $oldPre.Detected) { 'Not installed' } + elseif ($type -ne 'replace') { 'Installed (left in place by update)' } + elseif (-not $old['UninstallCommand'] -or -not $old['ContentPath']) { + 'Installed (no UninstallCommand or ContentPath)' + } + else { + $oldRun = @{ + Phase = 'uninstall' + Content = $old['ContentPath'] + CommandLine = $old['UninstallCommand'] + } + $oldUninstall = Invoke-ContentCommand @oldRun + switch (Get-Outcome -Run $oldUninstall) { + 'timedOut' { 'TimedOut' } + 'retry' { 'Retry' } + 'failed' { "Uninstall failed (exit $($oldUninstall.ExitCode))" } + default { + $oldPost = Invoke-DetectionPass -Phase 'Post' @detect + if ($oldPost.Detected) { 'Still detected after uninstall' } else { 'Uninstalled' } + } } } - } - $relatedSplat = @{ - Name = $name; Relationship = "supersedence ($type)"; Status = $oldStatus - Pre = $oldPre; Install = $null; Uninstall = $oldUninstall; Post = $oldPost - } - $superseded.Add((ConvertTo-RelatedResult @relatedSplat)) - if ($type -eq 'replace' -and $oldStatus -notin 'Uninstalled', 'Not installed') { - $warnings.Add("Superseded app $name (replace): $oldStatus. The agent removes a replace target " + - 'before it installs the new app (W32-SUP-OLD-B), so the old app would still be present') + $relatedSplat = @{ + Name = $name; Relationship = "supersedence ($type)"; Status = $oldStatus + Pre = $oldPre; Install = $null; Uninstall = $oldUninstall; Post = $oldPost + } + $superseded.Add((ConvertTo-RelatedResult @relatedSplat)) + if ($type -eq 'replace' -and $oldStatus -notin 'Uninstalled', 'Not installed') { + $warnings.Add("Superseded app $name (replace): $oldStatus. The agent removes a replace " + + 'target before it installs the new app (W32-SUP-OLD-B), so the old app would still ' + + 'be present') + } } } - } - if (-not $status) { - $execution = Invoke-ContentCommand -Phase $Intent.ToLower() -Content $ContentPath -CommandLine $command - $outcome = Get-Outcome -Run $execution - switch ($outcome) { - 'timedOut' { $status = 'TimedOut' } - 'retry' { $status = 'Retry' } - 'failed' { $status = "$Intent failed (exit $($execution.ExitCode))" } - default { - if ($outcome -in 'softReboot', 'hardReboot') { - $warnings.Add("$Intent returned $($execution.ExitCode): Intune records a $outcome as pending") - } - $post = Invoke-DetectionPass -Phase 'Post' -Path $DetectionPath -Rule $DetectionRule -Label '' - if ($post.TimedOut) { $status = 'TimedOut' } - elseif ($Intent -eq 'Install') { - $status = if ($post.Detected) { 'Installed after install' } - else { 'Not detected after install' } - if (-not $post.Detected) { - $warnings.Add("Post-install detection: $($post.Reason). Intune reports 0x87D1041C " + - 'and retries the install at the next check-in') + if (-not $status) { + $execution = Invoke-ContentCommand -Phase $Intent.ToLower() -Content $ContentPath -CommandLine $command + $outcome = Get-Outcome -Run $execution + switch ($outcome) { + 'timedOut' { $status = 'TimedOut' } + 'retry' { $status = 'Retry' } + 'failed' { $status = "$Intent failed (exit $($execution.ExitCode))" } + default { + if ($outcome -in 'softReboot', 'hardReboot') { + $warnings.Add("$Intent returned $($execution.ExitCode): Intune records a $outcome " + + 'as pending') } - } - else { - # Observed flow (W32-UNINSTALL): detected, uninstall command, detected again, and - # "Not installed" once the detection stops saying installed - $status = if ($post.Detected) { 'Still detected after uninstall' } else { 'Uninstalled' } - if ($post.Detected) { - $warnings.Add('Post-uninstall detection still reports installed: Intune keeps ' + - 'the app as installed and retries the uninstall at the next check-in') + $post = Invoke-DetectionPass -Phase 'Post' -Path $DetectionPath -Rule $DetectionRule -Label '' + if ($post.TimedOut) { $status = 'TimedOut' } + elseif ($Intent -eq 'Install') { + $status = if ($post.Detected) { 'Installed after install' } + else { 'Not detected after install' } + if (-not $post.Detected) { + $warnings.Add("Post-install detection: $($post.Reason). Intune reports 0x87D1041C " + + 'and retries the install at the next check-in') + } + } + else { + # Observed flow (W32-UNINSTALL): detected, uninstall command, detected again, and + # "Not installed" once the detection stops saying installed + $status = if ($post.Detected) { 'Still detected after uninstall' } else { 'Uninstalled' } + if ($post.Detected) { + $warnings.Add('Post-uninstall detection still reports installed: Intune keeps ' + + 'the app as installed and retries the uninstall at the next check-in') + } } } } } + } catch { + $PSCmdlet.ThrowTerminatingError($_) } Write-Verbose "Completed $($MyInvocation.MyCommand.Name)" diff --git a/README.md b/README.md index e5ce0a8..bfaf577 100644 --- a/README.md +++ b/README.md @@ -744,7 +744,7 @@ Install-PSResource Microsoft.PowerShell.PlatyPS # 1.0.3 or later, once | `-Context System` says "run elevated" | `Register-ScheduledTask` needs an administrator session. Restart PowerShell as administrator; the current-user runs need no elevation. | | `-Architecture x64` refused on an ARM64 PC | ARM64 Windows has no x64 `powershell.exe`; only x86 (emulated) and arm64 (native) exist there, which is what Intune's agent uses too. Test x64 on an x64 machine. | | Runtime result differs from what Intune showed | Compare what the result carries as Intune reports it: `IntuneOutput` and `IntuneError` on a remediation result, `StdOut`, `StdErr` and `ExitCode` on a detection, platform script or requirement result (OEM code page; the 2,048-character tail where the portal caps it). The `-Verbose` switch prints each step. | -| A script goes on after `Get-IntuneAgentLog`, `Get-IntuneAgentTimeline` or `Export-IntuneAgentDiagnostic` failed | These three end on a failure with a terminating error, as a compiled cmdlet does: the command ends, and the script decides whether it stops too. Start the script with `$ErrorActionPreference = 'Stop'`, or make the call inside `try`. The error's `FullyQualifiedErrorId` says what failed, for example `UnknownAgentLogEvent` or `DiagnosticPackageExists`. A path that does not exist and a log that cannot be parsed (`CmTraceTimestampInvalid`) are reported for that one item and the other logs are still read; `-ErrorAction Stop` ends the command there. | +| A script goes on after a command failed | `Get-IntuneAgentLog`, `Get-IntuneAgentTimeline`, `Export-IntuneAgentDiagnostic` and the five `Invoke-Intune*Test` commands end on a failure with a terminating error, as a compiled cmdlet does: the command ends, and the script decides whether it stops too. Start the script with `$ErrorActionPreference = 'Stop'`, or make the call inside `try`. The error's `FullyQualifiedErrorId` says what failed, for example `UnknownAgentLogEvent`, `DiagnosticPackageExists`, `HostArchitectureUnavailable` or `ScheduledTaskNotRegistered`. One item among several is reported for that item and the others are still processed: a path that does not exist and a log that cannot be parsed (`CmTraceTimestampInvalid`) for the log commands, a script that cannot be run for `Invoke-IntuneDetectionTest`, `Invoke-IntuneRequirementTest` and `Invoke-IntunePlatformScriptTest`. `-ErrorAction Stop` ends the command there. | | Pester says `Should-HaveIntuneStatus` is not recognised | The aliases come from this module, not Pester: `Import-Module IntuneScriptLab` in `BeforeAll`, and use Pester 6.2 or later (`New-ShouldAssertion`). | ## Blog posts diff --git a/Tests/Integration/RuntimeHarness.Tests.ps1 b/Tests/Integration/RuntimeHarness.Tests.ps1 index e02507b..ac7b8e2 100644 --- a/Tests/Integration/RuntimeHarness.Tests.ps1 +++ b/Tests/Integration/RuntimeHarness.Tests.ps1 @@ -59,7 +59,8 @@ Describe 'Runtime harness launch' -Tag 'Integration', 'Runtime' { 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 } + $refused | Should-Throw -FullyQualifiedErrorId 'HostArchitectureUnavailable,*' } It 'kills a script at the timeout and reports TimedOut' { @@ -94,6 +95,66 @@ Describe 'Runtime harness launch' -Tag 'Integration', 'Runtime' { } } +Describe 'A run that cannot be started, for a script that has no try' -Tag 'Integration', 'Runtime' { + + It 'reports a script that is not there and still runs the next one from the pipeline' { + $good = New-TestScript 'good.ps1' "'ran'; exit 0" -Bom + $missing = Join-Path $TestDrive 'not-there.ps1' + + $run = Invoke-CallerScript -Statement @( + "`$results = @('$missing', '$good' | Invoke-IntunePlatformScriptTest)" + "'results: ' + `$results.Count + ' ' + `$results[0].RunState" + ) + + $run.ReachedEnd | Should-BeTrue + $run.Output | Should-BeCollection -Count 1 + $run.Output[0] | Should-Be 'results: 1 Success' + $run.ErrorId | Should-BeCollection -Count 1 + $run.ErrorId[0] | Should-BeLikeString 'PathNotFound,*' + } + + It 'ends a remediation at the detection that is not there, with one error and no result' { + $missing = Join-Path $TestDrive 'not-there.ps1' + $marker = Join-Path $TestDrive "remediated-$([guid]::NewGuid().ToString('N')).marker" + $remediate = New-TestScript 'remediate-marker.ps1' "Set-Content -LiteralPath '$marker' -Value ran" -Bom + + $run = Invoke-CallerScript -Statement @( + "`$result = Invoke-IntuneRemediationTest -DetectionPath '$missing' -RemediationPath '$remediate'" + "'no result: ' + (`$null -eq `$result)" + ) + + $run.ReachedEnd | Should-BeTrue + $run.Output | Should-BeCollection -Count 1 + $run.Output[0] | Should-Be 'no result: True' + $run.ErrorId | Should-BeCollection -Count 1 + $run.ErrorId[0] | Should-BeLikeString 'PathNotFound,*' + Test-Path -LiteralPath $marker | Should-BeFalse + } + + It 'ends a Win32 uninstall at the detection that is not there, without running the command' { + # With nothing where the detection result should be, the app read as detected + $missing = Join-Path $TestDrive 'not-there.ps1' + $content = Join-Path $TestDrive "content-$([guid]::NewGuid().ToString('N'))" + $null = New-Item -ItemType Directory -Path $content + $marker = Join-Path $TestDrive "uninstalled-$([guid]::NewGuid().ToString('N')).marker" + $batch = Join-Path $content 'uninstall.cmd' + Set-Content -LiteralPath $batch -Value "@echo ran> `"$marker`"" -Encoding ascii + + $run = Invoke-CallerScript -Statement @( + "`$appSplat = @{ DetectionPath = '$missing'; ContentPath = '$content'; Intent = 'Uninstall' }" + "`$result = Invoke-IntuneWin32AppTest @appSplat -UninstallCommand 'uninstall.cmd'" + "'no result: ' + (`$null -eq `$result)" + ) + + $run.ReachedEnd | Should-BeTrue + $run.Output | Should-BeCollection -Count 1 + $run.Output[0] | Should-Be 'no result: True' + $run.ErrorId | Should-BeCollection -Count 1 + $run.ErrorId[0] | Should-BeLikeString 'PathNotFound,*' + Test-Path -LiteralPath $marker | Should-BeFalse + } +} + Describe 'Remediation output as Intune reports it' -Tag 'Integration', 'Runtime' { It 'treats a script-scope return as exit 0, as Intune does' { diff --git a/Tests/Unit/Module.ErrorFlow.Tests.ps1 b/Tests/Unit/Module.ErrorFlow.Tests.ps1 index eb16a34..19f2e5b 100644 --- a/Tests/Unit/Module.ErrorFlow.Tests.ps1 +++ b/Tests/Unit/Module.ErrorFlow.Tests.ps1 @@ -32,6 +32,10 @@ BeforeAll { Caller, Callee, Call (both names) and EndsQuietly: whether the callee ends with ThrowTerminatingError, which lets the caller carry on. + A call is guarded when it is inside a try that has a catch. A call made in a nested + function is guarded as well when every call of that nested function is: an error + raised below a try travels up to its catch through every function in between. + .PARAMETER ModuleRoot The folder that holds Public and Private. @@ -132,6 +136,31 @@ BeforeAll { } } + # 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 = @{} + foreach ($name in $nodes.Keys) { + if ($name -like '*::*' -and @($calls | Where-Object { $_.Callee -eq $name }).Count -gt 0) { + $covered[$name] = $true + } + } + do { + $changed = $false + foreach ($call in $calls) { + $isCovered = $call.Guarded -or $covered.ContainsKey($call.Caller) + if (-not $isCovered -and $covered.ContainsKey($call.Callee)) { + $covered.Remove($call.Callee) + $changed = $true + } + } + } while ($changed) + foreach ($call in $calls) { + if ($covered.ContainsKey($call.Caller)) { + $call.Guarded = $true + } + } + # A function that makes an unguarded call to one that can fail can fail itself do { $changed = $false @@ -173,16 +202,10 @@ Describe 'How a failure travels through the module' -Tag 'Unit', 'Contract' { } It 'never calls a function that ends with ThrowTerminatingError outside a try with a catch' { - # 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 = @( - 'Invoke-IslProcess -> Stop-IslProcessTree' - ) + # The caller would carry on with nothing where the result should be $quiet = @($script:Unguarded | Where-Object { $_.EndsQuietly } | ForEach-Object { $_.Call } | Sort-Object) - @($quiet | Where-Object { $_ -notin $known }) | Should-BeCollection @() - @($known | Where-Object { $_ -notin $quiet }) | Should-BeCollection @() + $quiet | Should-BeCollection @() } It 'lists every call that still relies on a throw in the function it calls, and no other' { @@ -211,20 +234,7 @@ Describe 'How a failure travels through the module' -Tag 'Unit', 'Contract' { 'Get-IntuneScriptHealth::Get-WantedPolicy -> Invoke-IslGraphRequest' 'Get-IslExportReport -> Invoke-IslGraphRequest' 'Get-IslSetting -> Get-IslSetting::ConvertTo-SettingsObject' - 'Invoke-IntuneDetectionTest -> Invoke-IslScriptRun' - 'Invoke-IntunePlatformScriptTest -> Invoke-IslScriptRun' - 'Invoke-IntuneRemediationTest -> Invoke-IslScriptRun' - 'Invoke-IntuneRequirementTest -> Invoke-IslScriptRun' - 'Invoke-IntuneWin32AppTest -> Invoke-IntuneWin32AppTest::Invoke-ContentCommand' - 'Invoke-IntuneWin32AppTest -> Invoke-IntuneWin32AppTest::Invoke-DetectionPass' - 'Invoke-IntuneWin32AppTest::Invoke-ContentCommand -> Grant-IslFolderAccess' - 'Invoke-IntuneWin32AppTest::Invoke-ContentCommand -> Invoke-IslProcess' - 'Invoke-IntuneWin32AppTest::Invoke-DetectionPass -> Invoke-IntuneDetectionTest' - 'Invoke-IntuneWin32AppTest::Invoke-DetectionPass -> Test-IntuneWin32Rule' 'Invoke-IslGraphRequest -> Invoke-IslGraphRequest::Invoke-Once' - 'Invoke-IslScriptRun -> Get-IslHostPath' - 'Invoke-IslScriptRun -> Grant-IslFolderAccess' - 'Invoke-IslScriptRun -> Invoke-IslProcess' 'Repair-IntuneScript -> Test-IntuneScript' 'Test-IntuneAssignmentFilter -> Get-IslFilterDeviceFact' 'Test-IntuneDeployedScript -> Invoke-IslGraphRequest' diff --git a/Tests/Unit/Private/Get-IslHostPath.Tests.ps1 b/Tests/Unit/Private/Get-IslHostPath.Tests.ps1 index ad5b574..c96326a 100644 --- a/Tests/Unit/Private/Get-IslHostPath.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslHostPath.Tests.ps1 @@ -58,6 +58,15 @@ Describe 'Get-IslHostPath' -Tag 'Unit', 'Private' { Get-IslHostPath -Architecture $Missing } } | Should-Throw $failure.Exception.Message | Should-BeLikeString "*-Architecture $($script:Native)*" + $failure.FullyQualifiedErrorId | Should-BeLikeString 'HostArchitectureUnavailable,*' + } + + It 'says which host is missing when the file is not where Windows keeps it' { + Mock Test-Path -ModuleName IntuneScriptLab { $false } + + $failure = { InModuleScope IntuneScriptLab { Get-IslHostPath -Architecture x86 } } | Should-Throw + $failure.Exception.Message | Should-BeLikeString 'PowerShell host not found: *powershell.exe' + $failure.FullyQualifiedErrorId | Should-BeLikeString 'HostNotFound,*' } } } diff --git a/Tests/Unit/Private/Grant-IslFolderAccess.Tests.ps1 b/Tests/Unit/Private/Grant-IslFolderAccess.Tests.ps1 index a5be3c9..dbe6355 100644 --- a/Tests/Unit/Private/Grant-IslFolderAccess.Tests.ps1 +++ b/Tests/Unit/Private/Grant-IslFolderAccess.Tests.ps1 @@ -68,5 +68,6 @@ Describe 'Grant-IslFolderAccess' -Tag 'Unit', 'Private' { $missing = "$env:COMPUTERNAME\no-such-account-for-isl" $failure = { Grant-Access $script:Folder $missing $Preference } | Should-Throw $failure.Exception.Message | Should-BeLikeString "Could not grant $missing access to *No mapping*" + $failure.FullyQualifiedErrorId | Should-BeLikeString 'FolderAccessNotGranted,*' } } diff --git a/Tests/Unit/Private/Invoke-IslNativeCommand.Tests.ps1 b/Tests/Unit/Private/Invoke-IslNativeCommand.Tests.ps1 new file mode 100644 index 0000000..a0c63fe --- /dev/null +++ b/Tests/Unit/Private/Invoke-IslNativeCommand.Tests.ps1 @@ -0,0 +1,71 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The runner for the small system tools, against a real cmd.exe (milliseconds). What matters is + what the call operator gets wrong on Windows PowerShell 5.1: a line on the error stream must + come back as text, whatever error preference is in force in the module. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force + $script:Cmd = Join-Path ([System.Environment]::SystemDirectory) 'cmd.exe' + + function Invoke-NativeCommand { + param([hashtable]$Parameters, [string]$Preference = 'Continue') + InModuleScope IntuneScriptLab -Parameters @{ Parameters = $Parameters; Preference = $Preference } { + # What a caller's -ErrorAction leaves in force inside the module + $ErrorActionPreference = $Preference + Invoke-IslNativeCommand @Parameters + } + } +} + +AfterAll { + Remove-Module IntuneScriptLab -Force -ErrorAction SilentlyContinue +} + +Describe 'Invoke-IslNativeCommand' -Tag 'Unit', 'Private' { + + Context 'Parameter Validation' { + It 'needs the path of the executable and takes the arguments as one optional string' { + $command = InModuleScope IntuneScriptLab { Get-Command Invoke-IslNativeCommand } + $command | Should-HaveParameter -ParameterName FilePath -Type ([string]) -Mandatory + $command | Should-HaveParameter -ParameterName Arguments -Type ([string]) + $command.Parameters['Arguments'].Attributes.Mandatory | Should-NotContainCollection $true + } + } + + Context 'Core Functionality' { + It 'returns the exit code and what both streams held, under error action ' -ForEach @( + @{ Preference = 'Continue' } + @{ Preference = 'Stop' } + ) { + $result = Invoke-NativeCommand -Preference $Preference -Parameters @{ + FilePath = $script:Cmd; Arguments = '/D /C "echo out& echo err 1>&2& exit 3"' + } + + $result.PSObject.TypeNames | Should-ContainCollection 'IntuneScriptLab.NativeCommandResult' + $result.ExitCode | Should-Be 3 + $result.StdOut | Should-Be 'out' + $result.StdErr | Should-Be 'err' + } + + It 'returns empty text for a stream the executable did not write to' { + $result = Invoke-NativeCommand @{ FilePath = $script:Cmd; Arguments = '/D /C "exit 0"' } + + $result.ExitCode | Should-Be 0 + $result.StdOut | Should-Be '' + $result.StdErr | Should-Be '' + } + } + + Context 'Error Handling' { + It 'ends with a terminating error when the executable cannot be started' { + $missing = Join-Path $TestDrive 'no-such-tool.exe' + + { Invoke-NativeCommand @{ FilePath = $missing } } | + Should-Throw -ExceptionType ([System.Management.Automation.MethodInvocationException]) + } + } +} diff --git a/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 b/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 index aaacbe0..cc62c00 100644 --- a/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 +++ b/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 @@ -40,6 +40,38 @@ Describe 'Invoke-IslProcess' -Tag 'Unit', 'Private' { $result.PSObject.TypeNames | Should-ContainCollection 'IntuneScriptLab.ProcessResult' } + It 'says which executable could not be started' { + $missing = Join-Path $TestDrive 'no-such-host.exe' + $failure = { Invoke-Process @{ + FilePath = $missing; WorkingDirectory = $TestDrive; WorkFolder = $TestDrive + } } | Should-Throw + $failure.Exception.Message | Should-BeLikeString "Could not start '$missing': *" + $failure.FullyQualifiedErrorId | Should-BeLikeString 'ProcessStartFailed,*' + } + + It 'ends with the error of a cleanup that could not be run after a timeout' { + # A TimedOut result would say that the tree is gone. The mock notes the process it was + # asked to end, and the test ends it afterwards + $script:LeftRunning = $null + Mock Stop-IslProcessTree -ModuleName IntuneScriptLab { + $script:LeftRunning = $ProcessId + throw 'taskkill.exe could not be started' + } + try { + $failure = { Invoke-Process @{ + FilePath = $script:Cmd; Arguments = '/D /C ping.exe -n 30 127.0.0.1 > nul' + WorkingDirectory = [System.Environment]::SystemDirectory; WorkFolder = $TestDrive + TimeoutSeconds = 1 + } } | Should-Throw + $failure.Exception.Message | Should-BeLikeString '*taskkill.exe could not be started*' + $script:LeftRunning | Should-NotBeNull + } finally { + if ($script:LeftRunning) { + $null = & $script:Cmd /D /C "taskkill.exe /PID $($script:LeftRunning) /T /F > nul 2>&1" + } + } + } + It 'runs in the working directory it is given' { $result = Invoke-Process @{ FilePath = $script:Cmd; Arguments = '/C cd'; WorkingDirectory = $TestDrive; WorkFolder = $TestDrive @@ -185,6 +217,7 @@ Describe 'Invoke-IslProcess' -Tag 'Unit', 'Private' { FilePath = 'x.exe'; WorkingDirectory = 'C:\'; WorkFolder = $script:WorkFolder; Context = 'System' } } | Should-Throw $failure.Exception.Message | Should-BeLikeString '*run elevated*Access is denied*' + $failure.FullyQualifiedErrorId | Should-BeLikeString 'ScheduledTaskNotRegistered,*' } It 'reports TimedOut, stops the task and removes it when no exit file appears' { @@ -372,6 +405,7 @@ Describe 'Invoke-IslProcess' -Tag 'Unit', 'Private' { $stopwatch.Elapsed.TotalSeconds | Should-BeLessThan 10 $failure.Exception.Message | Should-BeLikeString '*LAB\isl-user did not start: 0x80070569*Log on as a batch job*' + $failure.FullyQualifiedErrorId | Should-BeLikeString 'ScheduledTaskNotStarted,*' Should-Invoke Unregister-ScheduledTask -ModuleName IntuneScriptLab -Exactly -Times 1 } diff --git a/Tests/Unit/Private/Invoke-IslScriptRun.Tests.ps1 b/Tests/Unit/Private/Invoke-IslScriptRun.Tests.ps1 index f58d716..2895483 100644 --- a/Tests/Unit/Private/Invoke-IslScriptRun.Tests.ps1 +++ b/Tests/Unit/Private/Invoke-IslScriptRun.Tests.ps1 @@ -64,6 +64,20 @@ Describe 'Invoke-IslScriptRun' -Tag 'Unit', 'Private' { Should-Invoke Invoke-IslProcess -ModuleName IntuneScriptLab -Times 0 -Exactly } + It 'ends without starting the host when the script cannot be copied' { + # Copy-Item reports this without ending anything. The run used to go on, and the host + # was started on a file that was not there + $locked = New-TestScript 'Locked.ps1' 'exit 0' -Bom + $stream = [System.IO.File]::Open($locked, 'Open', 'Read', 'None') + try { + { Invoke-ScriptRun @{ Path = $locked; Architecture = 'x86' } } | + Should-Throw -ExceptionType ([System.IO.IOException]) + } finally { + $stream.Dispose() + } + Should-Invoke Invoke-IslProcess -ModuleName IntuneScriptLab -Times 0 -Exactly + } + It 'removes the cache copy after the run' { $result = Invoke-ScriptRun @{ Path = $script:Script; Architecture = 'x86' } $workFolder = ($result.StdOut -split '\|')[3] diff --git a/Tests/Unit/Public/Invoke-IntuneDetectionTest.Tests.ps1 b/Tests/Unit/Public/Invoke-IntuneDetectionTest.Tests.ps1 index 13d8d1e..9160ffd 100644 --- a/Tests/Unit/Public/Invoke-IntuneDetectionTest.Tests.ps1 +++ b/Tests/Unit/Public/Invoke-IntuneDetectionTest.Tests.ps1 @@ -163,6 +163,44 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { $reason = (Invoke-IntuneDetectionTest -Path $script:Detect).Reason $reason | Should-BeLikeString '*Exit code 2*Nothing on stdout*stderr*' } + + It 'reports a script that cannot be run and goes on with the next one from the pipeline' { + Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'installed'; StdErr = '' } + } + Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Path -like '*broken*' } { + throw 'The host could not be started.' + } + + $output = 'C:\lab\broken.ps1', $script:Detect | + Invoke-IntuneDetectionTest -ErrorAction Continue 2>&1 + $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) + $results = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }) + + $errors | Should-BeCollection -Count 1 + $errors[0].Exception.Message | Should-BeLikeString '*host could not be started*' + $results | Should-BeCollection -Count 1 + $results[0].Detected | Should-BeTrue + } + + It 'ends at the script that cannot be run when the caller asks it to stop' { + Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { throw 'The host could not be started.' } + + { 'C:\lab\broken.ps1', $script:Detect | Invoke-IntuneDetectionTest -ErrorAction Stop } | + Should-Throw -ExceptionMessage '*host could not be started*' + Should-Invoke Invoke-IslScriptRun -ModuleName IntuneScriptLab -Times 1 -Exactly + } + + It 'reports a script that is not there when the signature check has to read it' { + Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { } + $missing = Join-Path $TestDrive 'nowhere.ps1' + + $output = Invoke-IntuneDetectionTest -Path $missing -EnforceSignatureCheck -ErrorAction Continue 2>&1 + + $output | Should-BeCollection -Count 1 + $output[0].FullyQualifiedErrorId | Should-BeLikeString 'PathNotFound,*' + Should-Invoke Invoke-IslScriptRun -ModuleName IntuneScriptLab -Times 0 -Exactly + } } Context 'Another account' { @@ -183,7 +221,7 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { $Credential.UserName -eq 'LAB\isl-user' } { Invoke-IntuneDetectionTest -Path $script:Detect -Context System -Credential $credential } | - Should-Throw -ExceptionMessage '*-Credential applies to -Context User*' + Should-Throw -FullyQualifiedErrorId 'CredentialWithSystemContext,*' } } } diff --git a/Tests/Unit/Public/Invoke-IntunePlatformScriptTest.Tests.ps1 b/Tests/Unit/Public/Invoke-IntunePlatformScriptTest.Tests.ps1 index 50c338e..88f979f 100644 --- a/Tests/Unit/Public/Invoke-IntunePlatformScriptTest.Tests.ps1 +++ b/Tests/Unit/Public/Invoke-IntunePlatformScriptTest.Tests.ps1 @@ -92,6 +92,33 @@ Describe 'Invoke-IntunePlatformScriptTest' -Tag 'Unit', 'Public' { $result.TimedOut | Should-BeTrue $result.ExitCode | Should-BeNull } + + It 'reports a script that cannot be run and goes on with the next one from the pipeline' { + Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'done'; StdErr = '' } + } + Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Path -like '*broken*' } { + throw 'The host could not be started.' + } + + $output = 'C:\lab\broken.ps1', $script:Script | + Invoke-IntunePlatformScriptTest -ErrorAction Continue 2>&1 + $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) + $results = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }) + + $errors | Should-BeCollection -Count 1 + $errors[0].Exception.Message | Should-BeLikeString '*host could not be started*' + $results | Should-BeCollection -Count 1 + $results[0].RunState | Should-Be 'Success' + } + + It 'ends at the script that cannot be run when the caller asks it to stop' { + Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { throw 'The host could not be started.' } + + { 'C:\lab\broken.ps1', $script:Script | Invoke-IntunePlatformScriptTest -ErrorAction Stop } | + Should-Throw -ExceptionMessage '*host could not be started*' + Should-Invoke Invoke-IslScriptRun -ModuleName IntuneScriptLab -Times 1 -Exactly + } } Context 'Another account' { @@ -110,7 +137,7 @@ Describe 'Invoke-IntunePlatformScriptTest' -Tag 'Unit', 'Public' { $Credential.UserName -eq 'LAB\isl-user' } { Invoke-IntunePlatformScriptTest -Path $script:Script -Context System -Credential $credential } | - Should-Throw -ExceptionMessage '*-Credential applies to -Context User*' + Should-Throw -FullyQualifiedErrorId 'CredentialWithSystemContext,*' } } } diff --git a/Tests/Unit/Public/Invoke-IntuneRemediationTest.Tests.ps1 b/Tests/Unit/Public/Invoke-IntuneRemediationTest.Tests.ps1 index d623efc..33d0ade 100644 --- a/Tests/Unit/Public/Invoke-IntuneRemediationTest.Tests.ps1 +++ b/Tests/Unit/Public/Invoke-IntuneRemediationTest.Tests.ps1 @@ -65,7 +65,7 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { $Credential.UserName -eq 'LAB\isl-user' } { Invoke-IntuneRemediationTest @remediationSplat -Context System } | - Should-Throw -ExceptionMessage '*-Credential applies to -Context User*' + Should-Throw -FullyQualifiedErrorId 'CredentialWithSystemContext,*' } } @@ -200,5 +200,18 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { $result.Status | Should-Be 'TimedOut' $result.PostDetection | Should-BeNull } + + It 'ends with the error of a run that cannot be started, without the detection that follows' { + Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'remediate' } { + throw 'The host could not be started.' + } + $remediationSplat = @{ DetectionPath = $script:Detect; RemediationPath = $script:Remediate } + + { Invoke-IntuneRemediationTest @remediationSplat } | + Should-Throw -ExceptionMessage '*host could not be started*' + Should-Invoke Invoke-IslScriptRun -ModuleName IntuneScriptLab -Times 1 -Exactly -ParameterFilter { + $Phase -eq 'detect' + } + } } } diff --git a/Tests/Unit/Public/Invoke-IntuneRequirementTest.Tests.ps1 b/Tests/Unit/Public/Invoke-IntuneRequirementTest.Tests.ps1 index cc12f98..4e5814b 100644 --- a/Tests/Unit/Public/Invoke-IntuneRequirementTest.Tests.ps1 +++ b/Tests/Unit/Public/Invoke-IntuneRequirementTest.Tests.ps1 @@ -120,5 +120,47 @@ Describe 'Invoke-IntuneRequirementTest' -Tag 'Unit', 'Public' { $result.TimedOut | Should-BeTrue $result.Reason | Should-BeLikeString 'Timed out*' } + + It 'reports a script that cannot be run and goes on with the next one from the pipeline' { + Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'ok'; StdErr = '' } + } + Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Path -like '*broken*' } { + throw 'The host could not be started.' + } + + $output = 'C:\lab\broken.ps1', $script:Script | + Invoke-IntuneRequirementTest -OutputType String -Value 'ok' -ErrorAction Continue 2>&1 + $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) + $results = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }) + + $errors | Should-BeCollection -Count 1 + $errors[0].Exception.Message | Should-BeLikeString '*host could not be started*' + $results | Should-BeCollection -Count 1 + $results[0].Applicable | Should-BeTrue + } + + It 'ends at the script that cannot be run when the caller asks it to stop' { + Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { throw 'The host could not be started.' } + $requirementSplat = @{ OutputType = 'String'; Value = 'ok'; ErrorAction = 'Stop' } + + { 'C:\lab\broken.ps1', $script:Script | Invoke-IntuneRequirementTest @requirementSplat } | + Should-Throw -ExceptionMessage '*host could not be started*' + Should-Invoke Invoke-IslScriptRun -ModuleName IntuneScriptLab -Times 1 -Exactly + } + + It 'refuses -Credential with Context System before anything runs' { + Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { } + $secure = [securestring]::new() + foreach ($char in 'pw'.ToCharArray()) { $secure.AppendChar($char) } + $requirementSplat = @{ + Path = $script:Script; OutputType = 'String'; Value = 'ok'; Context = 'System' + Credential = [pscredential]::new('LAB\isl-user', $secure) + } + + { Invoke-IntuneRequirementTest @requirementSplat } | + Should-Throw -FullyQualifiedErrorId 'CredentialWithSystemContext,*' + Should-Invoke Invoke-IslScriptRun -ModuleName IntuneScriptLab -Times 0 -Exactly + } } } diff --git a/Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 b/Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 index 8c2267f..df4c09f 100644 --- a/Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 +++ b/Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 @@ -61,13 +61,13 @@ Describe 'Invoke-IntuneWin32AppTest' -Tag 'Unit', 'Public' { $command = Get-Command Invoke-IntuneWin32AppTest $command.Parameters['ContentPath'].Attributes.Mandatory | Should-ContainCollection $true { Invoke-IntuneWin32AppTest -ContentPath $script:Fixture.Content -InstallCommand 'setup.exe' } | - Should-Throw -ExceptionMessage '*-DetectionPath*-DetectionRule*' + Should-Throw -FullyQualifiedErrorId 'DetectionMissing,*' -ExceptionMessage '*-DetectionPath*-DetectionRule*' $intuneWin32AppTestSplat = @{ DetectionPath = $script:Fixture.Detection ContentPath = $script:Fixture.Content } { Invoke-IntuneWin32AppTest @intuneWin32AppTestSplat } | - Should-Throw -ExceptionMessage '*-InstallCommand*' + Should-Throw -FullyQualifiedErrorId 'IntentCommandMissing,*' -ExceptionMessage '*-InstallCommand*' $intuneWin32AppTestSplat2 = @{ DetectionPath = $script:Fixture.Detection Intent = 'Uninstall' @@ -98,7 +98,24 @@ Describe 'Invoke-IntuneWin32AppTest' -Tag 'Unit', 'Public' { ContentPath = $missing InstallCommand = 'setup.exe' } - { Invoke-IntuneWin32AppTest @intuneWin32AppTestSplat } | Should-Throw + { Invoke-IntuneWin32AppTest @intuneWin32AppTestSplat } | + Should-Throw -FullyQualifiedErrorId 'PathNotFound,*' + Should-Invoke Invoke-IntuneDetectionTest -ModuleName IntuneScriptLab -Times 0 -Exactly + } + + It 'refuses -Credential with Context System before anything runs' { + $secure = [securestring]::new() + foreach ($char in 'pw'.ToCharArray()) { $secure.AppendChar($char) } + $intuneWin32AppTestSplat = @{ + DetectionPath = $script:Fixture.Detection + ContentPath = $script:Fixture.Content + InstallCommand = 'setup.exe' + Context = 'System' + Credential = [pscredential]::new('LAB\isl-user', $secure) + } + { Invoke-IntuneWin32AppTest @intuneWin32AppTestSplat } | + Should-Throw -FullyQualifiedErrorId 'CredentialWithSystemContext,*' + Should-Invoke Invoke-IntuneDetectionTest -ModuleName IntuneScriptLab -Times 0 -Exactly } } @@ -557,10 +574,10 @@ Describe 'Invoke-IntuneWin32AppTest' -Tag 'Unit', 'Public' { It 'rejects a related app without a Name or without a detection' { $noName = @{ DetectionPath = $script:Child.Detection } { Invoke-IntuneWin32AppTest @script:ParentSplat -DependsOn $noName } | - Should-Throw -ExceptionMessage '*needs a Name*' + Should-Throw -FullyQualifiedErrorId 'RelatedAppNameMissing,*' -ExceptionMessage '*needs a Name*' $noDetection = @{ Name = 'Old' } { Invoke-IntuneWin32AppTest @script:ParentSplat -Supersedes $noDetection } | - Should-Throw -ExceptionMessage '*Old needs a DetectionPath*' + Should-Throw -FullyQualifiedErrorId 'RelatedAppDetectionMissing,*' } } @@ -596,5 +613,34 @@ Describe 'Invoke-IntuneWin32AppTest' -Tag 'Unit', 'Public' { $result.Status | Should-Be 'TimedOut' $result.Install | Should-BeNull } + + It 'ends without running the command when a detection cannot be run' { + # With nothing where the detection result should be, an uninstall read the app as + # detected and ran its command + Mock Invoke-IntuneDetectionTest -ModuleName IntuneScriptLab { throw 'The host could not be started.' } + $intuneWin32AppTestSplat = @{ + DetectionPath = $script:Fixture.Detection + ContentPath = $script:Fixture.Content + UninstallCommand = 'setup.exe /uninstall' + Intent = 'Uninstall' + } + + { Invoke-IntuneWin32AppTest @intuneWin32AppTestSplat } | + Should-Throw -ExceptionMessage '*host could not be started*' + Should-Invoke Invoke-IslProcess -ModuleName IntuneScriptLab -Times 0 -Exactly + } + + It 'ends without the post-detection when the command cannot be started' { + Mock Invoke-IslProcess -ModuleName IntuneScriptLab { throw 'cmd.exe could not be started.' } + $intuneWin32AppTestSplat = @{ + DetectionPath = $script:Fixture.Detection + ContentPath = $script:Fixture.Content + InstallCommand = 'setup.exe' + } + + { Invoke-IntuneWin32AppTest @intuneWin32AppTestSplat } | + Should-Throw -ExceptionMessage '*cmd.exe could not be started*' + Should-Invoke Invoke-IntuneDetectionTest -ModuleName IntuneScriptLab -Times 1 -Exactly + } } } diff --git a/docs/IntuneScriptLab/Invoke-IntuneDetectionTest.md b/docs/IntuneScriptLab/Invoke-IntuneDetectionTest.md index 33dbdd9..7bdffb8 100644 --- a/docs/IntuneScriptLab/Invoke-IntuneDetectionTest.md +++ b/docs/IntuneScriptLab/Invoke-IntuneDetectionTest.md @@ -41,6 +41,11 @@ scheduled task (elevated session required); the default User is quicker and need no rights, but results that depend on the account (HKCU, user profile paths) differ, which Test-IntuneScript's IslContextIssue flags statically. +A script that cannot be run, such as one that is not there or one asked to run in a host this +device does not have, is reported as an error for that script, and the next script from the +pipeline still runs. +-ErrorAction Stop ends the command at that error. + ## EXAMPLES ### EXAMPLE 1 diff --git a/docs/IntuneScriptLab/Invoke-IntunePlatformScriptTest.md b/docs/IntuneScriptLab/Invoke-IntunePlatformScriptTest.md index f2cae0b..2585f68 100644 --- a/docs/IntuneScriptLab/Invoke-IntunePlatformScriptTest.md +++ b/docs/IntuneScriptLab/Invoke-IntunePlatformScriptTest.md @@ -40,6 +40,11 @@ User approximates. -Context System runs it as NT AUTHORITY\SYSTEM in session 0 through a scheduled task (elevated session required). +A script that cannot be run, such as one that is not there or one asked to run in a host this +device does not have, is reported as an error for that script, and the next script from the +pipeline still runs. +-ErrorAction Stop ends the command at that error. + ## EXAMPLES ### EXAMPLE 1 diff --git a/docs/IntuneScriptLab/Invoke-IntuneRemediationTest.md b/docs/IntuneScriptLab/Invoke-IntuneRemediationTest.md index 750b084..a34dfad 100644 --- a/docs/IntuneScriptLab/Invoke-IntuneRemediationTest.md +++ b/docs/IntuneScriptLab/Invoke-IntuneRemediationTest.md @@ -62,6 +62,11 @@ a scheduled task (elevated session required). User, the default here, needs no rights and is right for packages set to run with the signed-in user's credentials. +A run that cannot be started, such as one of a script that is not there, ends the command with +a terminating error: no result is returned, and the runs that would have followed do not start. +A script that calls the command goes on after that error unless the call is inside try or the +script sets $ErrorActionPreference to Stop. + ## EXAMPLES ### EXAMPLE 1 diff --git a/docs/IntuneScriptLab/Invoke-IntuneRequirementTest.md b/docs/IntuneScriptLab/Invoke-IntuneRequirementTest.md index 4bfe8e3..a340df7 100644 --- a/docs/IntuneScriptLab/Invoke-IntuneRequirementTest.md +++ b/docs/IntuneScriptLab/Invoke-IntuneRequirementTest.md @@ -42,6 +42,11 @@ does not parse fails the rule. Under Intune the requirement runs before the install and after the detection has said "not installed"; a rule that fails leaves the app "Not applicable". +A script that cannot be run, such as one that is not there or one asked to run in a host this +device does not have, is reported as an error for that script, and the next script from the +pipeline still runs. +-ErrorAction Stop ends the command at that error. + ## EXAMPLES ### EXAMPLE 1 diff --git a/docs/IntuneScriptLab/Invoke-IntuneWin32AppTest.md b/docs/IntuneScriptLab/Invoke-IntuneWin32AppTest.md index 328ca7e..fe251be 100644 --- a/docs/IntuneScriptLab/Invoke-IntuneWin32AppTest.md +++ b/docs/IntuneScriptLab/Invoke-IntuneWin32AppTest.md @@ -77,6 +77,12 @@ working directory. A `powershell` call on the command line, or inside the batch command line names, adds a warning about the 32-bit host. Soft/hard reboot codes count as success but are reported. +A step that cannot be run, such as a detection script that is not there or a content folder +that cannot be copied, ends the command with a terminating error: no result is returned, and the +install or uninstall and the detections that would have followed do not run. +A script that calls the command goes on after that error unless the call is inside try or the +script sets $ErrorActionPreference to Stop. + ## EXAMPLES ### EXAMPLE 1 diff --git a/en-US/IntuneScriptLab-Help.xml b/en-US/IntuneScriptLab-Help.xml index 457c86c..4d861b8 100644 --- a/en-US/IntuneScriptLab-Help.xml +++ b/en-US/IntuneScriptLab-Help.xml @@ -2791,7 +2791,12 @@ Detection scripts run as SYSTEM under Intune. -Context System reproduces that through a scheduled task (elevated session required); the default User is quicker and needs no rights, but results that depend on the account (HKCU, user profile paths) differ, which -Test-IntuneScript's IslContextIssue flags statically. +Test-IntuneScript's IslContextIssue flags statically. + +A script that cannot be run, such as one that is not there or one asked to run in a host this +device does not have, is reported as an error for that script, and the next script from the +pipeline still runs. +-ErrorAction Stop ends the command at that error. @@ -3054,7 +3059,12 @@ Write-Host, is reported as the result message, so ResultMessage is the full capt The portal's default context for platform scripts is the signed-in user, which is what User approximates. -Context System runs it as NT AUTHORITY\SYSTEM in session 0 -through a scheduled task (elevated session required). +through a scheduled task (elevated session required). + +A script that cannot be run, such as one that is not there or one asked to run in a host this +device does not have, is reported as an error for that script, and the next script from the +pipeline still runs. +-ErrorAction Stop ends the command at that error. @@ -3322,7 +3332,12 @@ Warnings point out output Intune drops. Remediations run as SYSTEM by default under Intune; -Context System reproduces that with a scheduled task (elevated session required). User, the default here, needs no -rights and is right for packages set to run with the signed-in user's credentials. +rights and is right for packages set to run with the signed-in user's credentials. + +A run that cannot be started, such as one of a script that is not there, ends the command with +a terminating error: no result is returned, and the runs that would have followed do not start. +A script that calls the command goes on after that error unless the call is inside try or the +script sets $ErrorActionPreference to Stop. @@ -3589,7 +3604,12 @@ Float, Version, Boolean and DateTime outputs are parsed as that type, and an out does not parse fails the rule. Under Intune the requirement runs before the install and after the detection has said -"not installed"; a rule that fails leaves the app "Not applicable". +"not installed"; a rule that fails leaves the app "Not applicable". + +A script that cannot be run, such as one that is not there or one asked to run in a host this +device does not have, is reported as an error for that script, and the next script from the +pipeline still runs. +-ErrorAction Stop ends the command at that error. @@ -3924,7 +3944,13 @@ command runs through a 32-bit cmd.exe, so a bare `powershell.exe` resolves to th host exactly as it does under the agent's own 32-bit process, with the content copy as working directory. A `powershell` call on the command line, or inside the batch file the command line names, adds a warning about the 32-bit host. -Soft/hard reboot codes count as success but are reported. +Soft/hard reboot codes count as success but are reported. + +A step that cannot be run, such as a detection script that is not there or a content folder +that cannot be copied, ends the command with a terminating error: no result is returned, and the +install or uninstall and the detections that would have followed do not run. +A script that calls the command goes on after that error unless the call is inside try or the +script sets $ErrorActionPreference to Stop. From 5ae4ea03a97707c269d68d36e7488f707513aa5a Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:55:20 -0800 Subject: [PATCH 2/3] fix(harness): put the reason first when icacls refuses a grant 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. --- Private/Grant-IslFolderAccess.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Private/Grant-IslFolderAccess.ps1 b/Private/Grant-IslFolderAccess.ps1 index 2eb7cc7..a69c00f 100644 --- a/Private/Grant-IslFolderAccess.ps1 +++ b/Private/Grant-IslFolderAccess.ps1 @@ -46,7 +46,8 @@ function Grant-IslFolderAccess { } if ($result.ExitCode -ne 0) { - $output = @($result.StdOut, $result.StdErr | Where-Object { $_ }) -join ' ' + # icacls writes the reason to its error stream and a count of files to its output + $output = @($result.StdErr, $result.StdOut | Where-Object { $_ }) -join ' ' $recordSplat = @{ Message = "Could not grant $Account access to ${Path}: $output" ErrorId = 'FolderAccessNotGranted' From 8a4dc4a6bc472f1c05c64edfae0605eb72562625 Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:00:59 -0800 Subject: [PATCH 3/3] test(harness): keep an assertion within the line limit 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. --- Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 b/Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 index df4c09f..bb65260 100644 --- a/Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 +++ b/Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 @@ -60,8 +60,12 @@ Describe 'Invoke-IntuneWin32AppTest' -Tag 'Unit', 'Public' { It 'needs a detection script or detection rules, the content folder and the intent command' { $command = Get-Command Invoke-IntuneWin32AppTest $command.Parameters['ContentPath'].Attributes.Mandatory | Should-ContainCollection $true + $missingDetection = @{ + FullyQualifiedErrorId = 'DetectionMissing,*' + ExceptionMessage = '*-DetectionPath*-DetectionRule*' + } { Invoke-IntuneWin32AppTest -ContentPath $script:Fixture.Content -InstallCommand 'setup.exe' } | - Should-Throw -FullyQualifiedErrorId 'DetectionMissing,*' -ExceptionMessage '*-DetectionPath*-DetectionRule*' + Should-Throw @missingDetection $intuneWin32AppTestSplat = @{ DetectionPath = $script:Fixture.Detection ContentPath = $script:Fixture.Content