Skip to content
Merged
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
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,19 @@ entries are carried over from the manifest's release notes.
without the key.
- CI installs Pester 6.2.0 and PSScriptAnalyzer 1.25.0 exactly, where it took any Pester 6 from
6.2.0 on and the newest PSScriptAnalyzer.
- `Get-IntuneAgentLog`, `Get-IntuneAgentTimeline` and `Export-IntuneAgentDiagnostic` end on a
failure with a terminating error raised the way a compiled cmdlet raises one, where they used
`throw`. Each failure has an ID of its own in `FullyQualifiedErrorId`: `UnknownAgentLogEvent`,
`CmTraceTimestampInvalid`, `DiagnosticPackageExists`. **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. The other commands still use `throw`.
- `Get-IntuneAgentLog` reports a path that does not exist, and a log it cannot read or parse, as
an error for that one item and goes on with the others, where the first such item ended the
command. The same holds for `Get-IntuneAgentTimeline` and `Export-IntuneAgentDiagnostic`, which
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 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 Down
20 changes: 20 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,26 @@ The loader fails the import when `Private`, `Private/Rules` or `Public` is missi
them fails to load. A file that does not parse used to leave the module imported without its
commands.

### A call to a function that can fail sits inside `try` with a `catch`

A function that ends with `$PSCmdlet.ThrowTerminatingError()` ends only itself. The module function
that called it carries on at its next statement with nothing where the result should be, unless the
call is inside a `try` that has a `catch`; a `try` with only a `finally`, a nested helper and a
pipeline do not stop it. A `throw` ended every function above it, which is what the callers were
written for. The module is moving from `throw` to `ThrowTerminatingError` one area at a time (#64),
callers first: the caller gets `try { ... } catch { $PSCmdlet.ThrowTerminatingError($_) }`, then the
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
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
it an ID and a category. That function must not fail: it is called in the argument of
`ThrowTerminatingError`, and an error there would end only that statement.

### A nested function returning `@()` hands the caller `$null`

Several public commands use nested helper functions. PowerShell unrolls an empty array on the
Expand Down
27 changes: 20 additions & 7 deletions Private/ConvertFrom-IslCmTraceLog.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,21 @@ function ConvertFrom-IslCmTraceLog {
[string[]]$Contains
)

$file = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath
$stream = [System.IO.File]::Open($file, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read,
[System.IO.FileShare]::ReadWrite)
# A log that is not there or cannot be read ends the function. The caller decides what that
# means for its own work
$stream = $null
try {
$file = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath
$stream = [System.IO.File]::Open($file, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read,
[System.IO.FileShare]::ReadWrite)
$reader = [System.IO.StreamReader]::new($stream, [System.Text.Encoding]::UTF8, $true)
$text = $reader.ReadToEnd()
}
finally {
$stream.Dispose()
} catch {
$PSCmdlet.ThrowTerminatingError($_)
} finally {
if ($null -ne $stream) {
$stream.Dispose()
}
}

$levels = @{ '1' = 'Information'; '2' = 'Warning'; '3' = 'Error' }
Expand Down Expand Up @@ -135,7 +141,14 @@ function ConvertFrom-IslCmTraceLog {
$time = [datetime]::MinValue
$stamp = "$($groups['date'].Value) $timeText"
if (-not [datetime]::TryParseExact($stamp, $timeFormat, $invariant, $noStyle, [ref]$time)) {
throw "Not a CMTrace timestamp: $stamp ($file)"
$recordSplat = @{
Message = "Not a CMTrace timestamp: $stamp ($file)"
ErrorId = 'CmTraceTimestampInvalid'
Category = [System.Management.Automation.ErrorCategory]::InvalidData
TargetObject = $file
ExceptionType = [System.FormatException]
}
$PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat))
}
if ($hasAfter -and $time -lt $After) { continue }
if ($hasBefore -and $time -ge $Before) { continue }
Expand Down
11 changes: 10 additions & 1 deletion Private/ConvertTo-IslCmTraceTime.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,16 @@ function ConvertTo-IslCmTraceTime {
$value = [datetime]::MinValue
$parsed = [datetime]::TryParseExact("$Date $plain", $script:IslCmTraceTimeFormat,
[cultureinfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$value)
if (-not $parsed) { throw "Not a CMTrace timestamp: date=$Date time=$Time" }
if (-not $parsed) {
$recordSplat = @{
Message = "Not a CMTrace timestamp: date=$Date time=$Time"
ErrorId = 'CmTraceTimestampInvalid'
Category = [System.Management.Automation.ErrorCategory]::InvalidData
TargetObject = "$Date $Time"
ExceptionType = [System.FormatException]
}
$PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat))
}
$value
}

Expand Down
96 changes: 96 additions & 0 deletions Private/New-IslErrorRecord.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
function New-IslErrorRecord {
<#
.SYNOPSIS
Builds the error record a function ends with.

.DESCRIPTION
A failure the module detects itself is raised with $PSCmdlet.ThrowTerminatingError() and an
error record that has an ID and a category of its own, so that a caller can tell one failure
from another without matching the message. This function builds that record: the exception is
of the type named, carries the message, and wraps the error that caused it when there is one.

The record is returned, not raised. The function that detected the failure raises it, so that
the error names that function.

The function does not fail for any message, ID or type. It is called in the argument of
ThrowTerminatingError, and an error raised here would end only that statement: the calling
function would go on as if it had detected nothing. An exception type that cannot be built
from a message and an inner exception is therefore replaced by InvalidOperationException.

.PARAMETER Message
What failed and, where the caller can act on it, what to do.

.PARAMETER ErrorId
The ID of this failure, in PascalCase and without spaces. It is the first part of the
FullyQualifiedErrorId; PowerShell adds the name of the function that raises the record.

.PARAMETER Category
The category of the error.

.PARAMETER TargetObject
What the function was working on when it failed, such as a path or a name.

.PARAMETER ExceptionType
The type of the exception, one that has a constructor taking a message and an inner
exception. The default is System.InvalidOperationException.

.PARAMETER InnerException
The exception that caused the failure, kept as the inner exception.

.EXAMPLE
$record = New-IslErrorRecord -Message "$Path exists; use -Force" -ErrorId 'PathExists' -Category ResourceExists
$PSCmdlet.ThrowTerminatingError($record)

Ends the calling function with an error whose ID starts with PathExists.

.EXAMPLE
$recordSplat = @{ Message = 'No such event'; ErrorId = 'UnknownEvent'; Category = 'InvalidArgument' }
# The value of the bad argument is the target, and the exception says that it was an argument
New-IslErrorRecord @recordSplat -TargetObject $name -ExceptionType ([System.ArgumentException])

A record for a bad argument.

.INPUTS
None.

.OUTPUTS
System.Management.Automation.ErrorRecord.
#>
[CmdletBinding()]
[OutputType([System.Management.Automation.ErrorRecord])]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',
Justification = 'Builds an error record and changes nothing.')]
param(
[Parameter(Mandatory)]
[string]$Message,

[Parameter(Mandatory)]
[string]$ErrorId,

[Parameter(Mandatory)]
[System.Management.Automation.ErrorCategory]$Category,

[Parameter()]
[AllowNull()]
[object]$TargetObject,

[Parameter()]
[type]$ExceptionType = [System.InvalidOperationException],

[Parameter()]
[System.Exception]$InnerException
)

$exception = $null
try {
$exception = $ExceptionType::new($Message, $InnerException) -as [System.Exception]
} catch {
# The type has no such constructor. The record is still built: see the description
Write-Debug "No $($ExceptionType.FullName) could be built for error $ErrorId."

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

An earlier form of this function validated the ID with a pattern and ended with an error for a type it could not build. Both made it possible for the function to fail in the argument of ThrowTerminatingError, which ends that statement only: the caller would have gone on past the failure it had just detected. So it accepts anything and falls back to InvalidOperationException. The typo that validation would have caught is caught by the tests that assert each ID.

}
if ($null -eq $exception) {
$exception = [System.InvalidOperationException]::new($Message, $InnerException)
}

[System.Management.Automation.ErrorRecord]::new($exception, $ErrorId, $Category, $TargetObject)
}
13 changes: 12 additions & 1 deletion Public/Export-IntuneAgentDiagnostic.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,14 @@ function Export-IntuneAgentDiagnostic {
if ([System.IO.Path]::GetExtension($Path) -ne '.zip') { $Path = "$Path.zip" }
$zip = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
if ((Test-Path -LiteralPath $zip) -and -not $Force) {
throw "$zip exists; use -Force to overwrite it"
$recordSplat = @{
Message = "$zip exists; use -Force to overwrite it"
ErrorId = 'DiagnosticPackageExists'
Category = [System.Management.Automation.ErrorCategory]::ResourceExists
TargetObject = $zip
ExceptionType = [System.IO.IOException]
}
$PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat))
}
if (-not $LogPath) {
$programData = if ($env:ProgramData) { $env:ProgramData } else { 'C:\ProgramData' }
Expand Down Expand Up @@ -186,6 +193,10 @@ function Export-IntuneAgentDiagnostic {
}
$entryCount = Compress-Staging -Folder $staging -Destination $zip
}
catch {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

The try had only a finally. A terminating error raised by a function called inside it, such as the read of a log with a bad timestamp for the timeline, ended that one statement, and the command went on to write the manifest and the zip. With the catch the command ends, and the finally still removes the staging folder. Measured from a script without try: no zip is written, and an existing one is left as it was.

# Whatever failed, the package is not complete: the command ends without a result
$PSCmdlet.ThrowTerminatingError($_)
}
finally {
Remove-Item -LiteralPath $staging -Recurse -Force -ErrorAction SilentlyContinue
}
Expand Down
37 changes: 32 additions & 5 deletions Public/Get-IntuneAgentLog.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,14 @@ function Get-IntuneAgentLog {
$knownEvents = @($script:IslAgentLogEvents | ForEach-Object { $_.Event })
foreach ($name in $EventName) {
if ($name -notin $knownEvents) {
throw "Unknown event '$name'. Get-IntuneAgentLog -ListEvent shows the names"
$recordSplat = @{
Message = "Unknown event '$name'. Get-IntuneAgentLog -ListEvent shows the names"
ErrorId = 'UnknownAgentLogEvent'
Category = [System.Management.Automation.ErrorCategory]::InvalidArgument
TargetObject = $name
ExceptionType = [System.ArgumentException]
}
$PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat))
}
}

Expand All @@ -72,18 +79,31 @@ function Get-IntuneAgentLog {
AgentExecutor = 'AgentExecutor*.log'
All = '*.log'
}
# Each path is one item of the input. One that cannot be resolved is reported, and the others
# are still read
$unresolved = 0
$files = foreach ($item in $Path) {
$resolved = (Resolve-Path -LiteralPath $item -ErrorAction Stop).ProviderPath
try {
$resolved = (Resolve-Path -LiteralPath $item -ErrorAction Stop).ProviderPath
} catch {
$unresolved++
$PSCmdlet.WriteError($_)
continue
}
if (Test-Path -LiteralPath $resolved -PathType Container) {
foreach ($name in $Log) {
Get-ChildItem -LiteralPath $resolved -Filter $filters[$name] -File | ForEach-Object { $_.FullName }
Get-ChildItem -LiteralPath $resolved -Filter $filters[$name] -File |
ForEach-Object { $_.FullName }
}
}
else { $resolved }
}
$files = @($files | Sort-Object -Unique)
if (-not $files) {
Write-Warning "No log files under $($Path -join ', ')"
# When no path could be resolved, the errors have said so already
if ($unresolved -lt @($Path).Count) {
Write-Warning "No log files under $($Path -join ', ')"
}
return
}

Expand All @@ -110,7 +130,14 @@ function Get-IntuneAgentLog {
continue
}
Write-Verbose "Reading $file"
$kept = @(ConvertFrom-IslCmTraceLog -Path $file @parseSplat)
try {
$kept = @(ConvertFrom-IslCmTraceLog -Path $file @parseSplat)
} catch {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

A log that cannot be parsed still ends the whole command, as the throw in the parser did. ERR-13 would report the file with WriteError and go on with the other logs. That would be a change of behaviour of its own, so it is left as a question in the description.

# A log that cannot be read or parsed is one item of the input too: it is reported
# and gives no entries, and the other logs are still read
$PSCmdlet.WriteError($_)
continue
}
if (-not $kept.Count) { continue }
$classified = @(Get-IslAgentLogEvent -Message @($kept | ForEach-Object { $_.Message }))
for ($index = 0; $index -lt $kept.Count; $index++) {
Expand Down
8 changes: 7 additions & 1 deletion Public/Get-IntuneAgentTimeline.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ function Get-IntuneAgentTimeline {
if ($Id) { $logSplat.Id = $Id }
if ($PSBoundParameters.ContainsKey('After')) { $logSplat.After = $After }
if ($PSBoundParameters.ContainsKey('Before')) { $logSplat.Before = $Before }
$entries = @(Get-IntuneAgentLog @logSplat)
# A failure of the read ends this command too: without the catch it would end only this
# statement, and the timelines would be built from nothing
try {
$entries = @(Get-IntuneAgentLog @logSplat)
} catch {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

This guard changes nothing a test of behaviour can see. Without it the command goes on with no entries and returns no timelines, which is also what it returns when it stops here; the 11 tests of this command passed with the guard removed. It is here because the rule has to hold everywhere to hold where it matters, and Module.ErrorFlow.Tests.ps1 is what fails when it is missing.

$PSCmdlet.ThrowTerminatingError($_)
}

# App names travel in the policy list the agent logs; nothing else names a policy
$names = @{}
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,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. |
| 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
Expand Down
Loading