diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d2e9b3..765a244 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/CLAUDE.md b/CLAUDE.md index d49dfa0..b71da1e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 diff --git a/Private/ConvertFrom-IslCmTraceLog.ps1 b/Private/ConvertFrom-IslCmTraceLog.ps1 index 87db2aa..61b3177 100644 --- a/Private/ConvertFrom-IslCmTraceLog.ps1 +++ b/Private/ConvertFrom-IslCmTraceLog.ps1 @@ -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' } @@ -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 } diff --git a/Private/ConvertTo-IslCmTraceTime.ps1 b/Private/ConvertTo-IslCmTraceTime.ps1 index d573c6b..0d5cb4f 100644 --- a/Private/ConvertTo-IslCmTraceTime.ps1 +++ b/Private/ConvertTo-IslCmTraceTime.ps1 @@ -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 } diff --git a/Private/New-IslErrorRecord.ps1 b/Private/New-IslErrorRecord.ps1 new file mode 100644 index 0000000..8b99375 --- /dev/null +++ b/Private/New-IslErrorRecord.ps1 @@ -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." + } + if ($null -eq $exception) { + $exception = [System.InvalidOperationException]::new($Message, $InnerException) + } + + [System.Management.Automation.ErrorRecord]::new($exception, $ErrorId, $Category, $TargetObject) +} diff --git a/Public/Export-IntuneAgentDiagnostic.ps1 b/Public/Export-IntuneAgentDiagnostic.ps1 index 80146a7..9d946ac 100644 --- a/Public/Export-IntuneAgentDiagnostic.ps1 +++ b/Public/Export-IntuneAgentDiagnostic.ps1 @@ -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' } @@ -186,6 +193,10 @@ function Export-IntuneAgentDiagnostic { } $entryCount = Compress-Staging -Folder $staging -Destination $zip } + catch { + # Whatever failed, the package is not complete: the command ends without a result + $PSCmdlet.ThrowTerminatingError($_) + } finally { Remove-Item -LiteralPath $staging -Recurse -Force -ErrorAction SilentlyContinue } diff --git a/Public/Get-IntuneAgentLog.ps1 b/Public/Get-IntuneAgentLog.ps1 index f572748..c97b1fd 100644 --- a/Public/Get-IntuneAgentLog.ps1 +++ b/Public/Get-IntuneAgentLog.ps1 @@ -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)) } } @@ -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 } @@ -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 { + # 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++) { diff --git a/Public/Get-IntuneAgentTimeline.ps1 b/Public/Get-IntuneAgentTimeline.ps1 index 60fe771..b938e7e 100644 --- a/Public/Get-IntuneAgentTimeline.ps1 +++ b/Public/Get-IntuneAgentTimeline.ps1 @@ -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 { + $PSCmdlet.ThrowTerminatingError($_) + } # App names travel in the policy list the agent logs; nothing else names a policy $names = @{} diff --git a/README.md b/README.md index be2b8c8..45b36f0 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/Tests/TestHelpers/TestHelpers.ps1 b/Tests/TestHelpers/TestHelpers.ps1 index aa89505..c0c577a 100644 --- a/Tests/TestHelpers/TestHelpers.ps1 +++ b/Tests/TestHelpers/TestHelpers.ps1 @@ -182,3 +182,96 @@ function ConvertTo-FakeRunResult { } [pscustomobject]$result } + + +function Invoke-CallerScript { + <# + .SYNOPSIS + Runs statements as a script in a new process that has no try and the default error preference. + + .DESCRIPTION + A command that ends with a terminating error ends only itself for such a caller, and the test + wants to know what the command did before it ended: did it stop where it failed, or did it go + on with nothing where a result should be? Should-Throw cannot tell. It runs the call inside + a try, and with a try anywhere above it every error travels all the way up. + + The script imports the module, runs the statements, and then writes the IDs of every error + the session recorded, oldest first. A command that stopped where it failed leaves the IDs of + that one failure. One that went on leaves the errors of the statements after it as well. + + .PARAMETER Statement + The statements of the script, one to a line, after the import of the module. + + .PARAMETER Manifest + The module manifest to import. The default is the one of this repository. + + .EXAMPLE + Invoke-CallerScript -Statement "Get-IntuneAgentTimeline -Path 'C:\nowhere'" + + Runs the command against a folder that is not there and returns what the script wrote, the + IDs of the errors and whether the script reached its end. + + .INPUTS + None. + + .OUTPUTS + System.Management.Automation.PSCustomObject. Output, ErrorId, ReachedEnd and ExitCode. + #> + [CmdletBinding()] + [OutputType([System.Management.Automation.PSCustomObject])] + param( + [Parameter(Mandatory)] + [string[]]$Statement, + + [Parameter()] + [string]$Manifest + ) + + if (-not $Manifest) { + $repositoryRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) + $Manifest = Join-Path $repositoryRoot 'IntuneScriptLab.psd1' + } + $folder = Join-Path $TestDrive "caller-$([guid]::NewGuid().ToString('N'))" + $null = New-Item -ItemType Directory -Path $folder -Force + $script = Join-Path $folder 'caller.ps1' + $marker = 'CALLER-SCRIPT-' + $lines = @( + "Import-Module '$Manifest'" + $Statement + # Oldest first; the session lists its errors newest first + "`$ids = @(`$Error | ForEach-Object { `$_.FullyQualifiedErrorId }); [array]::Reverse(`$ids)" + "'${marker}ERRORS:' + (`$ids -join '|')" + "'${marker}END'" + ) + [System.IO.File]::WriteAllLines($script, [string[]]$lines, [System.Text.UTF8Encoding]::new($true)) + + # Files, not the pipeline: Windows PowerShell turns what a native command writes to a redirected + # error stream into error records, and under a CI step's error preference those end the test + $outFile = Join-Path $folder 'out.txt' + $errFile = Join-Path $folder 'err.txt' + $startParameters = @{ + FilePath = (Get-Process -Id $PID).Path + ArgumentList = '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', "`"$script`"" + RedirectStandardOutput = $outFile + RedirectStandardError = $errFile + Wait = $true + PassThru = $true + } + # Start-Process has -WindowStyle on Windows only + if ($PSVersionTable.PSVersion.Major -lt 6 -or $IsWindows) { + $startParameters['WindowStyle'] = 'Hidden' + } + $process = Start-Process @startParameters + $written = @([System.IO.File]::ReadAllLines($outFile)) + $errorLine = @($written | Where-Object { $_.StartsWith("${marker}ERRORS:") }) | Select-Object -Last 1 + $errorIds = @() + if ($errorLine) { + $errorIds = @($errorLine.Substring("${marker}ERRORS:".Length) -split '\|' | Where-Object { $_ }) + } + [pscustomobject]@{ + Output = @($written | Where-Object { -not $_.StartsWith($marker) }) + ErrorId = $errorIds + ReachedEnd = $written -contains "${marker}END" + ExitCode = $process.ExitCode + } +} diff --git a/Tests/Unit/Module.ErrorFlow.Tests.ps1 b/Tests/Unit/Module.ErrorFlow.Tests.ps1 new file mode 100644 index 0000000..eb16a34 --- /dev/null +++ b/Tests/Unit/Module.ErrorFlow.Tests.ps1 @@ -0,0 +1,244 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + How a failure travels through the module, checked on the syntax trees of its functions. + + A function that ends with $PSCmdlet.ThrowTerminatingError() ends only itself. The function that + called it carries on at its next statement, with nothing where the result should be, unless the + call sits inside a try that has a catch. A throw is different: it ends every function above it. + No test of behaviour shows the difference reliably, because a caller that goes on with nothing + often returns nothing as well, and Should-Throw runs its call inside a try, where every error + travels all the way up. So the rule is checked as a rule: no call to a function that can end + with ThrowTerminatingError outside a try with a catch. + + The module is being moved from throw to ThrowTerminatingError one area at a time (#64). The + calls that still rely on a throw in the function they call are listed below, and the list has + to match what is in the code exactly, so it shrinks with every area that is converted. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) + + function Get-ErrorFlowCall { + <# + .SYNOPSIS + Lists the calls between module functions that are not inside a try with a catch. + + .DESCRIPTION + Every function of Public, Private and Private\Rules is a node, and so is every function + nested in one of them. A node can fail when it has a throw outside a try with a catch, + when it calls ThrowTerminatingError, or when it makes an unguarded call to a node that + can fail. Returns one object for each unguarded call to a node that can fail, with + Caller, Callee, Call (both names) and EndsQuietly: whether the callee ends with + ThrowTerminatingError, which lets the caller carry on. + + .PARAMETER ModuleRoot + The folder that holds Public and Private. + + .EXAMPLE + Get-ErrorFlowCall -ModuleRoot $script:ModuleRoot + + The unguarded calls in the module. + + .INPUTS + None. + + .OUTPUTS + System.Management.Automation.PSCustomObject. + #> + [CmdletBinding()] + [OutputType([System.Management.Automation.PSCustomObject])] + param( + [Parameter(Mandatory)] + [string]$ModuleRoot + ) + + $functionType = [System.Management.Automation.Language.FunctionDefinitionAst] + $nodes = @{} + $topLevelOf = @{} + foreach ($folder in 'Public', 'Private', 'Private\Rules') { + $folderPath = Join-Path -Path $ModuleRoot -ChildPath $folder + foreach ($file in Get-ChildItem -LiteralPath $folderPath -Filter '*.ps1' -File) { + $tree = [System.Management.Automation.Language.Parser]::ParseFile( + $file.FullName, [ref]$null, [ref]$null) + foreach ($statement in $tree.EndBlock.Statements) { + if ($statement -isnot $functionType) { + continue + } + $nodes[$statement.Name] = $statement + $topLevelOf[$statement] = $statement.Name + $nested = $statement.FindAll({ param($node) $node -is $functionType }, $true) | + Where-Object { $_ -ne $statement } + foreach ($definition in $nested) { + $nodes["$($statement.Name)::$($definition.Name)"] = $definition + $topLevelOf[$definition] = $statement.Name + } + } + } + } + + # The function a node of the tree belongs to, and whether a try with a catch stands + # between the node and that function + $describe = { + param($Node) + $guarded = $false + $child = $Node + $current = $Node.Parent + while ($null -ne $current -and $current -isnot $functionType) { + $isTry = $current -is [System.Management.Automation.Language.TryStatementAst] + if ($isTry -and $current.CatchClauses.Count -gt 0 -and $current.Body -eq $child) { + $guarded = $true + } + $child = $current + $current = $current.Parent + } + [pscustomobject]@{ Owner = $current; Guarded = $guarded } + } + + $canFail = @{} + $endsQuietly = @{} + $calls = [System.Collections.Generic.List[object]]::new() + foreach ($name in $nodes.Keys) { + $definition = $nodes[$name] + $topLevel = $topLevelOf[$definition] + foreach ($node in $definition.FindAll({ $true }, $true)) { + if ($node -is [System.Management.Automation.Language.ThrowStatementAst]) { + $place = & $describe $node + if ($place.Owner -eq $definition -and -not $place.Guarded) { + $canFail[$name] = $true + } + } elseif ($node -is [System.Management.Automation.Language.InvokeMemberExpressionAst]) { + $isTerminating = "$($node.Member.Extent.Text)" -eq 'ThrowTerminatingError' + if ($isTerminating -and (& $describe $node).Owner -eq $definition) { + $canFail[$name] = $true + $endsQuietly[$name] = $true + } + } elseif ($node -is [System.Management.Automation.Language.CommandAst]) { + $place = & $describe $node + if ($place.Owner -ne $definition) { + continue + } + $commandName = $node.GetCommandName() + $callee = $null + if ($commandName -and $nodes.ContainsKey("${topLevel}::$commandName")) { + $callee = "${topLevel}::$commandName" + } elseif ($commandName -and $nodes.ContainsKey($commandName)) { + $callee = $commandName + } + if ($null -ne $callee -and $callee -ne $name) { + $calls.Add([pscustomobject]@{ Caller = $name; Callee = $callee; Guarded = $place.Guarded }) + } + } + } + } + + # A function that makes an unguarded call to one that can fail can fail itself + do { + $changed = $false + foreach ($call in $calls) { + if (-not $call.Guarded -and $canFail.ContainsKey($call.Callee) -and + -not $canFail.ContainsKey($call.Caller)) { + $canFail[$call.Caller] = $true + $changed = $true + } + } + } while ($changed) + + $seen = @{} + foreach ($call in $calls) { + $text = "$($call.Caller) -> $($call.Callee)" + if ($call.Guarded -or -not $canFail.ContainsKey($call.Callee) -or $seen.ContainsKey($text)) { + continue + } + $seen[$text] = $true + [pscustomobject]@{ + Caller = $call.Caller + Callee = $call.Callee + Call = $text + EndsQuietly = $endsQuietly.ContainsKey($call.Callee) + } + } + } + + $script:Unguarded = @(Get-ErrorFlowCall -ModuleRoot $script:ModuleRoot) +} + +Describe 'How a failure travels through the module' -Tag 'Unit', 'Contract' { + + It 'finds the module''s functions and the calls between them' { + # Guards the two tests below against an analysis that found nothing to check + $script:Unguarded.Count | Should-BeGreaterThan 0 + @($script:Unguarded | Where-Object { $_.Caller -eq 'Get-IntuneAgentTimeline' }) | + Should-BeCollection -Count 0 + } + + 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' + ) + $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 @() + } + + It 'lists every call that still relies on a throw in the function it calls, and no other' { + # Not yet converted (#64). A line goes when its caller gets the try and the catch; a new + # line is a call that was added without them + $pending = @( + 'Assert-BeIntuneApplicable -> Test-IslPesterAssertionSupport' + 'Assert-BeIntuneDetected -> Test-IslPesterAssertionSupport' + 'Assert-HaveIntuneRunState -> Test-IslPesterAssertionSupport' + 'Assert-HaveIntuneStatus -> Test-IslPesterAssertionSupport' + 'Assert-NotBeIntuneApplicable -> Test-IslPesterAssertionSupport' + 'Assert-NotBeIntuneDetected -> Test-IslPesterAssertionSupport' + 'Assert-PassIntuneAnalysis -> Test-IntuneScript' + 'Assert-PassIntuneAnalysis -> Test-IslPesterAssertionSupport' + 'Compare-IntuneDeployedScript -> Compare-IntuneDeployedScript::Compare-Role' + 'Compare-IntuneDeployedScript -> Compare-IntuneDeployedScript::Get-WantedPolicy' + 'Compare-IntuneDeployedScript -> Invoke-IslGraphRequest' + 'Compare-IntuneDeployedScript::Compare-Role -> Compare-IntuneDeployedScript::Compare-Setting' + 'Compare-IntuneDeployedScript::Compare-Setting -> Compare-IntuneDeployedScript::Get-LocalSetting' + 'Compare-IntuneDeployedScript::Get-LocalSetting -> Get-IslSetting' + 'Compare-IntuneDeployedScript::Get-WantedPolicy -> Invoke-IslGraphRequest' + 'Get-IntuneScriptHealth -> Compare-IntuneDeployedScript' + 'Get-IntuneScriptHealth -> Get-IntuneScriptHealth::Get-WantedPolicy' + 'Get-IntuneScriptHealth -> Invoke-IslGraphRequest' + 'Get-IntuneScriptHealth -> Test-IntuneDeployedScript' + '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' + 'Test-IntuneDeployedScript -> Test-IntuneDeployedScript::Get-WantedPolicy' + 'Test-IntuneDeployedScript -> Test-IntuneDeployedScript::Test-PolicyScript' + 'Test-IntuneDeployedScript::Get-WantedPolicy -> Invoke-IslGraphRequest' + 'Test-IntuneDeployedScript::Test-PolicyScript -> Test-IntuneScript' + 'Test-IntuneScript -> Get-IslSetting' + 'Test-IntuneWin32Requirement -> Get-IslWindowsReleaseBuild' + 'Test-IntuneWin32Rule -> ConvertFrom-IslRuleSpec' + ) + $relying = @($script:Unguarded | Where-Object { -not $_.EndsQuietly } | ForEach-Object { $_.Call }) + + @($relying | Where-Object { $_ -notin $pending } | Sort-Object) | Should-BeCollection @() + @($pending | Where-Object { $_ -notin $relying } | Sort-Object) | Should-BeCollection @() + } +} diff --git a/Tests/Unit/Private/ConvertFrom-IslCmTraceLog.Tests.ps1 b/Tests/Unit/Private/ConvertFrom-IslCmTraceLog.Tests.ps1 index 685e7f2..49a951f 100644 --- a/Tests/Unit/Private/ConvertFrom-IslCmTraceLog.Tests.ps1 +++ b/Tests/Unit/Private/ConvertFrom-IslCmTraceLog.Tests.ps1 @@ -121,7 +121,8 @@ Describe 'ConvertFrom-IslCmTraceLog' -Tag 'Unit', 'Private' { ConvertFrom-IslCmTraceLog -Path $Path }) $entries.Count | Should-Be 0 - { InModuleScope IntuneScriptLab { ConvertFrom-IslCmTraceLog -Path 'C:\nowhere\none.log' } } | Should-Throw + { InModuleScope IntuneScriptLab { ConvertFrom-IslCmTraceLog -Path 'C:\nowhere\none.log' } } | + Should-Throw -FullyQualifiedErrorId 'PathNotFound,*' } } @@ -146,6 +147,6 @@ Describe 'ConvertTo-IslCmTraceTime' -Tag 'Unit', 'Private' { { InModuleScope IntuneScriptLab { ConvertTo-IslCmTraceTime -Time 'noon' -Date '9-25-2026' } } | Should-Throw -ExceptionMessage '*Not a CMTrace timestamp*' { InModuleScope IntuneScriptLab { ConvertTo-IslCmTraceTime -Time '09:00:00' -Date '2026-09-25' } } | - Should-Throw + Should-Throw -FullyQualifiedErrorId 'CmTraceTimestampInvalid,ConvertTo-IslCmTraceTime' } } diff --git a/Tests/Unit/Private/New-IslErrorRecord.Tests.ps1 b/Tests/Unit/Private/New-IslErrorRecord.Tests.ps1 new file mode 100644 index 0000000..4a3510d --- /dev/null +++ b/Tests/Unit/Private/New-IslErrorRecord.Tests.ps1 @@ -0,0 +1,108 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The error record a module function ends with: an ID and a category of its own, an exception of + the type named, and the error that caused it kept as the inner exception. +#> + +BeforeAll { + if (-not (Get-Module -Name IntuneScriptLab)) { + $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + Import-Module (Join-Path $moduleRoot 'IntuneScriptLab.psd1') + } +} + +Describe 'New-IslErrorRecord' -Tag 'Unit', 'Private' { + + Context 'Parameter Validation' { + It 'declares as mandatory' -ForEach @( + @{ ParameterName = 'Message'; ParameterType = [string] } + @{ ParameterName = 'ErrorId'; ParameterType = [string] } + @{ ParameterName = 'Category'; ParameterType = [System.Management.Automation.ErrorCategory] } + ) { + InModuleScope IntuneScriptLab -Parameters @{ Name = $ParameterName; Type = $ParameterType } { + Get-Command -Name New-IslErrorRecord | + Should-HaveParameter -ParameterName $Name -Type $Type -Mandatory + } + } + } + + Context 'Core Functionality' { + It 'returns a record with the ID, the category, the target and an InvalidOperationException' { + InModuleScope IntuneScriptLab { + $recordSplat = @{ + Message = 'C:\out.zip exists; use -Force' + ErrorId = 'PathExists' + Category = [System.Management.Automation.ErrorCategory]::ResourceExists + TargetObject = 'C:\out.zip' + } + $record = @(New-IslErrorRecord @recordSplat) + + $record | Should-BeCollection -Count 1 + $record[0] | Should-HaveType ([System.Management.Automation.ErrorRecord]) + $record[0].FullyQualifiedErrorId | Should-Be 'PathExists' + $record[0].CategoryInfo.Category | Should-Be 'ResourceExists' + $record[0].TargetObject | Should-Be 'C:\out.zip' + $record[0].Exception | Should-HaveType ([System.InvalidOperationException]) + $record[0].Exception.Message | Should-Be 'C:\out.zip exists; use -Force' + $record[0].Exception.InnerException | Should-BeNull + } + } + + It 'builds the exception type named and keeps the cause as the inner exception' { + InModuleScope IntuneScriptLab { + $cause = [System.IO.FileNotFoundException]::new('the cause') + $recordSplat = @{ + Message = 'Unknown event' + ErrorId = 'UnknownEvent' + Category = [System.Management.Automation.ErrorCategory]::InvalidArgument + ExceptionType = [System.ArgumentException] + InnerException = $cause + } + $record = New-IslErrorRecord @recordSplat + + $record.Exception | Should-HaveType ([System.ArgumentException]) + $record.Exception.Message | Should-Be 'Unknown event' + [object]::ReferenceEquals($record.Exception.InnerException, $cause) | Should-BeTrue + $record.TargetObject | Should-BeNull + } + } + + It 'gives the error the name of the function that raises it, not its own' { + InModuleScope IntuneScriptLab { + function Get-ProbeFailure { + <# + .SYNOPSIS + Ends with a record from New-IslErrorRecord, as a module function does. + #> + [CmdletBinding()] + param() + $recordSplat = @{ Message = 'probe'; ErrorId = 'ProbeFailed'; Category = 'InvalidOperation' } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) + } + + { Get-ProbeFailure } | Should-Throw -FullyQualifiedErrorId 'ProbeFailed,Get-ProbeFailure' + } + } + } + + Context 'Error Handling' { + It 'still returns a record for a type it cannot build: ' -ForEach @( + # SocketException takes an error code, not a message and a cause + @{ TypeName = 'System.Net.Sockets.SocketException' } + @{ TypeName = 'System.String' } + ) { + # The call sits in the argument of ThrowTerminatingError. An error here would end only + # that statement, and the calling function would go on as if nothing had failed + InModuleScope IntuneScriptLab -Parameters @{ TypeName = $TypeName } { + $recordSplat = @{ Message = 'the message'; ErrorId = 'Any'; Category = 'InvalidOperation' } + $record = @(New-IslErrorRecord @recordSplat -ExceptionType ([type]$TypeName) -ErrorAction Stop) + + $record | Should-BeCollection -Count 1 + $record[0].Exception | Should-HaveType ([System.InvalidOperationException]) + $record[0].Exception.Message | Should-Be 'the message' + $record[0].FullyQualifiedErrorId | Should-Be 'Any' + } + } + } +} diff --git a/Tests/Unit/Public/Export-IntuneAgentDiagnostic.Tests.ps1 b/Tests/Unit/Public/Export-IntuneAgentDiagnostic.Tests.ps1 index 4c4e714..ea50f65 100644 --- a/Tests/Unit/Public/Export-IntuneAgentDiagnostic.Tests.ps1 +++ b/Tests/Unit/Public/Export-IntuneAgentDiagnostic.Tests.ps1 @@ -9,6 +9,7 @@ BeforeAll { $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force + . (Join-Path $script:ModuleRoot 'Tests\TestHelpers\TestHelpers.ps1') Add-Type -AssemblyName System.IO.Compression.FileSystem function script:New-CmTraceLine { @@ -113,6 +114,8 @@ Describe 'Export-IntuneAgentDiagnostic' -Tag 'Unit', 'Public' { $null = Export-IntuneAgentDiagnostic -Path $zip -LogPath $script:Logs -SkipRegistry -SkipTimeline { Export-IntuneAgentDiagnostic -Path $zip -LogPath $script:Logs -SkipRegistry -SkipTimeline } | Should-Throw -ExceptionMessage '*exists; use -Force*' + { Export-IntuneAgentDiagnostic -Path $zip -LogPath $script:Logs -SkipRegistry -SkipTimeline } | + Should-Throw -FullyQualifiedErrorId 'DiagnosticPackageExists,Export-IntuneAgentDiagnostic' $againSplat = @{ Path = $zip; LogPath = $script:Logs; SkipRegistry = $true; SkipTimeline = $true } $again = Export-IntuneAgentDiagnostic @againSplat -Force $again.Timeline | Should-BeFalse @@ -141,4 +144,58 @@ Describe 'Export-IntuneAgentDiagnostic' -Tag 'Unit', 'Public' { Get-ZipEntry -Zip $zip | Should-ContainCollection 'Manifest.txt' } } + + Context 'Error Handling' { + It 'still writes the package when one log cannot be parsed, and reports that log' { + $mixed = Join-Path $TestDrive 'MixedLogs' + Copy-Item -LiteralPath $script:Logs -Destination $mixed -Recurse + $lines = @( + New-CmTraceLine -Time '08:40:13.0000000' -Message 'a good entry' + New-CmTraceLine -Time 'noon' -Message 'an entry whose time is not one' + ) + [System.IO.File]::WriteAllLines((Join-Path $mixed 'AppWorkload.log'), [string[]]$lines) + $zip = Join-Path $TestDrive 'mixed.zip' + + $exportSplat = @{ Path = $zip; LogPath = $mixed; SkipRegistry = $true; ErrorAction = 'Continue' } + $output = Export-IntuneAgentDiagnostic @exportSplat 2>&1 + $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) + $result = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }) + + # The events and the timelines each read the logs, so the log is reported by both + $errors.Count | Should-BeGreaterThan 0 + $errors | Should-All { $_.FullyQualifiedErrorId -like 'CmTraceTimestampInvalid,*' } + $result | Should-BeCollection -Count 1 + $result[0].Path | Should-Be $zip + # The log itself is in the package, which is what a ticket needs most + Get-ZipEntry -Zip $zip | Should-ContainCollection 'Logs/AppWorkload.log' + Get-ZipEntry -Zip $zip | Should-ContainCollection 'Timeline/events.csv' + } + + It 'writes no package and returns nothing when a step fails, for a script without try' { + $existing = Join-Path $TestDrive 'existing.zip' + [System.IO.File]::WriteAllText($existing, 'not a zip') + # A zip cannot be created below a file + $below = Join-Path $existing 'inner.zip' + $logs = $script:Logs + $run = Invoke-CallerScript -Statement @( + "`$first = Export-IntuneAgentDiagnostic -Path '$existing' -LogPath '$logs' -SkipRegistry" + "'existing: ' + [bool]`$first" + "`$second = Export-IntuneAgentDiagnostic -Path '$below' -LogPath '$logs' -SkipRegistry" + "'below: ' + [bool]`$second" + ) + + $run.ReachedEnd | Should-BeTrue + $run.Output | Should-BeCollection -Count 2 + $run.Output[0] | Should-Be 'existing: False' + $run.Output[1] | Should-Be 'below: False' + [System.IO.File]::ReadAllText($existing) | Should-Be 'not a zip' + # A service or a command that is not on this computer is asked for quietly and still + # leaves a record in the session; those are not failures of the command + $failures = @($run.ErrorId | Where-Object { $_ -notlike '*,Microsoft.PowerShell.Commands.*' }) + $failures | Should-BeCollection -Count 2 + $failures[0] | Should-Be 'DiagnosticPackageExists,Export-IntuneAgentDiagnostic' + # The error of .NET, whose ID is the name of its exception + $failures[1] | Should-BeLikeString '*Exception*' + } + } } diff --git a/Tests/Unit/Public/Get-IntuneAgentLog.Tests.ps1 b/Tests/Unit/Public/Get-IntuneAgentLog.Tests.ps1 index de701fc..9d7a208 100644 --- a/Tests/Unit/Public/Get-IntuneAgentLog.Tests.ps1 +++ b/Tests/Unit/Public/Get-IntuneAgentLog.Tests.ps1 @@ -8,6 +8,7 @@ BeforeAll { $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force + . (Join-Path $script:ModuleRoot 'Tests\TestHelpers\TestHelpers.ps1') function script:New-CmTraceLine { param([string]$Message, [string]$Time, [string]$Date = '9-25-2026', [int]$Type = 1, @@ -80,10 +81,21 @@ Describe 'Get-IntuneAgentLog' -Tag 'Unit', 'Public' { It 'rejects an event name that is not in the table, naming the way to list them' { { Get-IntuneAgentLog -Path $script:Logs -EventName Nope } | Should-Throw -ExceptionMessage "*Unknown event 'Nope'*-ListEvent*" + { Get-IntuneAgentLog -Path $script:Logs -EventName Nope } | + Should-Throw -FullyQualifiedErrorId 'UnknownAgentLogEvent,Get-IntuneAgentLog' } - It 'fails for a path that does not exist and warns for a folder with no logs' { - { Get-IntuneAgentLog -Path (Join-Path $TestDrive 'nowhere') } | Should-Throw + It 'reports a path that does not exist and warns for a folder with no logs' { + $nowhere = Join-Path $TestDrive 'nowhere' + $warnings = @() + $logSplat = @{ Path = $nowhere; ErrorAction = 'Continue'; WarningVariable = 'warnings' } + $output = Get-IntuneAgentLog @logSplat 2>&1 3>$null + $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) + $errors | Should-BeCollection -Count 1 + $errors[0].FullyQualifiedErrorId | Should-BeLikeString 'PathNotFound,*' + @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }).Count | Should-Be 0 + # The error has said why there is nothing; the warning about no logs would say it again + $warnings.Count | Should-Be 0 $emptyFolder = Join-Path $TestDrive 'empty' $null = New-Item -ItemType Directory -Path $emptyFolder -Force $warnings = @() @@ -199,4 +211,72 @@ Describe 'Get-IntuneAgentLog' -Tag 'Unit', 'Public' { } } } + + Context 'Error Handling' { + BeforeAll { + # The logs of the fixture without its AgentExecutor.log, and in its place one whose + # second entry has no time + $script:Mixed = Join-Path $TestDrive 'MixedLogs' + Copy-Item -LiteralPath $script:Logs -Destination $script:Mixed -Recurse + $null = Write-TestLog $script:Mixed 'AgentExecutor.log' @( + New-CmTraceLine -Time '08:40:13.0000000' -Message 'a good entry' + New-CmTraceLine -Time 'noon' -Message 'an entry whose time is not one' + ) + $script:Others = 'Agent', 'AppWorkload', 'HealthScripts' + $script:Readable = @(Get-IntuneAgentLog -Path $script:Logs -Log $script:Others).Count + } + + It 'reports a log it cannot parse and still returns the entries of the others' { + $script:Readable | Should-BeGreaterThan 0 + $output = Get-IntuneAgentLog -Path $script:Mixed -ErrorAction Continue 2>&1 + $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) + $entries = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }) + + $errors | Should-BeCollection -Count 1 + $errors[0].FullyQualifiedErrorId | Should-BeLikeString 'CmTraceTimestampInvalid,*' + $entries.Count | Should-Be $script:Readable + # The log that failed gives nothing, not the entries before the one that broke it + @($entries | Where-Object Log -eq 'AgentExecutor').Count | Should-Be 0 + } + + It 'reports a path that does not exist and still reads the other paths' { + $paths = (Join-Path $TestDrive 'nowhere'), $script:Logs + $output = Get-IntuneAgentLog -Path $paths -Log $script:Others -ErrorAction Continue 2>&1 + $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) + + $errors | Should-BeCollection -Count 1 + $errors[0].FullyQualifiedErrorId | Should-BeLikeString 'PathNotFound,*' + @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }).Count | + Should-Be $script:Readable + } + + It 'ends at the first such error when the caller asks it to stop' { + { Get-IntuneAgentLog -Path $script:Mixed -ErrorAction Stop } | + Should-Throw -FullyQualifiedErrorId 'CmTraceTimestampInvalid,*' + { Get-IntuneAgentLog -Path (Join-Path $TestDrive 'nowhere') -ErrorAction Stop } | + Should-Throw -FullyQualifiedErrorId 'PathNotFound,*' + } + + It 'ends on a bad argument and reports a bad log, for a script without try' { + # Should-Throw cannot show what such a caller sees: it calls inside a try, where every + # error travels all the way up. The script here has none + $logs = $script:Logs + $mixed = $script:Mixed + $run = Invoke-CallerScript -Statement @( + "`$unknown = @(Get-IntuneAgentLog -Path '$logs' -EventName Nope)" + "'unknown: ' + `$unknown.Count" + "`$mixed = @(Get-IntuneAgentLog -Path '$mixed')" + "'mixed: ' + `$mixed.Count" + ) + + $run.ReachedEnd | Should-BeTrue + $run.Output | Should-BeCollection -Count 2 + $run.Output[0] | Should-Be 'unknown: 0' + $run.Output[1] | Should-Be "mixed: $($script:Readable)" + # One error for each failure, and none from a statement that ran after one + $run.ErrorId | Should-BeCollection -Count 2 + $run.ErrorId[0] | Should-Be 'UnknownAgentLogEvent,Get-IntuneAgentLog' + $run.ErrorId[1] | Should-BeLikeString 'CmTraceTimestampInvalid,*' + } + } } diff --git a/Tests/Unit/Public/Get-IntuneAgentTimeline.Tests.ps1 b/Tests/Unit/Public/Get-IntuneAgentTimeline.Tests.ps1 index e429444..8473cc3 100644 --- a/Tests/Unit/Public/Get-IntuneAgentTimeline.Tests.ps1 +++ b/Tests/Unit/Public/Get-IntuneAgentTimeline.Tests.ps1 @@ -9,6 +9,7 @@ BeforeAll { $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force + . (Join-Path $script:ModuleRoot 'Tests\TestHelpers\TestHelpers.ps1') function script:New-CmTraceLine { param([string]$Message, [string]$Time, [string]$Date = '9-25-2026', [int]$Type = 1, @@ -180,4 +181,53 @@ Describe 'Get-IntuneAgentTimeline' -Tag 'Unit', 'Public' { @(Get-IntuneAgentTimeline -Path $empty).Count | Should-Be 0 } } + + Context 'Error Handling' { + BeforeAll { + # The logs of the fixture, and one more whose second entry has no time + $script:Mixed = Join-Path $TestDrive 'MixedLogs' + Copy-Item -LiteralPath $script:Logs -Destination $script:Mixed -Recurse + $null = Write-TestLog $script:Mixed 'AgentExecutor.log' @( + New-CmTraceLine -Time '08:40:13.0000000' -Message 'a good entry' + New-CmTraceLine -Time 'noon' -Message 'an entry whose time is not one' + ) + $script:Expected = @(Get-IntuneAgentTimeline -Path $script:Logs).Count + } + + It 'passes on the error of a log that cannot be parsed and builds the timelines of the others' { + $script:Expected | Should-BeGreaterThan 0 + $output = Get-IntuneAgentTimeline -Path $script:Mixed -ErrorAction Continue 2>&1 + $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) + + $errors | Should-BeCollection -Count 1 + $errors[0].FullyQualifiedErrorId | Should-BeLikeString 'CmTraceTimestampInvalid,*' + @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }).Count | + Should-Be $script:Expected + } + + It 'ends with the error of the read when the caller asks it to stop' { + { Get-IntuneAgentTimeline -Path $script:Mixed -ErrorAction Stop } | + Should-Throw -FullyQualifiedErrorId 'CmTraceTimestampInvalid,*' + { Get-IntuneAgentTimeline -Path (Join-Path $TestDrive 'nowhere') -ErrorAction Stop } | + Should-Throw -FullyQualifiedErrorId 'PathNotFound,*' + } + + It 'reports what it could not read and goes on, for a script without try' { + $mixed = $script:Mixed + $run = Invoke-CallerScript -Statement @( + "`$missing = @(Get-IntuneAgentTimeline -Path '$TestDrive\nowhere')" + "'missing: ' + `$missing.Count" + "`$mixed = @(Get-IntuneAgentTimeline -Path '$mixed')" + "'mixed: ' + `$mixed.Count" + ) + + $run.ReachedEnd | Should-BeTrue + $run.Output | Should-BeCollection -Count 2 + $run.Output[0] | Should-Be 'missing: 0' + $run.Output[1] | Should-Be "mixed: $($script:Expected)" + $run.ErrorId | Should-BeCollection -Count 2 + $run.ErrorId[0] | Should-BeLikeString 'PathNotFound,*' + $run.ErrorId[1] | Should-BeLikeString 'CmTraceTimestampInvalid,*' + } + } }