Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
20 changes: 16 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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
Expand Down
36 changes: 30 additions & 6 deletions Private/Get-IslHostPath.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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'
}
Expand All @@ -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'
Expand Down
10 changes: 6 additions & 4 deletions Private/Get-IslOemEncoding.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
24 changes: 19 additions & 5 deletions Private/Grant-IslFolderAccess.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,24 @@ 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) {
# 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'
Category = [System.Management.Automation.ErrorCategory]::PermissionDenied

@fadwen fadwen Nov 24, 2026 •

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

The message is the one the function had, so that the two existing tests of it, under error action Continue and Stop, hold as they were. icacls.exe writes its reason to the error stream ("No mapping between account names and security IDs was done.") and a count of files to the output stream, so the message takes both, the reason first.

TargetObject = $Path
}
$PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat))
}
}
75 changes: 75 additions & 0 deletions Private/Invoke-IslNativeCommand.ps1
Original file line number Diff line number Diff line change
@@ -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
}
}
73 changes: 55 additions & 18 deletions Private/Invoke-IslProcess.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

A decision more than a conversion. Before, a Stop-IslProcessTree that could not start taskkill.exe ended only itself, and the run returned TimedOut with no output while the process went on. The alternative was to keep the TimedOut result and add a warning; an error was chosen because the result would claim a cleanup that did not happen.

# 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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

This catch also receives the ScheduledTaskNotStarted record that is raised a few lines up inside the same try, and passes it on unchanged. The test "reports a logon the scheduler refuses" asserts that the ID survives.

$PSCmdlet.ThrowTerminatingError($_)
}
finally {
# Of the task cmdlets used here only this one has -WhatIf. Under a preference the
Expand Down
Loading