From d4036b5d4e8b047c2293a00e53087801c5a01724 Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:33:21 -0800 Subject: [PATCH 1/4] refactor(helpers): move the log, diagnostic and Graph helpers out The second part of #65. Eight functions nested in Get-IslAgentLogEvent, Export-IntuneAgentDiagnostic and Invoke-IslGraphRequest are private functions in files of their own, advanced functions with full help and output types, taking as parameters what they read from the function around them: - Get-LiteralPrefix -> Get-IslRegexLiteralPrefix - ConvertTo-NamedGroup -> ConvertTo-IslNamedGroupPattern - Write-Section -> Write-IslTextFile, with the staging folder as -Root; it takes no lines as an empty file, as the nested copy did - Copy-SharedFile -> Copy-IslSharedFile - Get-RegistryText -> Get-IslRegistryText - Compress-Staging -> Compress-IslFolder - Get-RetryDelay -> Get-IslGraphRetryDelay - Invoke-Once -> Invoke-IslGraphRequestOnce The three that write files declare SupportsShouldProcess (FUN-30), and the diagnostic export calls them with -WhatIf:$false and -Confirm:$false, as it does every internal operation after its own question. Invoke-IslGraphRequestOnce ends with ThrowTerminatingError where Invoke-Once passed Graph's error on with throw, so no function of the module uses throw any more. Each new function has a test file of its own; the tests of the three callers are unchanged. Refs #65. --- CHANGELOG.md | 3 +- CLAUDE.md | 8 +- Private/Compress-IslFolder.ps1 | 59 +++++++++++++ Private/ConvertTo-IslNamedGroupPattern.ps1 | 66 +++++++++++++++ Private/Copy-IslSharedFile.ps1 | 50 +++++++++++ Private/Get-IslAgentLogEvent.ps1 | 66 ++------------- Private/Get-IslGraphRetryDelay.ps1 | 61 ++++++++++++++ Private/Get-IslRegexLiteralPrefix.ps1 | 56 +++++++++++++ Private/Get-IslRegistryText.ps1 | 60 ++++++++++++++ Private/Invoke-IslGraphRequest.ps1 | 48 +---------- Private/Invoke-IslGraphRequestOnce.ps1 | 54 ++++++++++++ Private/Write-IslTextFile.ps1 | 58 +++++++++++++ Public/Export-IntuneAgentDiagnostic.ps1 | 76 +++-------------- .../Unit/Private/Compress-IslFolder.Tests.ps1 | 52 ++++++++++++ .../ConvertTo-IslNamedGroupPattern.Tests.ps1 | 51 ++++++++++++ .../Unit/Private/Copy-IslSharedFile.Tests.ps1 | 59 +++++++++++++ .../Private/Get-IslGraphRetryDelay.Tests.ps1 | 83 +++++++++++++++++++ .../Get-IslRegexLiteralPrefix.Tests.ps1 | 44 ++++++++++ .../Private/Get-IslRegistryText.Tests.ps1 | 64 ++++++++++++++ .../Invoke-IslGraphRequestOnce.Tests.ps1 | 73 ++++++++++++++++ .../Unit/Private/Write-IslTextFile.Tests.ps1 | 62 ++++++++++++++ 21 files changed, 975 insertions(+), 178 deletions(-) create mode 100644 Private/Compress-IslFolder.ps1 create mode 100644 Private/ConvertTo-IslNamedGroupPattern.ps1 create mode 100644 Private/Copy-IslSharedFile.ps1 create mode 100644 Private/Get-IslGraphRetryDelay.ps1 create mode 100644 Private/Get-IslRegexLiteralPrefix.ps1 create mode 100644 Private/Get-IslRegistryText.ps1 create mode 100644 Private/Invoke-IslGraphRequestOnce.ps1 create mode 100644 Private/Write-IslTextFile.ps1 create mode 100644 Tests/Unit/Private/Compress-IslFolder.Tests.ps1 create mode 100644 Tests/Unit/Private/ConvertTo-IslNamedGroupPattern.Tests.ps1 create mode 100644 Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 create mode 100644 Tests/Unit/Private/Get-IslGraphRetryDelay.Tests.ps1 create mode 100644 Tests/Unit/Private/Get-IslRegexLiteralPrefix.Tests.ps1 create mode 100644 Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 create mode 100644 Tests/Unit/Private/Invoke-IslGraphRequestOnce.Tests.ps1 create mode 100644 Tests/Unit/Private/Write-IslTextFile.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 91a5281..0d2b884 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,7 +43,8 @@ entries are carried over from the manifest's release notes. ### Changed - The helper functions nested in `Test-IntuneScript`, `Test-IntuneWin32Requirement`, - `Export-IntuneFindingSarif` and `Get-IslSetting` are private functions of their own, each an + `Export-IntuneFindingSarif`, `Export-IntuneAgentDiagnostic`, `Get-IslSetting`, + `Get-IslAgentLogEvent` and `Invoke-IslGraphRequest` are private functions of their own, each an advanced function with help and tests (#65). Nothing changes for a caller, except that the error of a settings value that is not allowed now names `ConvertTo-IslSettingsObject` after `SettingsInvalid` in its `FullyQualifiedErrorId`. diff --git a/CLAUDE.md b/CLAUDE.md index 9c51f58..ddeb6a3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -115,10 +115,10 @@ call is inside a `try` that has a `catch`; a `try` with only a `finally`, a nest pipeline do not stop it. A `throw` ended every function above it, which is what the callers were written for until the module moved from `throw` to `ThrowTerminatingError` (#64). A new call of a function that can fail gets `try { ... } catch { $PSCmdlet.ThrowTerminatingError($_) }` before the -function it calls is written to fail that way. The one `throw` that is left is in a nested function -without `[CmdletBinding()]`, `Invoke-Once` in `Invoke-IslGraphRequest`, which passes on the error it -caught; nested helpers are being moved to their own files as advanced functions (#65), and a -helper in its own file ends with `ThrowTerminatingError` like any other. +function it calls is written to fail that way. No function of the module uses `throw`: +nested helpers are being moved to their own files as advanced functions (#65), and a helper in its +own file ends with `ThrowTerminatingError` like any other. A plain nested function has no +`$PSCmdlet`, so a new one that can fail is written as a private function of its own instead. `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 diff --git a/Private/Compress-IslFolder.ps1 b/Private/Compress-IslFolder.ps1 new file mode 100644 index 0000000..65f7646 --- /dev/null +++ b/Private/Compress-IslFolder.ps1 @@ -0,0 +1,59 @@ +function Compress-IslFolder { + <# + .SYNOPSIS + Writes the files of a folder into a new zip archive, with forward slashes in the entry names. + + .DESCRIPTION + Windows PowerShell 5.1 runs on .NET Framework, whose ZipFile.CreateFromDirectory writes + entry names with backslashes, and such an archive does not open as folders on another + platform. This adds one entry for each file below the folder, named by its path relative to + the folder with forward slashes, on every host. Empty folders are not kept. The archive must + not exist yet. The command that calls this has asked ShouldProcess for the whole package, + and calls it with -WhatIf:$false and -Confirm:$false. + + .PARAMETER Folder + The full path of the folder to compress, without a trailing separator. + + .PARAMETER Destination + The full path of the zip archive to create. + + .EXAMPLE + $entryCount = Compress-IslFolder -Folder $staging -Destination $zip @script:IslInternal + + Writes the staging folder of a diagnostic package into its zip and returns the number of + entries. + + .INPUTS + None. + + .OUTPUTS + System.Int32. The number of entries written. + #> + [CmdletBinding(SupportsShouldProcess)] + [OutputType([int])] + param( + [Parameter(Mandatory)] + [string]$Folder, + + [Parameter(Mandatory)] + [string]$Destination + ) + + if (-not $PSCmdlet.ShouldProcess($Destination, "Compress $Folder")) { + return + } + Add-Type -AssemblyName System.IO.Compression.FileSystem + $archive = [System.IO.Compression.ZipFile]::Open($Destination, 'Create') + $count = 0 + try { + foreach ($file in (Get-ChildItem -LiteralPath $Folder -Recurse -File)) { + $relative = $file.FullName.Substring($Folder.Length).TrimStart('\', '/') -replace '\\', '/' + $null = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile( + $archive, $file.FullName, $relative) + $count++ + } + } finally { + $archive.Dispose() + } + $count +} diff --git a/Private/ConvertTo-IslNamedGroupPattern.ps1 b/Private/ConvertTo-IslNamedGroupPattern.ps1 new file mode 100644 index 0000000..b99caf6 --- /dev/null +++ b/Private/ConvertTo-IslNamedGroupPattern.ps1 @@ -0,0 +1,66 @@ +function ConvertTo-IslNamedGroupPattern { + <# + .SYNOPSIS + Renames the capturing groups of a regular expression so that several fit into one pattern. + + .DESCRIPTION + The agent-log reader joins every event pattern into one alternation and must still tell + which pattern matched and read its own captures. Each capturing group becomes a named group, + the prefix followed by its number from 1. A group that does not capture, such as (?:...) or + (?...), is left as it is, and so is a parenthesis that is escaped or inside a character + class. + + .PARAMETER Pattern + The regular expression. + + .PARAMETER Prefix + The start of the new group names, such as e3g. + + .EXAMPLE + ConvertTo-IslNamedGroupPattern -Pattern '^exit code is (-?\d+)' -Prefix 'e3g' + + Returns @{ Pattern = '^exit code is (?-?\d+)'; Count = 1 }. + + .INPUTS + None. + + .OUTPUTS + System.Collections.Hashtable. Pattern, the renamed expression, and Count, the number of + groups that were renamed. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [string]$Pattern, + + [Parameter(Mandatory)] + [string]$Prefix + ) + + $named = [System.Text.StringBuilder]::new() + $count = 0 + $inClass = $false + for ($index = 0; $index -lt $Pattern.Length; $index++) { + $character = $Pattern[$index] + if ($character -eq '\' -and $index + 1 -lt $Pattern.Length) { + $null = $named.Append($character).Append($Pattern[$index + 1]) + $index++ + continue + } + if ($inClass) { + if ($character -eq ']') { $inClass = $false } + $null = $named.Append($character) + continue + } + if ($character -eq '[') { $inClass = $true } + $opensCapture = $character -eq '(' -and ($index + 1 -ge $Pattern.Length -or $Pattern[$index + 1] -ne '?') + if ($opensCapture) { + $count++ + $null = $named.Append("(?<$Prefix$count>") + continue + } + $null = $named.Append($character) + } + @{ Pattern = $named.ToString(); Count = $count } +} diff --git a/Private/Copy-IslSharedFile.ps1 b/Private/Copy-IslSharedFile.ps1 new file mode 100644 index 0000000..6c521a9 --- /dev/null +++ b/Private/Copy-IslSharedFile.ps1 @@ -0,0 +1,50 @@ +function Copy-IslSharedFile { + <# + .SYNOPSIS + Copies a file that another process holds open for writing. + + .DESCRIPTION + The agent keeps its current log open while it writes to it. A stream that allows only + other readers cannot open such a file, so the source is opened for reading with write + sharing allowed, and the copy is the file as it stands at that moment. A file that is at the + destination is replaced. The command that calls this has asked ShouldProcess for the whole + package, and calls it with -WhatIf:$false and -Confirm:$false. + + .PARAMETER Source + The full path of the file to copy. + + .PARAMETER Destination + The full path of the copy. Its folder must exist. + + .EXAMPLE + Copy-IslSharedFile -Source $log.FullName -Destination $copy @script:IslInternal + + Copies a log of the agent that the agent is still writing. + + .INPUTS + None. + + .OUTPUTS + None. + #> + [CmdletBinding(SupportsShouldProcess)] + [OutputType([void])] + param( + [Parameter(Mandatory)] + [string]$Source, + + [Parameter(Mandatory)] + [string]$Destination + ) + + if (-not $PSCmdlet.ShouldProcess($Destination, "Copy $Source")) { + return + } + $in = [System.IO.File]::Open($Source, 'Open', 'Read', 'ReadWrite') + try { + $out = [System.IO.File]::Create($Destination) + try { $in.CopyTo($out) } finally { $out.Dispose() } + } finally { + $in.Dispose() + } +} diff --git a/Private/Get-IslAgentLogEvent.ps1 b/Private/Get-IslAgentLogEvent.ps1 index fdc044d..b478cda 100644 --- a/Private/Get-IslAgentLogEvent.ps1 +++ b/Private/Get-IslAgentLogEvent.ps1 @@ -159,65 +159,6 @@ function Get-IslAgentLogEvent { } @{ Event = 'ExecutorError'; Pattern = '^error from script =(.*)$' } ) - # The literal text a pattern starts with, which a matching message must contain somewhere: - # cheaper to look for than to run the pattern, and most messages match no pattern at all. - # Read up to the first metacharacter; an escaped punctuation character is a literal, an - # escaped letter is a class. A quantifier would make the last literal optional, so it goes - function Get-LiteralPrefix { - param([string]$Pattern) - $literal = [System.Text.StringBuilder]::new() - $index = if ($Pattern.StartsWith('^')) { 1 } else { 0 } - while ($index -lt $Pattern.Length) { - $character = $Pattern[$index] - if ($character -eq '\') { - if ($index + 1 -ge $Pattern.Length) { break } - $next = $Pattern[$index + 1] - if ([char]::IsLetterOrDigit($next)) { break } - $null = $literal.Append($next) - $index += 2 - continue - } - if ('()[]{}.*+?|^$'.IndexOf($character) -ge 0) { break } - $null = $literal.Append($character) - $index++ - } - if ($index -lt $Pattern.Length -and '*?{'.IndexOf($Pattern[$index]) -ge 0 -and $literal.Length) { - $literal.Length-- - } - $literal.ToString() - } - # The same pattern with its capturing groups named , so every group of the - # combined expression below has a name and the matched alternative is the first group that - # succeeded. A "(" opens a capture unless it is escaped, inside a class, or followed by "?" - function ConvertTo-NamedGroup { - param([string]$Pattern, [string]$Prefix) - $named = [System.Text.StringBuilder]::new() - $count = 0 - $inClass = $false - for ($index = 0; $index -lt $Pattern.Length; $index++) { - $character = $Pattern[$index] - if ($character -eq '\' -and $index + 1 -lt $Pattern.Length) { - $null = $named.Append($character).Append($Pattern[$index + 1]) - $index++ - continue - } - if ($inClass) { - if ($character -eq ']') { $inClass = $false } - $null = $named.Append($character) - continue - } - if ($character -eq '[') { $inClass = $true } - $opensCapture = $character -eq '(' -and - ($index + 1 -ge $Pattern.Length -or $Pattern[$index + 1] -ne '?') - if ($opensCapture) { - $count++ - $null = $named.Append("(?<$Prefix$count>") - continue - } - $null = $named.Append($character) - } - @{ Pattern = $named.ToString(); Count = $count } - } # One expression for the whole table: 44 patterns tried one by one cost 44 statements a # message, which was most of what reading a log cost; one Match is one. Alternation keeps # the table's order at a given position, so two patterns that fit the same text still @@ -226,9 +167,12 @@ function Get-IslAgentLogEvent { $combined = [System.Text.StringBuilder]::new() $position = 0 $script:IslAgentLogEvents = @(foreach ($definition in $definitions) { - $prefix = Get-LiteralPrefix -Pattern $definition.Pattern + # The literal text a pattern starts with, which a matching message must contain + # somewhere: cheaper to look for than to run the pattern, and most messages match + # no pattern at all + $prefix = Get-IslRegexLiteralPrefix -Pattern $definition.Pattern $group = "e$position" - $renamed = ConvertTo-NamedGroup -Pattern $definition.Pattern -Prefix "${group}g" + $renamed = ConvertTo-IslNamedGroupPattern -Pattern $definition.Pattern -Prefix "${group}g" if ($position -gt 0) { $null = $combined.Append('|') } $null = $combined.Append("(?<$group>").Append($renamed.Pattern).Append(')') $position++ diff --git a/Private/Get-IslGraphRetryDelay.ps1 b/Private/Get-IslGraphRetryDelay.ps1 new file mode 100644 index 0000000..9a6adfc --- /dev/null +++ b/Private/Get-IslGraphRetryDelay.ps1 @@ -0,0 +1,61 @@ +function Get-IslGraphRetryDelay { + <# + .SYNOPSIS + Gets how long to wait before sending a failed Graph request again. + + .DESCRIPTION + Microsoft Graph asks a client to come back later with 429 (too many requests), 503 and 504. + For those, the delay is the one the reply's Retry-After header gives, as a number of seconds + or as a date, and otherwise 2 to the power of the attempt; it is at most 60 seconds. For any + other failure there is nothing to wait for, and the function returns nothing. The status code + and the response are read from Invoke-MgGraphRequest's exception by name, so an exception + of another type with the same members serves in the tests. + + .PARAMETER ErrorRecord + The error of the request that failed. + + .PARAMETER Attempt + The number of the attempt that failed, from 1. + + .EXAMPLE + $delay = Get-IslGraphRetryDelay -ErrorRecord $_ -Attempt 1 + + In a catch: 2 for a 503 without Retry-After, nothing for a 404. + + .INPUTS + None. + + .OUTPUTS + System.Int32. The delay in seconds, or nothing when the request is not to be sent again. + #> + [CmdletBinding()] + [OutputType([int])] + param( + [Parameter(Mandatory)] + [System.Management.Automation.ErrorRecord]$ErrorRecord, + + [Parameter(Mandatory)] + [ValidateRange(1, 100)] + [int]$Attempt + ) + + $exception = $ErrorRecord.Exception + $status = 0 + if ($exception.PSObject.Properties['StatusCode'] -and $exception.StatusCode) { + $status = [int]$exception.StatusCode + } + $response = if ($exception.PSObject.Properties['Response']) { $exception.Response } else { $null } + if (-not $status -and $response) { $status = [int]$response.StatusCode } + if ($status -notin 429, 503, 504) { return } + + $delay = 0 + $retryAfter = if ($response) { $response.Headers.RetryAfter } else { $null } + if ($retryAfter) { + if ($null -ne $retryAfter.Delta) { $delay = [Math]::Ceiling($retryAfter.Delta.TotalSeconds) } + elseif ($null -ne $retryAfter.Date) { + $delay = [Math]::Ceiling(($retryAfter.Date.UtcDateTime - [datetime]::UtcNow).TotalSeconds) + } + } + if ($delay -lt 1) { $delay = [Math]::Pow(2, $Attempt) } + [int][Math]::Min($delay, 60) +} diff --git a/Private/Get-IslRegexLiteralPrefix.ps1 b/Private/Get-IslRegexLiteralPrefix.ps1 new file mode 100644 index 0000000..545e764 --- /dev/null +++ b/Private/Get-IslRegexLiteralPrefix.ps1 @@ -0,0 +1,56 @@ +function Get-IslRegexLiteralPrefix { + <# + .SYNOPSIS + Gets the literal text a regular expression starts with. + + .DESCRIPTION + A message that the pattern matches must contain this text, and looking for it is cheaper + than running the pattern; most lines of the agent's logs match no pattern at all. The text is + read up to the first metacharacter. A leading ^ is skipped, an escaped punctuation character + counts as itself, and an escaped letter or digit ends the text, because it stands for a + class. When a quantifier follows the text, its last character is optional in the pattern and + is left out. + + .PARAMETER Pattern + The regular expression. + + .EXAMPLE + Get-IslRegexLiteralPrefix -Pattern '^Powershell exit code is (-?\d+)' + + Returns 'Powershell exit code is '. + + .INPUTS + None. + + .OUTPUTS + System.String. The literal text, or an empty string when the pattern starts with a + metacharacter. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [string]$Pattern + ) + + $literal = [System.Text.StringBuilder]::new() + $index = if ($Pattern.StartsWith('^')) { 1 } else { 0 } + while ($index -lt $Pattern.Length) { + $character = $Pattern[$index] + if ($character -eq '\') { + if ($index + 1 -ge $Pattern.Length) { break } + $next = $Pattern[$index + 1] + if ([char]::IsLetterOrDigit($next)) { break } + $null = $literal.Append($next) + $index += 2 + continue + } + if ('()[]{}.*+?|^$'.IndexOf($character) -ge 0) { break } + $null = $literal.Append($character) + $index++ + } + if ($index -lt $Pattern.Length -and '*?{'.IndexOf($Pattern[$index]) -ge 0 -and $literal.Length) { + $literal.Length-- + } + $literal.ToString() +} diff --git a/Private/Get-IslRegistryText.ps1 b/Private/Get-IslRegistryText.ps1 new file mode 100644 index 0000000..45355ce --- /dev/null +++ b/Private/Get-IslRegistryText.ps1 @@ -0,0 +1,60 @@ +function Get-IslRegistryText { + <# + .SYNOPSIS + Gets a registry key and its subkeys as lines of text. + + .DESCRIPTION + For the registry sections of the diagnostic package. Each key is a line "[name]", followed + by one line " name = value" for each of its values. The PowerShell provider's own properties + are left out, binary values are shown by their length, and a value longer than 400 + characters is cut there and marked with "...". A key or a subkey that cannot be read is + passed over without an error; a key that is not there gives the one line " : not + present". + + .PARAMETER Key + The path of the key in a PowerShell registry drive, such as + HKLM:\SOFTWARE\Microsoft\IntuneManagementExtension. + + .PARAMETER Depth + How many levels of subkeys below the key are included. + + .EXAMPLE + Get-IslRegistryText -Key 'HKLM:\SOFTWARE\Microsoft\IntuneManagementExtension\Policies' -Depth 2 + + The policy keys of the agent, two levels down. + + .INPUTS + None. + + .OUTPUTS + System.String. One line at a time. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [string]$Key, + + [Parameter(Mandatory)] + [ValidateRange(0, 64)] + [int]$Depth + ) + + if (-not (Test-Path -LiteralPath $Key)) { + return "$Key : not present" + } + $children = @(Get-ChildItem -LiteralPath $Key -Recurse -Depth $Depth -ErrorAction SilentlyContinue) + $keys = @(Get-Item -LiteralPath $Key) + $children + foreach ($item in $keys) { + "[$($item.Name)]" + $values = Get-ItemProperty -LiteralPath $item.PSPath -ErrorAction SilentlyContinue + if (-not $values) { continue } + foreach ($property in $values.PSObject.Properties) { + if ($property.Name -like 'PS*') { continue } + $text = if ($property.Value -is [byte[]]) { "byte[$($property.Value.Length)]" } + else { "$($property.Value)" } + if ($text.Length -gt 400) { $text = $text.Substring(0, 400) + '...' } + " $($property.Name) = $text" + } + } +} diff --git a/Private/Invoke-IslGraphRequest.ps1 b/Private/Invoke-IslGraphRequest.ps1 index bc24db0..573f2d1 100644 --- a/Private/Invoke-IslGraphRequest.ps1 +++ b/Private/Invoke-IslGraphRequest.ps1 @@ -78,61 +78,17 @@ function Invoke-IslGraphRequest { if ($Body) { $requestSplat.Body = $Body } if ($Headers) { $requestSplat.Headers = $Headers } - # How long to wait before sending a failed request again, or nothing when the failure is not - # one that passes. Invoke-MgGraphRequest's exception carries the status code and the response; - # both are read by name so a stand-in exception with the same members serves in the tests - function Get-RetryDelay { - param($ErrorRecord, [int]$Attempt) - $exception = $ErrorRecord.Exception - $status = 0 - if ($exception.PSObject.Properties['StatusCode'] -and $exception.StatusCode) { - $status = [int]$exception.StatusCode - } - $response = if ($exception.PSObject.Properties['Response']) { $exception.Response } else { $null } - if (-not $status -and $response) { $status = [int]$response.StatusCode } - if ($status -notin 429, 503, 504) { return $null } - - $delay = 0 - $retryAfter = if ($response) { $response.Headers.RetryAfter } else { $null } - if ($retryAfter) { - if ($null -ne $retryAfter.Delta) { $delay = [Math]::Ceiling($retryAfter.Delta.TotalSeconds) } - elseif ($null -ne $retryAfter.Date) { - $delay = [Math]::Ceiling(($retryAfter.Date.UtcDateTime - [datetime]::UtcNow).TotalSeconds) - } - } - if ($delay -lt 1) { $delay = [Math]::Pow(2, $Attempt) } - [int][Math]::Min($delay, 60) - } - - function Invoke-Once { - param([hashtable]$Splat) - $attempt = 0 - while ($true) { - try { - return Invoke-MgGraphRequest @Splat - } - catch { - $attempt++ - $delay = if ($attempt -le 3) { Get-RetryDelay -ErrorRecord $_ -Attempt $attempt } else { $null } - if ($null -eq $delay) { throw } - Write-Verbose ("Graph answered $($_.Exception.Message); retry $attempt of 3 in $delay s: " + - $Splat.Uri) - Start-Sleep -Seconds $delay - } - } - } - # The request that failed for good ends this function with Graph's own error, unchanged, so # that a caller reads the status code and the response from it as before $items = [System.Collections.Generic.List[object]]::new() try { if (-not $All) { - $reply = Invoke-Once -Splat $requestSplat + $reply = Invoke-IslGraphRequestOnce -Request $requestSplat } else { $next = $Uri while ($next) { $requestSplat.Uri = $next - $page = Invoke-Once -Splat $requestSplat + $page = Invoke-IslGraphRequestOnce -Request $requestSplat # The last page has no next link, and an empty collection may come without a value $pageItems = @(Get-IslPropertyValue -InputObject $page -Name 'value') if ($pageItems.Count -gt 0) { $items.AddRange([object[]]$pageItems) } diff --git a/Private/Invoke-IslGraphRequestOnce.ps1 b/Private/Invoke-IslGraphRequestOnce.ps1 new file mode 100644 index 0000000..bdb57c7 --- /dev/null +++ b/Private/Invoke-IslGraphRequestOnce.ps1 @@ -0,0 +1,54 @@ +function Invoke-IslGraphRequestOnce { + <# + .SYNOPSIS + Sends one Graph request, and sends it again up to three times when Graph asks for that. + + .DESCRIPTION + One page of Invoke-IslGraphRequest. A reply of 429, 503 or 504 is followed by a wait of the + delay Get-IslGraphRetryDelay gives and another attempt, three at most. Any other failure, and + the fourth failure of one that passes, ends the function with Graph's own error, unchanged, + so that the caller reads the status code and the response from it. + + .PARAMETER Request + The parameters of Invoke-MgGraphRequest: Method and Uri, and Body and Headers when the + request has them. ErrorAction Stop is expected among them. + + .EXAMPLE + $page = Invoke-IslGraphRequestOnce -Request @{ Method = 'GET'; Uri = '/v1.0/me'; ErrorAction = 'Stop' } + + The reply to one GET. + + .INPUTS + None. + + .OUTPUTS + System.Object. The reply of Invoke-MgGraphRequest, as it returns it. + #> + [CmdletBinding()] + [OutputType([object])] + param( + [Parameter(Mandatory)] + [hashtable]$Request + ) + + $attempt = 0 + while ($true) { + try { + $reply = Invoke-MgGraphRequest @Request + break + } catch { + $attempt++ + $delay = $null + if ($attempt -le 3) { + $delay = Get-IslGraphRetryDelay -ErrorRecord $_ -Attempt $attempt + } + if ($null -eq $delay) { + $PSCmdlet.ThrowTerminatingError($_) + } + Write-Verbose ("Graph answered $($_.Exception.Message); retry $attempt of 3 in $delay s: " + + $Request['Uri']) + Start-Sleep -Seconds $delay + } + } + $reply +} diff --git a/Private/Write-IslTextFile.ps1 b/Private/Write-IslTextFile.ps1 new file mode 100644 index 0000000..b008e29 --- /dev/null +++ b/Private/Write-IslTextFile.ps1 @@ -0,0 +1,58 @@ +function Write-IslTextFile { + <# + .SYNOPSIS + Writes lines to a file below a folder, as UTF-8 without a byte order mark. + + .DESCRIPTION + One section of the diagnostic package of Export-IntuneAgentDiagnostic, such as the device + facts or one registry key. The folders on the way to the file are created, and a file that is + there is replaced. The command that calls this has asked ShouldProcess for the whole package, + and calls it with -WhatIf:$false and -Confirm:$false. + + .PARAMETER Root + The folder the relative path starts from. + + .PARAMETER RelativePath + The path of the file below the root, such as Registry\Scripts.txt. + + .PARAMETER Line + The lines of the file. An empty list, or none, writes an empty file. + + .EXAMPLE + Write-IslTextFile -Root $staging -RelativePath 'Device\system.txt' -Line $system @script:IslInternal + + Writes the device facts into the staging folder of a package. + + .INPUTS + None. + + .OUTPUTS + None. + #> + [CmdletBinding(SupportsShouldProcess)] + [OutputType([void])] + param( + [Parameter(Mandatory)] + [string]$Root, + + [Parameter(Mandatory)] + [string]$RelativePath, + + [Parameter(Mandatory)] + [AllowNull()] + [AllowEmptyCollection()] + [AllowEmptyString()] + [string[]]$Line + ) + + $file = Join-Path -Path $Root -ChildPath $RelativePath + if (-not $PSCmdlet.ShouldProcess($file, 'Write the file')) { + return + } + $folder = Split-Path -Path $file -Parent + $null = New-Item -ItemType Directory -Path $folder -Force @script:IslInternal + # Assigned, not taken from an if expression, which would unroll an empty array to nothing + [string[]]$text = @() + if ($null -ne $Line) { $text = $Line } + [System.IO.File]::WriteAllLines($file, $text, [System.Text.UTF8Encoding]::new($false)) +} diff --git a/Public/Export-IntuneAgentDiagnostic.ps1 b/Public/Export-IntuneAgentDiagnostic.ps1 index c8143fd..659dfd3 100644 --- a/Public/Export-IntuneAgentDiagnostic.ps1 +++ b/Public/Export-IntuneAgentDiagnostic.ps1 @@ -42,65 +42,6 @@ function Export-IntuneAgentDiagnostic { $stagingName = "IntuneScriptLab-diag-$([guid]::NewGuid().ToString('N'))" $staging = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath $stagingName $manifest = [System.Collections.Generic.List[string]]::new() - $utf8 = [System.Text.UTF8Encoding]::new($false) - - function Write-Section { - param([string]$Relative, [string[]]$Lines) - $file = Join-Path -Path $staging -ChildPath $Relative - $folder = Split-Path -Path $file -Parent - $null = New-Item -ItemType Directory -Path $folder -Force @script:IslInternal - [System.IO.File]::WriteAllLines($file, [string[]]$Lines, $utf8) - } - - # A log the agent holds open copies through a shared-read stream - function Copy-SharedFile { - param([string]$Source, [string]$Destination) - $in = [System.IO.File]::Open($Source, 'Open', 'Read', 'ReadWrite') - try { - $out = [System.IO.File]::Create($Destination) - try { $in.CopyTo($out) } finally { $out.Dispose() } - } - finally { $in.Dispose() } - } - - # A registry key and its subkeys as "key" and " name = value" lines - function Get-RegistryText { - param([string]$Key, [int]$Depth) - if (-not (Test-Path -LiteralPath $Key)) { return @("$Key : not present") } - $children = @(Get-ChildItem -LiteralPath $Key -Recurse -Depth $Depth -ErrorAction SilentlyContinue) - $keys = @(Get-Item -LiteralPath $Key) + $children - foreach ($item in $keys) { - "[$($item.Name)]" - $values = Get-ItemProperty -LiteralPath $item.PSPath -ErrorAction SilentlyContinue - if (-not $values) { continue } - foreach ($property in $values.PSObject.Properties) { - if ($property.Name -like 'PS*') { continue } - $text = if ($property.Value -is [byte[]]) { "byte[$($property.Value.Length)]" } - else { "$($property.Value)" } - if ($text.Length -gt 400) { $text = $text.Substring(0, 400) + '...' } - " $($property.Name) = $text" - } - } - } - - # The staging folder as a zip with forward-slash entry names on every host (.NET Framework's - # CreateFromDirectory writes backslashes) - function Compress-Staging { - param([string]$Folder, [string]$Destination) - Add-Type -AssemblyName System.IO.Compression.FileSystem - $archive = [System.IO.Compression.ZipFile]::Open($Destination, 'Create') - $count = 0 - try { - foreach ($file in (Get-ChildItem -LiteralPath $Folder -Recurse -File)) { - $relative = $file.FullName.Substring($Folder.Length).TrimStart('\', '/') -replace '\\', '/' - $null = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile( - $archive, $file.FullName, $relative) - $count++ - } - } - finally { $archive.Dispose() } - $count - } try { $null = New-Item -ItemType Directory -Path $staging -Force @script:IslInternal @@ -113,7 +54,8 @@ function Export-IntuneAgentDiagnostic { $null = New-Item -ItemType Directory -Path $logFolder -Force @script:IslInternal foreach ($file in $logFiles) { $destination = Join-Path -Path $logFolder -ChildPath $file.Name - Copy-SharedFile -Source $file.FullName -Destination $destination + # A log the agent holds open is copied through a shared-read stream + Copy-IslSharedFile -Source $file.FullName -Destination $destination @script:IslInternal } $manifest.Add("Logs: $($logFiles.Count) file(s) from $LogPath") } @@ -139,10 +81,11 @@ function Export-IntuneAgentDiagnostic { if ($agentExe -and (Test-Path -LiteralPath $agentExe)) { $system.Add("Agent version: $((Get-Item -LiteralPath $agentExe).VersionInfo.FileVersion)") } - Write-Section -Relative 'Device\system.txt' -Lines $system + Write-IslTextFile -Root $staging -RelativePath 'Device\system.txt' -Line $system @script:IslInternal if (Get-Command -Name dsregcmd.exe -ErrorAction SilentlyContinue) { $joinState = @(& dsregcmd.exe /status 2>&1 | ForEach-Object { "$_" }) - Write-Section -Relative 'Device\dsregcmd.txt' -Lines $joinState + $sectionSplat = @{ Root = $staging; RelativePath = 'Device\dsregcmd.txt'; Line = $joinState } + Write-IslTextFile @sectionSplat @script:IslInternal $manifest.Add('Device: system.txt, dsregcmd.txt') } else { $manifest.Add('Device: system.txt (dsregcmd not available)') } @@ -159,8 +102,9 @@ function Export-IntuneAgentDiagnostic { Key = 'HKLM:\SOFTWARE\Microsoft\Provisioning\Diagnostics\AutoPilot' } ) foreach ($entry in $keys) { - $lines = @(Get-RegistryText -Key $entry.Key -Depth $entry.Depth) - Write-Section -Relative "Registry\$($entry.Name).txt" -Lines $lines + $lines = @(Get-IslRegistryText -Key $entry.Key -Depth $entry.Depth) + $sectionSplat = @{ Root = $staging; RelativePath = "Registry\$($entry.Name).txt"; Line = $lines } + Write-IslTextFile @sectionSplat @script:IslInternal } $manifest.Add("Registry: $(($keys | ForEach-Object { $_.Name }) -join ', ')") } @@ -188,14 +132,14 @@ function Export-IntuneAgentDiagnostic { else { $manifest.Add('Timeline: skipped') } $manifest.Insert(0, "IntuneScriptLab diagnostic package, $((Get-Date).ToString('yyyy-MM-dd HH:mm:ss'))") - Write-Section -Relative 'Manifest.txt' -Lines $manifest + Write-IslTextFile -Root $staging -RelativePath 'Manifest.txt' -Line $manifest @script:IslInternal if (Test-Path -LiteralPath $zip) { Remove-Item -LiteralPath $zip -Force @script:IslInternal } $zipFolder = Split-Path -Path $zip -Parent if ($zipFolder -and -not (Test-Path -LiteralPath $zipFolder)) { $null = New-Item -ItemType Directory -Path $zipFolder -Force @script:IslInternal } - $entryCount = Compress-Staging -Folder $staging -Destination $zip + $entryCount = Compress-IslFolder -Folder $staging -Destination $zip @script:IslInternal } catch { # Whatever failed, the package is not complete: the command ends without a result diff --git a/Tests/Unit/Private/Compress-IslFolder.Tests.ps1 b/Tests/Unit/Private/Compress-IslFolder.Tests.ps1 new file mode 100644 index 0000000..58a3b5b --- /dev/null +++ b/Tests/Unit/Private/Compress-IslFolder.Tests.ps1 @@ -0,0 +1,52 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The zip of the diagnostic package, with forward slashes in its entry names on every host. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + Add-Type -AssemblyName System.IO.Compression.FileSystem + + $script:Folder = Join-Path $TestDrive 'staging' + foreach ($relative in 'Manifest.txt', 'Logs\Agent.log', 'Registry\Deep\Key.txt') { + $path = Join-Path $script:Folder $relative + $null = New-Item -ItemType Directory -Path (Split-Path $path -Parent) -Force + [System.IO.File]::WriteAllText($path, $relative) + } + $null = New-Item -ItemType Directory -Path (Join-Path $script:Folder 'Empty') +} + +Describe 'Compress-IslFolder' -Tag 'Unit', 'Private' { + + It 'writes one entry for each file, named with forward slashes, and returns the count' { + $zip = Join-Path $TestDrive 'package.zip' + $count = InModuleScope IntuneScriptLab -Parameters @{ Folder = $script:Folder; Zip = $zip } { + Compress-IslFolder -Folder $Folder -Destination $Zip @script:IslInternal + } + + $archive = [System.IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName } | Sort-Object) + } finally { + $archive.Dispose() + } + $count | Should-Be 3 + $names | Should-BeCollection -Count 3 + $names[0] | Should-Be 'Logs/Agent.log' + $names[1] | Should-Be 'Manifest.txt' + $names[2] | Should-Be 'Registry/Deep/Key.txt' + } + + It 'writes no archive under -WhatIf' { + $zip = Join-Path $TestDrive 'preview.zip' + InModuleScope IntuneScriptLab -Parameters @{ Folder = $script:Folder; Zip = $zip } { + Compress-IslFolder -Folder $Folder -Destination $Zip -WhatIf + } + + Test-Path -LiteralPath $zip | Should-BeFalse + } +} diff --git a/Tests/Unit/Private/ConvertTo-IslNamedGroupPattern.Tests.ps1 b/Tests/Unit/Private/ConvertTo-IslNamedGroupPattern.Tests.ps1 new file mode 100644 index 0000000..2cd394d --- /dev/null +++ b/Tests/Unit/Private/ConvertTo-IslNamedGroupPattern.Tests.ps1 @@ -0,0 +1,51 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The renaming of capturing groups that lets the agent-log reader join every event pattern into + one expression. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + function ConvertTo-Named { + param([string]$Pattern) + InModuleScope IntuneScriptLab -Parameters @{ Pattern = $Pattern } { + ConvertTo-IslNamedGroupPattern -Pattern $Pattern -Prefix 'e3g' + } + } +} + +Describe 'ConvertTo-IslNamedGroupPattern' -Tag 'Unit', 'Private' { + + It 'names group(s) in ' -ForEach @( + @{ Pattern = '^exit code is (-?\d+)'; Expected = '^exit code is (?-?\d+)'; Count = 1 } + @{ Pattern = 'a (b) c (d)'; Expected = 'a (?b) c (?d)'; Count = 2 } + @{ Pattern = 'x(?:y)(z)'; Expected = 'x(?:y)(?z)'; Count = 1 } + @{ Pattern = 'x(?y)'; Expected = 'x(?y)'; Count = 0 } + @{ Pattern = 'a\(b\)'; Expected = 'a\(b\)'; Count = 0 } + @{ Pattern = 'a[(]b(c)'; Expected = 'a[(]b(?c)'; Count = 1 } + @{ Pattern = 'plain text'; Expected = 'plain text'; Count = 0 } + ) { + $result = ConvertTo-Named -Pattern $Pattern + + $result['Pattern'] | Should-Be $Expected + $result['Count'] | Should-Be $Count + } + + It 'leaves a pattern that matches the same text and captures the same values' { + $pattern = '^write output done\. output = (.*?)(?:\r?\n?, error = (.*))?$' + $result = ConvertTo-Named -Pattern $pattern + $text = 'write output done. output = ok, error = bad' + + $original = [regex]::Match($text, $pattern) + $renamed = [regex]::Match($text, $result['Pattern']) + + $renamed.Success | Should-BeTrue + $renamed.Groups['e3g1'].Value | Should-Be $original.Groups[1].Value + $renamed.Groups['e3g2'].Value | Should-Be $original.Groups[2].Value + } +} diff --git a/Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 b/Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 new file mode 100644 index 0000000..01e72b8 --- /dev/null +++ b/Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 @@ -0,0 +1,59 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The copy of a log that the agent holds open for writing. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + function script:Copy-Shared { + param([string]$Source, [string]$Destination) + InModuleScope IntuneScriptLab -Parameters @{ Source = $Source; Destination = $Destination } { + Copy-IslSharedFile -Source $Source -Destination $Destination @script:IslInternal + } + } +} + +Describe 'Copy-IslSharedFile' -Tag 'Unit', 'Private' { + + It 'copies a file that another stream holds open for writing, as it stands' { + $source = Join-Path $TestDrive 'IntuneManagementExtension.log' + $destination = Join-Path $TestDrive 'copy-open.log' + # Open for writing and shared for reading only, as the agent holds its log + $writer = [System.IO.File]::Open($source, 'Create', 'Write', 'Read') + try { + $bytes = [System.Text.Encoding]::ASCII.GetBytes("line one`r`n") + $writer.Write($bytes, 0, $bytes.Length) + $writer.Flush() + # What the share mode is for: a reader that allows only other readers is refused + { [System.IO.File]::OpenRead($source).Dispose() } | Should-Throw + + Copy-Shared -Source $source -Destination $destination + } finally { + $writer.Dispose() + } + + [System.IO.File]::ReadAllText($destination) | Should-Be "line one`r`n" + } + + It 'replaces a file that is at the destination' { + $source = Join-Path $TestDrive 'Agent.log' + $destination = Join-Path $TestDrive 'copy-replaced.log' + [System.IO.File]::WriteAllText($source, 'new') + [System.IO.File]::WriteAllText($destination, 'old and longer') + + Copy-Shared -Source $source -Destination $destination + + [System.IO.File]::ReadAllText($destination) | Should-Be 'new' + } + + It 'ends with an error for a source that is not there' { + $missing = Join-Path $TestDrive 'not-there.log' + + { Copy-Shared -Source $missing -Destination (Join-Path $TestDrive 'never.log') } | Should-Throw + } +} diff --git a/Tests/Unit/Private/Get-IslGraphRetryDelay.Tests.ps1 b/Tests/Unit/Private/Get-IslGraphRetryDelay.Tests.ps1 new file mode 100644 index 0000000..cf96f74 --- /dev/null +++ b/Tests/Unit/Private/Get-IslGraphRetryDelay.Tests.ps1 @@ -0,0 +1,83 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + How long to wait before a failed Graph request is sent again, read from the failure the way + Invoke-MgGraphRequest raises it. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + # Windows PowerShell 5.1 loads System.Net.Http on demand + Add-Type -AssemblyName System.Net.Http -ErrorAction SilentlyContinue + + function script:New-GraphFailureRecord { + param([int]$StatusCode, [int]$RetryAfterSeconds) + # .NET Framework's HttpStatusCode has no name for 429; the enum takes the number all the same + $code = [System.Enum]::ToObject([System.Net.HttpStatusCode], $StatusCode) + $response = [System.Net.Http.HttpResponseMessage]::new($code) + if ($RetryAfterSeconds) { + $delta = [timespan]::FromSeconds($RetryAfterSeconds) + $response.Headers.RetryAfter = [System.Net.Http.Headers.RetryConditionHeaderValue]::new($delta) + } + $failure = [RetryDelayGraphException]::new("Response status code does not indicate success: $StatusCode") + $failure.StatusCode = $code + $failure.Response = $response + [System.Management.Automation.ErrorRecord]::new($failure, 'GraphFailure', 'InvalidResult', $null) + } + + function script:Get-Delay { + param([System.Management.Automation.ErrorRecord]$Record, [int]$Attempt) + $parameters = @{ Record = $Record; Attempt = $Attempt } + InModuleScope IntuneScriptLab -Parameters $parameters { + Get-IslGraphRetryDelay -ErrorRecord $Record -Attempt $Attempt + } + } +} + +class RetryDelayGraphException : System.Exception { + $StatusCode + $Response + RetryDelayGraphException([string]$message) : base($message) { } +} + +Describe 'Get-IslGraphRetryDelay' -Tag 'Unit', 'Private' { + + It 'waits the Retry-After seconds of a throttled request' { + Get-Delay -Record (New-GraphFailureRecord -StatusCode 429 -RetryAfterSeconds 7) -Attempt 1 | Should-Be 7 + } + + It 'doubles the wait with each attempt for without Retry-After' -ForEach @( + @{ Status = 503 } + @{ Status = 504 } + @{ Status = 429 } + ) { + $record = New-GraphFailureRecord -StatusCode $Status + @(1, 2, 3 | ForEach-Object { Get-Delay -Record $record -Attempt $_ }) | Should-BeCollection -Count 3 + Get-Delay -Record $record -Attempt 1 | Should-Be 2 + Get-Delay -Record $record -Attempt 2 | Should-Be 4 + Get-Delay -Record $record -Attempt 3 | Should-Be 8 + } + + It 'waits at most 60 seconds' { + Get-Delay -Record (New-GraphFailureRecord -StatusCode 429 -RetryAfterSeconds 600) -Attempt 1 | Should-Be 60 + } + + It 'gives nothing for a failure that is not sent again: ' -ForEach @( + @{ Status = 400 } + @{ Status = 403 } + @{ Status = 404 } + @{ Status = 500 } + ) { + @(Get-Delay -Record (New-GraphFailureRecord -StatusCode $Status) -Attempt 1) | Should-BeCollection @() + } + + It 'gives nothing for a failure that carries no status at all' { + $record = [System.Management.Automation.ErrorRecord]::new( + [System.InvalidOperationException]::new('no connection'), 'NoStatus', 'ConnectionError', $null) + + @(Get-Delay -Record $record -Attempt 1) | Should-BeCollection @() + } +} diff --git a/Tests/Unit/Private/Get-IslRegexLiteralPrefix.Tests.ps1 b/Tests/Unit/Private/Get-IslRegexLiteralPrefix.Tests.ps1 new file mode 100644 index 0000000..a80d8b0 --- /dev/null +++ b/Tests/Unit/Private/Get-IslRegexLiteralPrefix.Tests.ps1 @@ -0,0 +1,44 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The literal start of an event pattern, which the agent-log reader looks for before it runs + the pattern. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } +} + +Describe 'Get-IslRegexLiteralPrefix' -Tag 'Unit', 'Private' { + + It 'reads as ""' -ForEach @( + @{ Pattern = '^Powershell exit code is (-?\d+)'; Expected = 'Powershell exit code is ' } + @{ Pattern = 'ESP completed\. Triggering'; Expected = 'ESP completed. Triggering' } + @{ Pattern = '^error from script =(.*)$'; Expected = 'error from script =' } + @{ Pattern = 'abc\d+'; Expected = 'abc' } + @{ Pattern = 'colou?r'; Expected = 'colo' } + @{ Pattern = 'ab{2}'; Expected = 'a' } + @{ Pattern = '(start)'; Expected = '' } + @{ Pattern = 'ends with a backslash\'; Expected = 'ends with a backslash' } + ) { + $parameters = @{ Pattern = $Pattern } + $prefix = InModuleScope IntuneScriptLab -Parameters $parameters { + Get-IslRegexLiteralPrefix -Pattern $Pattern + } + + $prefix | Should-Be $Expected + } + + It 'gives text that every message the pattern matches contains' { + $pattern = '^Powershell exit code is (-?\d+)' + $prefix = InModuleScope IntuneScriptLab -Parameters @{ Pattern = $pattern } { + Get-IslRegexLiteralPrefix -Pattern $Pattern + } + + 'Powershell exit code is -1' -match $pattern | Should-BeTrue + 'Powershell exit code is -1'.Contains($prefix) | Should-BeTrue + } +} diff --git a/Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 b/Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 new file mode 100644 index 0000000..fe05174 --- /dev/null +++ b/Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 @@ -0,0 +1,64 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + A registry key as lines of text for the diagnostic package. The keys are made in Pester's + TestRegistry drive, which Pester removes after the file. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + function script:Get-Text { + param([string]$Key, [int]$Depth) + InModuleScope IntuneScriptLab -Parameters @{ Key = $Key; Depth = $Depth } { + @(Get-IslRegistryText -Key $Key -Depth $Depth) + } + } + + $script:Key = 'TestRegistry:\Policies' + $null = New-Item -Path $script:Key + $null = New-ItemProperty -Path $script:Key -Name 'Name' -Value 'Widget' + $null = New-ItemProperty -Path $script:Key -Name 'Blob' -PropertyType Binary -Value ([byte[]](1, 2, 3)) + $null = New-ItemProperty -Path $script:Key -Name 'Long' -Value ('x' * 450) + $null = New-Item -Path "$($script:Key)\Child" + $null = New-ItemProperty -Path "$($script:Key)\Child" -Name 'Inner' -Value 1 + $null = New-Item -Path "$($script:Key)\Child\Grandchild" +} + +Describe 'Get-IslRegistryText' -Tag 'Unit', 'Private' { + + It 'writes each key and each of its values, and leaves out the provider''s own properties' { + $lines = Get-Text -Key $script:Key -Depth 3 + + $lines[0] | Should-BeLikeString '`[*\Policies`]' + $lines | Should-ContainCollection ' Name = Widget' + @($lines | Where-Object { $_ -like ' PS*' }) | Should-BeCollection @() + @($lines | Where-Object { $_ -like '`[*\Child`]' }) | Should-BeCollection -Count 1 + $lines | Should-ContainCollection ' Inner = 1' + } + + It 'shows a binary value by its length and cuts a long value at 400 characters' { + $lines = Get-Text -Key $script:Key -Depth 0 + + $lines | Should-ContainCollection ' Blob = byte[3]' + $long = @($lines | Where-Object { $_ -like ' Long = *' }) + $long | Should-BeCollection -Count 1 + $long[0] | Should-Be (' Long = ' + ('x' * 400) + '...') + } + + It 'goes down as many levels as asked' { + $shallow = Get-Text -Key $script:Key -Depth 0 + $deep = Get-Text -Key $script:Key -Depth 1 + + @($shallow | Where-Object { $_ -like '`[*' }).Count | Should-Be 2 + @($deep | Where-Object { $_ -like '`[*Grandchild`]' }) | Should-BeCollection -Count 1 + } + + It 'gives one line for a key that is not there' { + $missing = 'TestRegistry:\NotThere' + Get-Text -Key $missing -Depth 1 | Should-BeCollection @("$missing : not present") + } +} diff --git a/Tests/Unit/Private/Invoke-IslGraphRequestOnce.Tests.ps1 b/Tests/Unit/Private/Invoke-IslGraphRequestOnce.Tests.ps1 new file mode 100644 index 0000000..ca94902 --- /dev/null +++ b/Tests/Unit/Private/Invoke-IslGraphRequestOnce.Tests.ps1 @@ -0,0 +1,73 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + One Graph request with its retries. The waits themselves are tested through + Invoke-IslGraphRequest and Get-IslGraphRetryDelay; this file holds what the function gives + back. Invoke-MgGraphRequest is stood in for by a global stub so no Graph module is needed. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + if (-not (Get-Command Invoke-MgGraphRequest -ErrorAction SilentlyContinue)) { + # The parameters exist so the mocks' parameter filters can bind to them + function global:Invoke-MgGraphRequest { + param($Method, $Uri, $Body, $Headers, $ErrorAction) + $null = $Method, $Uri, $Body, $Headers, $ErrorAction + } + $script:StubCreated = $true + } + Mock Start-Sleep -ModuleName IntuneScriptLab { } + + function script:Invoke-Once { + param([hashtable]$Request) + InModuleScope IntuneScriptLab -Parameters @{ Request = $Request } { + Invoke-IslGraphRequestOnce -Request $Request + } + } +} + +AfterAll { + if ($script:StubCreated) { Remove-Item Function:\global:Invoke-MgGraphRequest -ErrorAction SilentlyContinue } +} + +Describe 'Invoke-IslGraphRequestOnce' -Tag 'Unit', 'Private' { + + It 'passes the request through and returns the reply as it came' { + Mock Invoke-MgGraphRequest -ModuleName IntuneScriptLab { @{ id = 'x'; method = $Method; uri = $Uri } } + + $reply = Invoke-Once @{ Method = 'GET'; Uri = '/beta/things/x'; ErrorAction = 'Stop' } + + $reply['id'] | Should-Be 'x' + $reply['method'] | Should-Be 'GET' + $reply['uri'] | Should-Be '/beta/things/x' + Should-Invoke Invoke-MgGraphRequest -ModuleName IntuneScriptLab -Times 1 -Exactly + } + + It 'ends with the error of a failure that is not sent again, as Graph raised it' { + $failure = [System.InvalidOperationException]::new('Response status code does not indicate success: 404') + Mock Invoke-MgGraphRequest -ModuleName IntuneScriptLab { throw $failure } + + $thrown = { Invoke-Once @{ Method = 'GET'; Uri = '/beta/things/missing'; ErrorAction = 'Stop' } } | + Should-Throw -ExceptionMessage '*404*' + $thrown.Exception.GetBaseException() | Should-BeSame $failure + Should-Invoke Invoke-MgGraphRequest -ModuleName IntuneScriptLab -Times 1 -Exactly + } + + It 'sends the request again when Graph asks for it, and returns the reply that follows' { + $script:Calls = 0 + Mock Get-IslGraphRetryDelay -ModuleName IntuneScriptLab { 1 } + Mock Invoke-MgGraphRequest -ModuleName IntuneScriptLab { + $script:Calls++ + if ($script:Calls -lt 3) { throw 'Response status code does not indicate success: 503' } + @{ id = 'late' } + } + + $reply = Invoke-Once @{ Method = 'GET'; Uri = '/beta/things/late'; ErrorAction = 'Stop' } + + $reply['id'] | Should-Be 'late' + Should-Invoke Invoke-MgGraphRequest -ModuleName IntuneScriptLab -Times 3 -Exactly + } +} diff --git a/Tests/Unit/Private/Write-IslTextFile.Tests.ps1 b/Tests/Unit/Private/Write-IslTextFile.Tests.ps1 new file mode 100644 index 0000000..3adfaf0 --- /dev/null +++ b/Tests/Unit/Private/Write-IslTextFile.Tests.ps1 @@ -0,0 +1,62 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + One text section of the diagnostic package, written below its staging folder. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + function script:Write-Section { + param([string]$Root, [string]$RelativePath, [AllowNull()][string[]]$Line) + $parameters = @{ Root = $Root; RelativePath = $RelativePath; Line = $Line } + InModuleScope IntuneScriptLab -Parameters @{ Parameters = $parameters } { + Write-IslTextFile @Parameters @script:IslInternal + } + } +} + +Describe 'Write-IslTextFile' -Tag 'Unit', 'Private' { + + BeforeEach { + $script:Root = Join-Path $TestDrive "staging-$([guid]::NewGuid().ToString('N'))" + $null = New-Item -ItemType Directory -Path $script:Root + } + + It 'creates the folders on the way and writes UTF-8 without a byte order mark' { + $greeting = 'Gr' + [char]0xFC + [char]0xDF + 'e' + Write-Section -Root $script:Root -RelativePath 'Registry\Scripts.txt' -Line 'first', $greeting + + $file = Join-Path $script:Root 'Registry\Scripts.txt' + $bytes = [System.IO.File]::ReadAllBytes($file) + $bytes[0] | Should-Be ([byte][char]'f') + $lines = [System.IO.File]::ReadAllLines($file, [System.Text.UTF8Encoding]::new($false)) + $lines | Should-BeCollection -Count 2 + $lines[0] | Should-Be 'first' + $lines[1] | Should-Be $greeting + } + + It 'writes an empty file for no lines' { + Write-Section -Root $script:Root -RelativePath 'Device\dsregcmd.txt' -Line $null + + (Get-Item -LiteralPath (Join-Path $script:Root 'Device\dsregcmd.txt')).Length | Should-Be 0 + } + + It 'replaces a file that is there' { + Write-Section -Root $script:Root -RelativePath 'Manifest.txt' -Line 'old', 'older' + Write-Section -Root $script:Root -RelativePath 'Manifest.txt' -Line 'new' + + [System.IO.File]::ReadAllLines((Join-Path $script:Root 'Manifest.txt')) | Should-BeCollection @('new') + } + + It 'writes nothing under -WhatIf' { + InModuleScope IntuneScriptLab -Parameters @{ Root = $script:Root } { + Write-IslTextFile -Root $Root -RelativePath 'Preview\x.txt' -Line 'x' -WhatIf + } + + Test-Path -LiteralPath (Join-Path $script:Root 'Preview') | Should-BeFalse + } +} From 3bebe0ea21236d12054d5c005b87fbdf202a7bc4 Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:36:58 -0800 Subject: [PATCH 2/4] docs(claude): record that a help line starting with .NET hides the help --- CLAUDE.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index ddeb6a3..9db53f8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -186,6 +186,12 @@ Markdown from `Get-Help`), then trim the block to `.EXTERNALHELP IntuneScriptLab one-line `.SYNOPSIS`, delete the ALIASES placeholder and fill INPUTS and OUTPUTS by hand. Adding `.EXTERNALHELP` before the first generation leaves the Markdown full of `{{ Fill in }}`. +Inside a comment-based help block, a line that starts with a dot and a word is read as a keyword. +One that is not a keyword, such as a sentence that begins `.NET Framework's`, leaves the function +with no help that `Get-Help` finds, and nothing reports it but the standards' check (DOC-01). +Start such a sentence with another word, and check a new private function with +`(Get-Help ).description` from inside the module. + ### Never `Publish-PSResource -Path .` This repository *is* the module root, so packaging it directly ships the whole working tree, From 6c636f0d1e3b3b1510b98212f437ceeb06566a2c Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:52:17 -0800 Subject: [PATCH 3/4] fix(diagnostic): keep ShouldProcess to the command, and end helpers on failure Write-IslTextFile, Copy-IslSharedFile and Compress-IslFolder declared SupportsShouldProcess and asked ShouldProcess themselves, which CLAUDE.md reserves for the commands that run a script or write a report. Export-IntuneAgentDiagnostic asks for the whole package before it calls them, so they no longer ask, and their calls lose the -WhatIf:$false -Confirm:$false splat that pinned them. The three helpers made .NET calls that can fail outside any try. They now end with ThrowTerminatingError, so the error-flow contract test counts them as able to fail and checks their callers. Get-IslRegistryText read the key itself without -ErrorAction, so a key that exists but denies reading wrote an access error, where its help says such a key is passed over. --- Private/Compress-IslFolder.ps1 | 24 ++++++++------- Private/Copy-IslSharedFile.ps1 | 23 +++++++------- Private/Get-IslRegistryText.ps1 | 2 +- Private/Write-IslTextFile.ps1 | 22 +++++++------- Public/Export-IntuneAgentDiagnostic.ps1 | 12 ++++---- .../Unit/Private/Compress-IslFolder.Tests.ps1 | 24 +++++++++++---- .../Unit/Private/Copy-IslSharedFile.Tests.ps1 | 18 +++++++++-- .../Private/Get-IslRegistryText.Tests.ps1 | 30 +++++++++++++++++++ .../Unit/Private/Write-IslTextFile.Tests.ps1 | 17 ++++++++--- 9 files changed, 123 insertions(+), 49 deletions(-) diff --git a/Private/Compress-IslFolder.ps1 b/Private/Compress-IslFolder.ps1 index 65f7646..b5a4e23 100644 --- a/Private/Compress-IslFolder.ps1 +++ b/Private/Compress-IslFolder.ps1 @@ -8,8 +8,9 @@ function Compress-IslFolder { entry names with backslashes, and such an archive does not open as folders on another platform. This adds one entry for each file below the folder, named by its path relative to the folder with forward slashes, on every host. Empty folders are not kept. The archive must - not exist yet. The command that calls this has asked ShouldProcess for the whole package, - and calls it with -WhatIf:$false and -Confirm:$false. + not exist yet. It does not ask ShouldProcess: the command that calls it has asked for the + whole package, and it writes even when -WhatIf or -Confirm reached it through the + preferences. A failure ends the function with its error. .PARAMETER Folder The full path of the folder to compress, without a trailing separator. @@ -18,7 +19,7 @@ function Compress-IslFolder { The full path of the zip archive to create. .EXAMPLE - $entryCount = Compress-IslFolder -Folder $staging -Destination $zip @script:IslInternal + $entryCount = Compress-IslFolder -Folder $staging -Destination $zip Writes the staging folder of a diagnostic package into its zip and returns the number of entries. @@ -29,7 +30,7 @@ function Compress-IslFolder { .OUTPUTS System.Int32. The number of entries written. #> - [CmdletBinding(SupportsShouldProcess)] + [CmdletBinding()] [OutputType([int])] param( [Parameter(Mandatory)] @@ -39,21 +40,22 @@ function Compress-IslFolder { [string]$Destination ) - if (-not $PSCmdlet.ShouldProcess($Destination, "Compress $Folder")) { - return - } - Add-Type -AssemblyName System.IO.Compression.FileSystem - $archive = [System.IO.Compression.ZipFile]::Open($Destination, 'Create') + $archive = $null $count = 0 try { - foreach ($file in (Get-ChildItem -LiteralPath $Folder -Recurse -File)) { + Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Stop + $files = @(Get-ChildItem -LiteralPath $Folder -Recurse -File -ErrorAction Stop) + $archive = [System.IO.Compression.ZipFile]::Open($Destination, 'Create') + foreach ($file in $files) { $relative = $file.FullName.Substring($Folder.Length).TrimStart('\', '/') -replace '\\', '/' $null = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile( $archive, $file.FullName, $relative) $count++ } + } catch { + $PSCmdlet.ThrowTerminatingError($_) } finally { - $archive.Dispose() + if ($null -ne $archive) { $archive.Dispose() } } $count } diff --git a/Private/Copy-IslSharedFile.ps1 b/Private/Copy-IslSharedFile.ps1 index 6c521a9..eec0ecb 100644 --- a/Private/Copy-IslSharedFile.ps1 +++ b/Private/Copy-IslSharedFile.ps1 @@ -7,8 +7,9 @@ function Copy-IslSharedFile { The agent keeps its current log open while it writes to it. A stream that allows only other readers cannot open such a file, so the source is opened for reading with write sharing allowed, and the copy is the file as it stands at that moment. A file that is at the - destination is replaced. The command that calls this has asked ShouldProcess for the whole - package, and calls it with -WhatIf:$false and -Confirm:$false. + destination is replaced. It does not ask ShouldProcess: the command that calls it has asked + for the whole package, and it copies even when -WhatIf or -Confirm reached it through the + preferences. A failure ends the function with its error. .PARAMETER Source The full path of the file to copy. @@ -17,7 +18,7 @@ function Copy-IslSharedFile { The full path of the copy. Its folder must exist. .EXAMPLE - Copy-IslSharedFile -Source $log.FullName -Destination $copy @script:IslInternal + Copy-IslSharedFile -Source $log.FullName -Destination $copy Copies a log of the agent that the agent is still writing. @@ -27,7 +28,7 @@ function Copy-IslSharedFile { .OUTPUTS None. #> - [CmdletBinding(SupportsShouldProcess)] + [CmdletBinding()] [OutputType([void])] param( [Parameter(Mandatory)] @@ -37,14 +38,16 @@ function Copy-IslSharedFile { [string]$Destination ) - if (-not $PSCmdlet.ShouldProcess($Destination, "Copy $Source")) { - return - } - $in = [System.IO.File]::Open($Source, 'Open', 'Read', 'ReadWrite') + $in = $null + $out = $null try { + $in = [System.IO.File]::Open($Source, 'Open', 'Read', 'ReadWrite') $out = [System.IO.File]::Create($Destination) - try { $in.CopyTo($out) } finally { $out.Dispose() } + $in.CopyTo($out) + } catch { + $PSCmdlet.ThrowTerminatingError($_) } finally { - $in.Dispose() + if ($null -ne $out) { $out.Dispose() } + if ($null -ne $in) { $in.Dispose() } } } diff --git a/Private/Get-IslRegistryText.ps1 b/Private/Get-IslRegistryText.ps1 index 45355ce..73a250e 100644 --- a/Private/Get-IslRegistryText.ps1 +++ b/Private/Get-IslRegistryText.ps1 @@ -44,7 +44,7 @@ function Get-IslRegistryText { return "$Key : not present" } $children = @(Get-ChildItem -LiteralPath $Key -Recurse -Depth $Depth -ErrorAction SilentlyContinue) - $keys = @(Get-Item -LiteralPath $Key) + $children + $keys = @(Get-Item -LiteralPath $Key -ErrorAction SilentlyContinue) + $children foreach ($item in $keys) { "[$($item.Name)]" $values = Get-ItemProperty -LiteralPath $item.PSPath -ErrorAction SilentlyContinue diff --git a/Private/Write-IslTextFile.ps1 b/Private/Write-IslTextFile.ps1 index b008e29..2f78b8d 100644 --- a/Private/Write-IslTextFile.ps1 +++ b/Private/Write-IslTextFile.ps1 @@ -6,8 +6,9 @@ function Write-IslTextFile { .DESCRIPTION One section of the diagnostic package of Export-IntuneAgentDiagnostic, such as the device facts or one registry key. The folders on the way to the file are created, and a file that is - there is replaced. The command that calls this has asked ShouldProcess for the whole package, - and calls it with -WhatIf:$false and -Confirm:$false. + there is replaced. It does not ask ShouldProcess: the command that calls it has asked for the + whole package, and it writes even when -WhatIf or -Confirm reached it through the preferences. + A failure ends the function with its error. .PARAMETER Root The folder the relative path starts from. @@ -19,7 +20,7 @@ function Write-IslTextFile { The lines of the file. An empty list, or none, writes an empty file. .EXAMPLE - Write-IslTextFile -Root $staging -RelativePath 'Device\system.txt' -Line $system @script:IslInternal + Write-IslTextFile -Root $staging -RelativePath 'Device\system.txt' -Line $system Writes the device facts into the staging folder of a package. @@ -29,7 +30,7 @@ function Write-IslTextFile { .OUTPUTS None. #> - [CmdletBinding(SupportsShouldProcess)] + [CmdletBinding()] [OutputType([void])] param( [Parameter(Mandatory)] @@ -46,13 +47,14 @@ function Write-IslTextFile { ) $file = Join-Path -Path $Root -ChildPath $RelativePath - if (-not $PSCmdlet.ShouldProcess($file, 'Write the file')) { - return - } - $folder = Split-Path -Path $file -Parent - $null = New-Item -ItemType Directory -Path $folder -Force @script:IslInternal # Assigned, not taken from an if expression, which would unroll an empty array to nothing [string[]]$text = @() if ($null -ne $Line) { $text = $Line } - [System.IO.File]::WriteAllLines($file, $text, [System.Text.UTF8Encoding]::new($false)) + try { + $folder = Split-Path -Path $file -Parent + $null = New-Item -ItemType Directory -Path $folder -Force -ErrorAction Stop @script:IslInternal + [System.IO.File]::WriteAllLines($file, $text, [System.Text.UTF8Encoding]::new($false)) + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } } diff --git a/Public/Export-IntuneAgentDiagnostic.ps1 b/Public/Export-IntuneAgentDiagnostic.ps1 index 659dfd3..dc2e1a5 100644 --- a/Public/Export-IntuneAgentDiagnostic.ps1 +++ b/Public/Export-IntuneAgentDiagnostic.ps1 @@ -55,7 +55,7 @@ function Export-IntuneAgentDiagnostic { foreach ($file in $logFiles) { $destination = Join-Path -Path $logFolder -ChildPath $file.Name # A log the agent holds open is copied through a shared-read stream - Copy-IslSharedFile -Source $file.FullName -Destination $destination @script:IslInternal + Copy-IslSharedFile -Source $file.FullName -Destination $destination } $manifest.Add("Logs: $($logFiles.Count) file(s) from $LogPath") } @@ -81,11 +81,11 @@ function Export-IntuneAgentDiagnostic { if ($agentExe -and (Test-Path -LiteralPath $agentExe)) { $system.Add("Agent version: $((Get-Item -LiteralPath $agentExe).VersionInfo.FileVersion)") } - Write-IslTextFile -Root $staging -RelativePath 'Device\system.txt' -Line $system @script:IslInternal + Write-IslTextFile -Root $staging -RelativePath 'Device\system.txt' -Line $system if (Get-Command -Name dsregcmd.exe -ErrorAction SilentlyContinue) { $joinState = @(& dsregcmd.exe /status 2>&1 | ForEach-Object { "$_" }) $sectionSplat = @{ Root = $staging; RelativePath = 'Device\dsregcmd.txt'; Line = $joinState } - Write-IslTextFile @sectionSplat @script:IslInternal + Write-IslTextFile @sectionSplat $manifest.Add('Device: system.txt, dsregcmd.txt') } else { $manifest.Add('Device: system.txt (dsregcmd not available)') } @@ -104,7 +104,7 @@ function Export-IntuneAgentDiagnostic { foreach ($entry in $keys) { $lines = @(Get-IslRegistryText -Key $entry.Key -Depth $entry.Depth) $sectionSplat = @{ Root = $staging; RelativePath = "Registry\$($entry.Name).txt"; Line = $lines } - Write-IslTextFile @sectionSplat @script:IslInternal + Write-IslTextFile @sectionSplat } $manifest.Add("Registry: $(($keys | ForEach-Object { $_.Name }) -join ', ')") } @@ -132,14 +132,14 @@ function Export-IntuneAgentDiagnostic { else { $manifest.Add('Timeline: skipped') } $manifest.Insert(0, "IntuneScriptLab diagnostic package, $((Get-Date).ToString('yyyy-MM-dd HH:mm:ss'))") - Write-IslTextFile -Root $staging -RelativePath 'Manifest.txt' -Line $manifest @script:IslInternal + Write-IslTextFile -Root $staging -RelativePath 'Manifest.txt' -Line $manifest if (Test-Path -LiteralPath $zip) { Remove-Item -LiteralPath $zip -Force @script:IslInternal } $zipFolder = Split-Path -Path $zip -Parent if ($zipFolder -and -not (Test-Path -LiteralPath $zipFolder)) { $null = New-Item -ItemType Directory -Path $zipFolder -Force @script:IslInternal } - $entryCount = Compress-IslFolder -Folder $staging -Destination $zip @script:IslInternal + $entryCount = Compress-IslFolder -Folder $staging -Destination $zip } catch { # Whatever failed, the package is not complete: the command ends without a result diff --git a/Tests/Unit/Private/Compress-IslFolder.Tests.ps1 b/Tests/Unit/Private/Compress-IslFolder.Tests.ps1 index 58a3b5b..d09077b 100644 --- a/Tests/Unit/Private/Compress-IslFolder.Tests.ps1 +++ b/Tests/Unit/Private/Compress-IslFolder.Tests.ps1 @@ -25,7 +25,7 @@ Describe 'Compress-IslFolder' -Tag 'Unit', 'Private' { It 'writes one entry for each file, named with forward slashes, and returns the count' { $zip = Join-Path $TestDrive 'package.zip' $count = InModuleScope IntuneScriptLab -Parameters @{ Folder = $script:Folder; Zip = $zip } { - Compress-IslFolder -Folder $Folder -Destination $Zip @script:IslInternal + Compress-IslFolder -Folder $Folder -Destination $Zip } $archive = [System.IO.Compression.ZipFile]::OpenRead($zip) @@ -41,12 +41,26 @@ Describe 'Compress-IslFolder' -Tag 'Unit', 'Private' { $names[2] | Should-Be 'Registry/Deep/Key.txt' } - It 'writes no archive under -WhatIf' { + It 'writes the archive when -WhatIf reached it through the preference, as the command has asked' { $zip = Join-Path $TestDrive 'preview.zip' - InModuleScope IntuneScriptLab -Parameters @{ Folder = $script:Folder; Zip = $zip } { - Compress-IslFolder -Folder $Folder -Destination $Zip -WhatIf + $count = InModuleScope IntuneScriptLab -Parameters @{ Folder = $script:Folder; Zip = $zip } { + $WhatIfPreference = $true + Compress-IslFolder -Folder $Folder -Destination $Zip } - Test-Path -LiteralPath $zip | Should-BeFalse + $count | Should-Be 3 + Test-Path -LiteralPath $zip | Should-BeTrue + } + + It 'ends with an error when the archive is there already, and leaves it as it was' { + $zip = Join-Path $TestDrive 'taken.zip' + [System.IO.File]::WriteAllText($zip, 'not a zip') + + { + InModuleScope IntuneScriptLab -Parameters @{ Folder = $script:Folder; Zip = $zip } { + Compress-IslFolder -Folder $Folder -Destination $Zip + } + } | Should-Throw -ExceptionMessage '*taken.zip*' + [System.IO.File]::ReadAllText($zip) | Should-Be 'not a zip' } } diff --git a/Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 b/Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 index 01e72b8..37a9615 100644 --- a/Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 +++ b/Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 @@ -13,7 +13,7 @@ BeforeAll { function script:Copy-Shared { param([string]$Source, [string]$Destination) InModuleScope IntuneScriptLab -Parameters @{ Source = $Source; Destination = $Destination } { - Copy-IslSharedFile -Source $Source -Destination $Destination @script:IslInternal + Copy-IslSharedFile -Source $Source -Destination $Destination } } } @@ -54,6 +54,20 @@ Describe 'Copy-IslSharedFile' -Tag 'Unit', 'Private' { It 'ends with an error for a source that is not there' { $missing = Join-Path $TestDrive 'not-there.log' - { Copy-Shared -Source $missing -Destination (Join-Path $TestDrive 'never.log') } | Should-Throw + $never = Join-Path $TestDrive 'never.log' + { Copy-Shared -Source $missing -Destination $never } | Should-Throw -ExceptionMessage '*not-there.log*' + Test-Path -LiteralPath $never | Should-BeFalse + } + + It 'copies when -WhatIf reached it through the preference, as the command has asked' { + $source = Join-Path $TestDrive 'Preview.log' + $destination = Join-Path $TestDrive 'copy-preview.log' + [System.IO.File]::WriteAllText($source, 'previewed') + InModuleScope IntuneScriptLab -Parameters @{ Source = $source; Destination = $destination } { + $WhatIfPreference = $true + Copy-IslSharedFile -Source $Source -Destination $Destination + } + + [System.IO.File]::ReadAllText($destination) | Should-Be 'previewed' } } diff --git a/Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 b/Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 index fe05174..e9a5e49 100644 --- a/Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 @@ -57,6 +57,36 @@ Describe 'Get-IslRegistryText' -Tag 'Unit', 'Private' { @($deep | Where-Object { $_ -like '`[*Grandchild`]' }) | Should-BeCollection -Count 1 } + It 'passes over a key that is there but cannot be read, without an error' { + # A key in the test registry that the current user may not read; Test-Path still finds it + $null = New-Item -Path 'TestRegistry:\Denied\Child' -Force + $root = (Get-PSDrive -Name TestRegistry).Root -replace '^HKEY_CURRENT_USER\\', '' + $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User + $rights = [System.Security.AccessControl.RegistryRights]::ReadKey + $deny = [System.Security.AccessControl.RegistryAccessRule]::new($user, $rights, 'Deny') + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey( + "$root\Denied", [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, + [System.Security.AccessControl.RegistryRights]::ChangePermissions) + $sections = [System.Security.AccessControl.AccessControlSections]::Access + $acl = $key.GetAccessControl($sections) + $acl.AddAccessRule($deny) + $key.SetAccessControl($acl) + try { + $output = InModuleScope IntuneScriptLab { + Get-IslRegistryText -Key 'TestRegistry:\Denied' -Depth 1 -ErrorAction Continue 2>&1 + } + } finally { + # Pester removes the test registry after the file, which the rule would stop + $acl = $key.GetAccessControl($sections) + $null = $acl.RemoveAccessRule($deny) + $key.SetAccessControl($acl) + $key.Dispose() + } + + @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) | Should-BeCollection @() + @($output) | Should-BeCollection @() + } + It 'gives one line for a key that is not there' { $missing = 'TestRegistry:\NotThere' Get-Text -Key $missing -Depth 1 | Should-BeCollection @("$missing : not present") diff --git a/Tests/Unit/Private/Write-IslTextFile.Tests.ps1 b/Tests/Unit/Private/Write-IslTextFile.Tests.ps1 index 3adfaf0..70a60fe 100644 --- a/Tests/Unit/Private/Write-IslTextFile.Tests.ps1 +++ b/Tests/Unit/Private/Write-IslTextFile.Tests.ps1 @@ -14,7 +14,7 @@ BeforeAll { param([string]$Root, [string]$RelativePath, [AllowNull()][string[]]$Line) $parameters = @{ Root = $Root; RelativePath = $RelativePath; Line = $Line } InModuleScope IntuneScriptLab -Parameters @{ Parameters = $parameters } { - Write-IslTextFile @Parameters @script:IslInternal + Write-IslTextFile @Parameters } } } @@ -52,11 +52,20 @@ Describe 'Write-IslTextFile' -Tag 'Unit', 'Private' { [System.IO.File]::ReadAllLines((Join-Path $script:Root 'Manifest.txt')) | Should-BeCollection @('new') } - It 'writes nothing under -WhatIf' { + It 'writes the file when -WhatIf reached it through the preference, as the command has asked' { InModuleScope IntuneScriptLab -Parameters @{ Root = $script:Root } { - Write-IslTextFile -Root $Root -RelativePath 'Preview\x.txt' -Line 'x' -WhatIf + $WhatIfPreference = $true + Write-IslTextFile -Root $Root -RelativePath 'Preview\x.txt' -Line 'x' } - Test-Path -LiteralPath (Join-Path $script:Root 'Preview') | Should-BeFalse + [System.IO.File]::ReadAllLines((Join-Path $script:Root 'Preview\x.txt')) | Should-BeCollection @('x') + } + + It 'ends with an error when the file cannot be written' { + # A folder in the place of the file + $null = New-Item -ItemType Directory -Path (Join-Path $script:Root 'Manifest.txt') + + { Write-Section -Root $script:Root -RelativePath 'Manifest.txt' -Line 'x' } | + Should-Throw -ExceptionMessage '*Manifest.txt*' } } From 65ba5c3cfd8a0e63edde63191886fd158d35f3c9 Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:34:24 -0800 Subject: [PATCH 4/4] fix(diagnostic): keep logs, PS values and backreferences in the helpers A review of the helpers moved out of Export-IntuneAgentDiagnostic, Get-IslAgentLogEvent and Invoke-IslGraphRequest found older bugs that the moved code carried along. - Get-IslRegistryText dropped every value whose name starts with PS. It now leaves out only the five provider properties. Its help also says what -Depth counts: N gives N + 1 levels of subkeys. - Copy-IslSharedFile shared the source for reading and writing only, so a writer holding a log with delete access kept it out, and a log could not be renamed while it was copied. It shares Delete as well, and removes a part copy when the copy fails. - Export-IntuneAgentDiagnostic ended with no package when one log could not be copied. Following ERR-13, it reports that log with WriteError, names it in the manifest, and writes the rest; -ErrorAction Stop still ends it there. - Compress-IslFolder left a valid but incomplete zip at the destination when it failed part way. It removes the archive it created; one that was there before is left alone. - Get-IslRegexLiteralPrefix gave the first alternative's text for a pattern with a top-level |, so the needle of Get-IntuneAgentLog -EventName would have skipped lines of the other alternatives. Such a pattern now gives an empty string. - ConvertTo-IslNamedGroupPattern left \1 and \k<1> as they were, and in the joined expression they named another pattern's group. They now name the pattern's own renamed group. - Get-IslGraphRetryDelay read Headers.RetryAfter with member syntax, which under strict mode wrote an error for a response without that member and ended the request under -ErrorAction Stop. It reads the members by name and falls back to the doubling delay. - STY-02: elseif and else follow the closing brace in the new files. --- CHANGELOG.md | 23 ++++++++ Private/Compress-IslFolder.ps1 | 20 ++++++- Private/ConvertTo-IslNamedGroupPattern.ps1 | 47 ++++++++++++++-- Private/Copy-IslSharedFile.ps1 | 25 +++++++-- Private/Get-IslGraphRetryDelay.ps1 | 35 ++++++++---- Private/Get-IslRegexLiteralPrefix.ps1 | 25 ++++++++- Private/Get-IslRegistryText.ps1 | 22 +++++--- Public/Export-IntuneAgentDiagnostic.ps1 | 20 +++++-- .../Unit/Private/Compress-IslFolder.Tests.ps1 | 18 +++++++ .../ConvertTo-IslNamedGroupPattern.Tests.ps1 | 22 ++++++++ .../Unit/Private/Copy-IslSharedFile.Tests.ps1 | 42 +++++++++++++++ .../Private/Get-IslGraphRetryDelay.Tests.ps1 | 15 ++++++ .../Get-IslRegexLiteralPrefix.Tests.ps1 | 15 ++++++ .../Private/Get-IslRegistryText.Tests.ps1 | 18 +++++-- .../Export-IntuneAgentDiagnostic.Tests.ps1 | 53 +++++++++++++++++++ .../Export-IntuneAgentDiagnostic.md | 7 ++- en-US/IntuneScriptLab-Help.xml | 9 +++- 17 files changed, 376 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f73ad1..0895c83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -152,6 +152,29 @@ entries are carried over from the manifest's release notes. ### Fixed +- `Export-IntuneAgentDiagnostic` left every registry value whose name starts with `PS`, such as + `PSVersion`, out of the registry text. Only the five properties that the PowerShell provider + adds to each key are left out now. +- One log that `Export-IntuneAgentDiagnostic` could not copy ended the whole export with no + package. A log is now opened with delete sharing as well, so a writer that holds it with delete + access does not keep it out, and the agent can rename or rotate it during the copy. A log that + still cannot be copied, such as one that rotated away after the folder was listed, is reported + as a non-terminating error and named on a "Logs not copied" line of the manifest, and the rest + of the package is written; `-ErrorAction Stop` ends the export there. A failure while the zip + is written no longer leaves an incomplete zip at the destination, which under `-Force` had + already replaced the earlier package. +- `Get-IntuneAgentLog -EventName` would have skipped lines of an event whose pattern has + alternatives at its top level, such as `Script failed|Script timed out`: the text the pattern + starts with, which the reader looks for before it runs the pattern, was taken from the first + alternative only. Such a pattern now has no such text and every line is tried. A numbered + backreference in an event pattern, such as `\1`, referred to a group of another pattern once + the reader joined the patterns into one, and it now refers to the pattern's own group. No event + pattern of the module has either; the reader is ready for one that does. +- A Graph request that failed with 429, 503 or 504 and whose response had no `RetryAfter` member, + such as the `HttpWebResponse` of a `WebException`, wrote the strict-mode error "The property + 'RetryAfter' cannot be found" before it tried again, and under `-ErrorAction Stop` ended with + that error in place of Graph's own, which hid the status code from the caller. It now waits the + doubling delay and tries again without an error. - A test of `New-IslFinding` left out a mandatory parameter and expected an error. A host that can prompt asks for the value instead, so the suites waited for an answer at a console and wherever the standard input stayed open. The test reads the parameters from the command now, and a new diff --git a/Private/Compress-IslFolder.ps1 b/Private/Compress-IslFolder.ps1 index b5a4e23..bb156f5 100644 --- a/Private/Compress-IslFolder.ps1 +++ b/Private/Compress-IslFolder.ps1 @@ -10,7 +10,9 @@ function Compress-IslFolder { the folder with forward slashes, on every host. Empty folders are not kept. The archive must not exist yet. It does not ask ShouldProcess: the command that calls it has asked for the whole package, and it writes even when -WhatIf or -Confirm reached it through the - preferences. A failure ends the function with its error. + preferences. A failure ends the function with its error. An archive that this call created + and could not fill is removed, so a failure leaves no archive that looks complete; one that + was there before the call is left as it is. .PARAMETER Folder The full path of the folder to compress, without a trailing separator. @@ -53,7 +55,21 @@ function Compress-IslFolder { $count++ } } catch { - $PSCmdlet.ThrowTerminatingError($_) + $failure = $_ + if ($null -ne $archive) { + # Disposing writes the central directory, which makes the part archive a valid zip + $partArchive = $archive + $archive = $null + try { + $partArchive.Dispose() + [System.IO.File]::Delete($Destination) + } catch { + # The compression's own failure is the one to report; the archive that stays is named + $reason = $_.Exception.Message + Write-Warning "The incomplete archive at $Destination could not be removed: $reason" + } + } + $PSCmdlet.ThrowTerminatingError($failure) } finally { if ($null -ne $archive) { $archive.Dispose() } } diff --git a/Private/ConvertTo-IslNamedGroupPattern.ps1 b/Private/ConvertTo-IslNamedGroupPattern.ps1 index b99caf6..d35160d 100644 --- a/Private/ConvertTo-IslNamedGroupPattern.ps1 +++ b/Private/ConvertTo-IslNamedGroupPattern.ps1 @@ -10,6 +10,13 @@ function ConvertTo-IslNamedGroupPattern { (?...), is left as it is, and so is a parenthesis that is escaped or inside a character class. + In the joined pattern every group has a name, and .NET numbers groups across the whole + expression, so a numbered backreference such as \1 would refer to a group of another + pattern. A backreference \n or \k outside a character class, whose n is one of the + pattern's own groups, is therefore written as \k. A larger number is left as it + is, as .NET reads it on its own, and so is a conditional that names a group by number, such + as (?(1)...), which no event pattern uses. + .PARAMETER Pattern The regular expression. @@ -38,29 +45,59 @@ function ConvertTo-IslNamedGroupPattern { [string]$Prefix ) - $named = [System.Text.StringBuilder]::new() + # A backreference can come before the last group, so the text is kept in pieces and a + # backreference is resolved once the number of groups is known + $pieces = [System.Collections.Generic.List[object]]::new() + $text = [System.Text.StringBuilder]::new() + $backreference = [regex]::new('\G\\(?:([1-9][0-9]*)|k<([1-9][0-9]*)>)') $count = 0 $inClass = $false for ($index = 0; $index -lt $Pattern.Length; $index++) { $character = $Pattern[$index] if ($character -eq '\' -and $index + 1 -lt $Pattern.Length) { - $null = $named.Append($character).Append($Pattern[$index + 1]) + $reference = $null + if (-not $inClass) { $reference = $backreference.Match($Pattern, $index) } + if ($null -ne $reference -and $reference.Success) { + $pieces.Add($text.ToString()) + $null = $text.Clear() + $digits = $reference.Groups[2].Value + if ($reference.Groups[1].Success) { $digits = $reference.Groups[1].Value } + # More digits than nine is more groups than any pattern has + $number = [int]::MaxValue + if ($digits.Length -le 9) { $number = [int]$digits } + $pieces.Add(@{ Number = $number; Text = $reference.Value }) + $index += $reference.Length - 1 + continue + } + $null = $text.Append($character).Append($Pattern[$index + 1]) $index++ continue } if ($inClass) { if ($character -eq ']') { $inClass = $false } - $null = $named.Append($character) + $null = $text.Append($character) continue } if ($character -eq '[') { $inClass = $true } $opensCapture = $character -eq '(' -and ($index + 1 -ge $Pattern.Length -or $Pattern[$index + 1] -ne '?') if ($opensCapture) { $count++ - $null = $named.Append("(?<$Prefix$count>") + $null = $text.Append("(?<$Prefix$count>") continue } - $null = $named.Append($character) + $null = $text.Append($character) + } + $pieces.Add($text.ToString()) + + $named = [System.Text.StringBuilder]::new() + foreach ($piece in $pieces) { + if ($piece -is [string]) { + $null = $named.Append($piece) + } elseif ($piece['Number'] -le $count) { + $null = $named.Append("\k<$Prefix$($piece['Number'])>") + } else { + $null = $named.Append($piece['Text']) + } } @{ Pattern = $named.ToString(); Count = $count } } diff --git a/Private/Copy-IslSharedFile.ps1 b/Private/Copy-IslSharedFile.ps1 index eec0ecb..831c766 100644 --- a/Private/Copy-IslSharedFile.ps1 +++ b/Private/Copy-IslSharedFile.ps1 @@ -5,11 +5,14 @@ function Copy-IslSharedFile { .DESCRIPTION The agent keeps its current log open while it writes to it. A stream that allows only - other readers cannot open such a file, so the source is opened for reading with write - sharing allowed, and the copy is the file as it stands at that moment. A file that is at the + other readers cannot open such a file, so the source is opened for reading with write and + delete sharing allowed, and the copy is the file as it stands at that moment. Delete sharing + lets a writer that holds the file with delete access open it, and lets the file be renamed + or removed while it is copied, as a log is when it rotates. A file that is at the destination is replaced. It does not ask ShouldProcess: the command that calls it has asked for the whole package, and it copies even when -WhatIf or -Confirm reached it through the - preferences. A failure ends the function with its error. + preferences. A failure ends the function with its error; a copy that failed after the + destination was created is removed, so no part of a file is left there. .PARAMETER Source The full path of the file to copy. @@ -41,11 +44,23 @@ function Copy-IslSharedFile { $in = $null $out = $null try { - $in = [System.IO.File]::Open($Source, 'Open', 'Read', 'ReadWrite') + $in = [System.IO.File]::Open($Source, 'Open', 'Read', 'ReadWrite, Delete') $out = [System.IO.File]::Create($Destination) $in.CopyTo($out) } catch { - $PSCmdlet.ThrowTerminatingError($_) + $failure = $_ + if ($null -ne $out) { + $partCopy = $out + $out = $null + try { + $partCopy.Dispose() + [System.IO.File]::Delete($Destination) + } catch { + # The copy's own failure is the one to report; the part copy that stays is named + Write-Warning "The part copy at $Destination could not be removed: $($_.Exception.Message)" + } + } + $PSCmdlet.ThrowTerminatingError($failure) } finally { if ($null -ne $out) { $out.Dispose() } if ($null -ne $in) { $in.Dispose() } diff --git a/Private/Get-IslGraphRetryDelay.ps1 b/Private/Get-IslGraphRetryDelay.ps1 index 9a6adfc..ad384b5 100644 --- a/Private/Get-IslGraphRetryDelay.ps1 +++ b/Private/Get-IslGraphRetryDelay.ps1 @@ -9,7 +9,9 @@ function Get-IslGraphRetryDelay { or as a date, and otherwise 2 to the power of the attempt; it is at most 60 seconds. For any other failure there is nothing to wait for, and the function returns nothing. The status code and the response are read from Invoke-MgGraphRequest's exception by name, so an exception - of another type with the same members serves in the tests. + of another type with the same members serves in the tests. A response without a Retry-After + header, or of a type that has no RetryAfter member, such as the HttpWebResponse of a + WebException, gets the doubling delay. .PARAMETER ErrorRecord The error of the request that failed. @@ -41,19 +43,34 @@ function Get-IslGraphRetryDelay { $exception = $ErrorRecord.Exception $status = 0 - if ($exception.PSObject.Properties['StatusCode'] -and $exception.StatusCode) { - $status = [int]$exception.StatusCode + $exceptionStatus = Get-IslPropertyValue -InputObject $exception -Name 'StatusCode' + if ($exceptionStatus) { $status = [int]$exceptionStatus } + $response = Get-IslPropertyValue -InputObject $exception -Name 'Response' + if (-not $status -and $response) { + $responseStatus = Get-IslPropertyValue -InputObject $response -Name 'StatusCode' + if ($responseStatus) { $status = [int]$responseStatus } } - $response = if ($exception.PSObject.Properties['Response']) { $exception.Response } else { $null } - if (-not $status -and $response) { $status = [int]$response.StatusCode } if ($status -notin 429, 503, 504) { return } $delay = 0 - $retryAfter = if ($response) { $response.Headers.RetryAfter } else { $null } + # Headers.RetryAfter is a member of HttpResponseMessage only. The response of another type, + # such as the HttpWebResponse of a WebException, has no such member and gets the doubling + # delay. The headers are a collection, which a function would unroll into its entries, so + # they are read here and not through Get-IslPropertyValue + $retryAfter = $null + $headersProperty = $null + if ($null -ne $response) { $headersProperty = $response.PSObject.Properties['Headers'] } + if ($null -ne $headersProperty -and $null -ne $headersProperty.Value) { + $retryProperty = $headersProperty.Value.PSObject.Properties['RetryAfter'] + if ($null -ne $retryProperty) { $retryAfter = $retryProperty.Value } + } if ($retryAfter) { - if ($null -ne $retryAfter.Delta) { $delay = [Math]::Ceiling($retryAfter.Delta.TotalSeconds) } - elseif ($null -ne $retryAfter.Date) { - $delay = [Math]::Ceiling(($retryAfter.Date.UtcDateTime - [datetime]::UtcNow).TotalSeconds) + $retryDelta = Get-IslPropertyValue -InputObject $retryAfter -Name 'Delta' + $retryDate = Get-IslPropertyValue -InputObject $retryAfter -Name 'Date' + if ($null -ne $retryDelta) { + $delay = [Math]::Ceiling($retryDelta.TotalSeconds) + } elseif ($null -ne $retryDate) { + $delay = [Math]::Ceiling(($retryDate.UtcDateTime - [datetime]::UtcNow).TotalSeconds) } } if ($delay -lt 1) { $delay = [Math]::Pow(2, $Attempt) } diff --git a/Private/Get-IslRegexLiteralPrefix.ps1 b/Private/Get-IslRegexLiteralPrefix.ps1 index 545e764..687b792 100644 --- a/Private/Get-IslRegexLiteralPrefix.ps1 +++ b/Private/Get-IslRegexLiteralPrefix.ps1 @@ -9,7 +9,9 @@ function Get-IslRegexLiteralPrefix { read up to the first metacharacter. A leading ^ is skipped, an escaped punctuation character counts as itself, and an escaped letter or digit ends the text, because it stands for a class. When a quantifier follows the text, its last character is optional in the pattern and - is left out. + is left out. A pattern with a | outside every group and character class, such as + 'Script failed|Script timed out', has alternatives that need not share any text, and gives + an empty string. .PARAMETER Pattern The regular expression. @@ -24,7 +26,7 @@ function Get-IslRegexLiteralPrefix { .OUTPUTS System.String. The literal text, or an empty string when the pattern starts with a - metacharacter. + metacharacter or has alternatives at its top level. #> [CmdletBinding()] [OutputType([string])] @@ -33,6 +35,25 @@ function Get-IslRegexLiteralPrefix { [string]$Pattern ) + $depth = 0 + $inClass = $false + for ($index = 0; $index -lt $Pattern.Length; $index++) { + $character = $Pattern[$index] + if ($character -eq '\') { + $index++ + } elseif ($inClass) { + if ($character -eq ']') { $inClass = $false } + } elseif ($character -eq '[') { + $inClass = $true + } elseif ($character -eq '(') { + $depth++ + } elseif ($character -eq ')') { + if ($depth -gt 0) { $depth-- } + } elseif ($character -eq '|' -and $depth -eq 0) { + return '' + } + } + $literal = [System.Text.StringBuilder]::new() $index = if ($Pattern.StartsWith('^')) { 1 } else { 0 } while ($index -lt $Pattern.Length) { diff --git a/Private/Get-IslRegistryText.ps1 b/Private/Get-IslRegistryText.ps1 index 73a250e..3729328 100644 --- a/Private/Get-IslRegistryText.ps1 +++ b/Private/Get-IslRegistryText.ps1 @@ -5,8 +5,10 @@ function Get-IslRegistryText { .DESCRIPTION For the registry sections of the diagnostic package. Each key is a line "[name]", followed - by one line " name = value" for each of its values. The PowerShell provider's own properties - are left out, binary values are shown by their length, and a value longer than 400 + by one line " name = value" for each of its values. The five properties that the PowerShell + provider adds to every key (PSPath, PSParentPath, PSChildName, PSDrive and PSProvider) are + left out, and a value of the key whose name only starts with PS, such as PSVersion, is kept. + Binary values are shown by their length, and a value longer than 400 characters is cut there and marked with "...". A key or a subkey that cannot be read is passed over without an error; a key that is not there gives the one line " : not present". @@ -16,12 +18,14 @@ function Get-IslRegistryText { HKLM:\SOFTWARE\Microsoft\IntuneManagementExtension. .PARAMETER Depth - How many levels of subkeys below the key are included. + How many levels below the key's own subkeys are included, as Get-ChildItem -Depth counts + them: 0 gives the key and its subkeys, and each step adds one more level, so Depth N gives + N + 1 levels of subkeys. .EXAMPLE Get-IslRegistryText -Key 'HKLM:\SOFTWARE\Microsoft\IntuneManagementExtension\Policies' -Depth 2 - The policy keys of the agent, two levels down. + The policy keys of the agent, three levels of subkeys down. .INPUTS None. @@ -45,14 +49,18 @@ function Get-IslRegistryText { } $children = @(Get-ChildItem -LiteralPath $Key -Recurse -Depth $Depth -ErrorAction SilentlyContinue) $keys = @(Get-Item -LiteralPath $Key -ErrorAction SilentlyContinue) + $children + $providerProperties = 'PSPath', 'PSParentPath', 'PSChildName', 'PSDrive', 'PSProvider' foreach ($item in $keys) { "[$($item.Name)]" $values = Get-ItemProperty -LiteralPath $item.PSPath -ErrorAction SilentlyContinue if (-not $values) { continue } foreach ($property in $values.PSObject.Properties) { - if ($property.Name -like 'PS*') { continue } - $text = if ($property.Value -is [byte[]]) { "byte[$($property.Value.Length)]" } - else { "$($property.Value)" } + if ($property.Name -in $providerProperties) { continue } + if ($property.Value -is [byte[]]) { + $text = "byte[$($property.Value.Length)]" + } else { + $text = "$($property.Value)" + } if ($text.Length -gt 400) { $text = $text.Substring(0, 400) + '...' } " $($property.Name) = $text" } diff --git a/Public/Export-IntuneAgentDiagnostic.ps1 b/Public/Export-IntuneAgentDiagnostic.ps1 index dc2e1a5..569f7a8 100644 --- a/Public/Export-IntuneAgentDiagnostic.ps1 +++ b/Public/Export-IntuneAgentDiagnostic.ps1 @@ -48,16 +48,28 @@ function Export-IntuneAgentDiagnostic { # Logs $logFiles = @() + $copiedCount = 0 if (Test-Path -LiteralPath $LogPath -PathType Container) { $logFiles = @(Get-ChildItem -LiteralPath $LogPath -Filter '*.log' -File) $logFolder = Join-Path -Path $staging -ChildPath 'Logs' $null = New-Item -ItemType Directory -Path $logFolder -Force @script:IslInternal + $notCopied = [System.Collections.Generic.List[string]]::new() foreach ($file in $logFiles) { $destination = Join-Path -Path $logFolder -ChildPath $file.Name - # A log the agent holds open is copied through a shared-read stream - Copy-IslSharedFile -Source $file.FullName -Destination $destination + try { + # A log the agent holds open is copied through a shared-read stream + Copy-IslSharedFile -Source $file.FullName -Destination $destination + } catch { + # One log that cannot be read, or that rotated away since the folder was + # listed, is one item of the package: it is reported and the rest is written + $PSCmdlet.WriteError($_) + $notCopied.Add($file.Name) + continue + } + $copiedCount++ } - $manifest.Add("Logs: $($logFiles.Count) file(s) from $LogPath") + $manifest.Add("Logs: $copiedCount file(s) from $LogPath") + if ($notCopied.Count) { $manifest.Add("Logs not copied: $($notCopied -join ', ')") } } else { $manifest.Add("Logs: folder not found: $LogPath") @@ -154,7 +166,7 @@ function Export-IntuneAgentDiagnostic { PSTypeName = 'IntuneScriptLab.Diagnostic' Path = $zip Files = $entryCount - Logs = $logFiles.Count + Logs = $copiedCount Registry = -not $SkipRegistry Timeline = (-not $SkipTimeline) -and $logFiles.Count -gt 0 SizeBytes = (Get-Item -LiteralPath $zip).Length diff --git a/Tests/Unit/Private/Compress-IslFolder.Tests.ps1 b/Tests/Unit/Private/Compress-IslFolder.Tests.ps1 index d09077b..f646a36 100644 --- a/Tests/Unit/Private/Compress-IslFolder.Tests.ps1 +++ b/Tests/Unit/Private/Compress-IslFolder.Tests.ps1 @@ -52,6 +52,24 @@ Describe 'Compress-IslFolder' -Tag 'Unit', 'Private' { Test-Path -LiteralPath $zip | Should-BeTrue } + It 'ends with an error and leaves no archive when a file cannot be added' { + $zip = Join-Path $TestDrive 'part.zip' + $locked = Join-Path $script:Folder 'Registry\Deep\Key.txt' + # A stream that writes to the file and shares only reading keeps the archive from opening it + $holder = [System.IO.File]::Open($locked, 'Open', 'ReadWrite', 'Read') + try { + { + InModuleScope IntuneScriptLab -Parameters @{ Folder = $script:Folder; Zip = $zip } { + Compress-IslFolder -Folder $Folder -Destination $Zip + } + } | Should-Throw -ExceptionMessage '*Key.txt*' + } finally { + $holder.Dispose() + } + + Test-Path -LiteralPath $zip | Should-BeFalse + } + It 'ends with an error when the archive is there already, and leaves it as it was' { $zip = Join-Path $TestDrive 'taken.zip' [System.IO.File]::WriteAllText($zip, 'not a zip') diff --git a/Tests/Unit/Private/ConvertTo-IslNamedGroupPattern.Tests.ps1 b/Tests/Unit/Private/ConvertTo-IslNamedGroupPattern.Tests.ps1 index 2cd394d..8887aeb 100644 --- a/Tests/Unit/Private/ConvertTo-IslNamedGroupPattern.Tests.ps1 +++ b/Tests/Unit/Private/ConvertTo-IslNamedGroupPattern.Tests.ps1 @@ -29,6 +29,13 @@ Describe 'ConvertTo-IslNamedGroupPattern' -Tag 'Unit', 'Private' { @{ Pattern = 'a\(b\)'; Expected = 'a\(b\)'; Count = 0 } @{ Pattern = 'a[(]b(c)'; Expected = 'a[(]b(?c)'; Count = 1 } @{ Pattern = 'plain text'; Expected = 'plain text'; Count = 0 } + @{ Pattern = '^(\w+) .* \1$'; Expected = '^(?\w+) .* \k$'; Count = 1 } + @{ Pattern = '\2(a)(b)'; Expected = '\k(?a)(?b)'; Count = 2 } + @{ Pattern = '(a)\k<1>'; Expected = '(?a)\k'; Count = 1 } + @{ Pattern = '(a)[\1]'; Expected = '(?a)[\1]'; Count = 1 } + @{ Pattern = '(a)\\1'; Expected = '(?a)\\1'; Count = 1 } + @{ Pattern = '(a)\0'; Expected = '(?a)\0'; Count = 1 } + @{ Pattern = '(a)\12'; Expected = '(?a)\12'; Count = 1 } ) { $result = ConvertTo-Named -Pattern $Pattern @@ -48,4 +55,19 @@ Describe 'ConvertTo-IslNamedGroupPattern' -Tag 'Unit', 'Private' { $renamed.Groups['e3g1'].Value | Should-Be $original.Groups[1].Value $renamed.Groups['e3g2'].Value | Should-Be $original.Groups[2].Value } + + It 'keeps a backreference to its own group when the pattern is joined after another' { + $first = InModuleScope IntuneScriptLab { ConvertTo-IslNamedGroupPattern -Pattern '^(x)y' -Prefix 'e0g' } + $second = InModuleScope IntuneScriptLab { + ConvertTo-IslNamedGroupPattern -Pattern '^(\w+) and \1$' -Prefix 'e1g' + } + $joined = "(?$($first['Pattern']))|(?$($second['Pattern']))" + + $match = [regex]::Match('same and same', $joined) + + $match.Success | Should-BeTrue + $match.Groups['e1'].Success | Should-BeTrue + $match.Groups['e1g1'].Value | Should-Be 'same' + [regex]::IsMatch('same and other', $joined) | Should-BeFalse + } } diff --git a/Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 b/Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 index 37a9615..2e749d1 100644 --- a/Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 +++ b/Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 @@ -40,6 +40,48 @@ Describe 'Copy-IslSharedFile' -Tag 'Unit', 'Private' { [System.IO.File]::ReadAllText($destination) | Should-Be "line one`r`n" } + It 'copies a file that a writer holds with delete access, as one that rotates its log does' { + $source = Join-Path $TestDrive 'Rotating.log' + $destination = Join-Path $TestDrive 'copy-rotating.log' + $rights = [System.Security.AccessControl.FileSystemRights]'Write, Delete' + $share = [System.IO.FileShare]'ReadWrite, Delete' + if ($PSVersionTable.PSVersion -lt [version]'6.0') { + $writer = [System.IO.FileStream]::new($source, 'Create', $rights, $share, 4096, 'None') + } else { + $writer = [System.IO.FileSystemAclExtensions]::Create( + [System.IO.FileInfo]$source, 'Create', $rights, $share, 4096, 'None', $null) + } + try { + $bytes = [System.Text.Encoding]::ASCII.GetBytes("rotating`r`n") + $writer.Write($bytes, 0, $bytes.Length) + $writer.Flush() + # What delete sharing is for: a reader that shares only reading and writing is refused + { [System.IO.File]::Open($source, 'Open', 'Read', 'ReadWrite').Dispose() } | Should-Throw + + Copy-Shared -Source $source -Destination $destination + } finally { + $writer.Dispose() + } + + [System.IO.File]::ReadAllText($destination) | Should-Be "rotating`r`n" + } + + It 'removes the part copy when the source cannot be read to its end' { + $source = Join-Path $TestDrive 'Locked.log' + $destination = Join-Path $TestDrive 'copy-locked.log' + [System.IO.File]::WriteAllText($source, ('x' * 1000)) + # A byte range that another stream has locked cannot be read, though the file opens + $holder = [System.IO.File]::Open($source, 'Open', 'ReadWrite', 'ReadWrite, Delete') + try { + $holder.Lock(0, 1000) + { Copy-Shared -Source $source -Destination $destination } | Should-Throw -ExceptionMessage '*lock*' + } finally { + $holder.Dispose() + } + + Test-Path -LiteralPath $destination | Should-BeFalse + } + It 'replaces a file that is at the destination' { $source = Join-Path $TestDrive 'Agent.log' $destination = Join-Path $TestDrive 'copy-replaced.log' diff --git a/Tests/Unit/Private/Get-IslGraphRetryDelay.Tests.ps1 b/Tests/Unit/Private/Get-IslGraphRetryDelay.Tests.ps1 index cf96f74..6d0796f 100644 --- a/Tests/Unit/Private/Get-IslGraphRetryDelay.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslGraphRetryDelay.Tests.ps1 @@ -74,6 +74,21 @@ Describe 'Get-IslGraphRetryDelay' -Tag 'Unit', 'Private' { @(Get-Delay -Record (New-GraphFailureRecord -StatusCode $Status) -Attempt 1) | Should-BeCollection @() } + It 'doubles the wait for a whose response has no RetryAfter member' -ForEach @( + @{ Status = 503 } + @{ Status = 429 } + ) { + # The shape of a WebException's HttpWebResponse: a status code and a header collection + # that holds Retry-After as text, with no RetryAfter member + $headers = [System.Net.WebHeaderCollection]::new() + $headers.Add('Retry-After', '7') + $failure = [RetryDelayGraphException]::new("Response status code does not indicate success: $Status") + $failure.Response = [pscustomobject]@{ StatusCode = $Status; Headers = $headers } + $record = [System.Management.Automation.ErrorRecord]::new($failure, 'WebFailure', 'InvalidResult', $null) + + Get-Delay -Record $record -Attempt 2 | Should-Be 4 + } + It 'gives nothing for a failure that carries no status at all' { $record = [System.Management.Automation.ErrorRecord]::new( [System.InvalidOperationException]::new('no connection'), 'NoStatus', 'ConnectionError', $null) diff --git a/Tests/Unit/Private/Get-IslRegexLiteralPrefix.Tests.ps1 b/Tests/Unit/Private/Get-IslRegexLiteralPrefix.Tests.ps1 index a80d8b0..b8fb236 100644 --- a/Tests/Unit/Private/Get-IslRegexLiteralPrefix.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslRegexLiteralPrefix.Tests.ps1 @@ -23,6 +23,11 @@ Describe 'Get-IslRegexLiteralPrefix' -Tag 'Unit', 'Private' { @{ Pattern = 'ab{2}'; Expected = 'a' } @{ Pattern = '(start)'; Expected = '' } @{ Pattern = 'ends with a backslash\'; Expected = 'ends with a backslash' } + @{ Pattern = 'Script failed|Script timed out'; Expected = '' } + @{ Pattern = '^abc|def'; Expected = '' } + @{ Pattern = 'abc(def|ghi)'; Expected = 'abc' } + @{ Pattern = 'abc[|]def'; Expected = 'abc' } + @{ Pattern = 'abc\|def'; Expected = 'abc|def' } ) { $parameters = @{ Pattern = $Pattern } $prefix = InModuleScope IntuneScriptLab -Parameters $parameters { @@ -41,4 +46,14 @@ Describe 'Get-IslRegexLiteralPrefix' -Tag 'Unit', 'Private' { 'Powershell exit code is -1' -match $pattern | Should-BeTrue 'Powershell exit code is -1'.Contains($prefix) | Should-BeTrue } + + It 'gives no text that a match of the second alternative lacks' { + $pattern = 'Script failed|Script timed out' + $prefix = InModuleScope IntuneScriptLab -Parameters @{ Pattern = $pattern } { + Get-IslRegexLiteralPrefix -Pattern $Pattern + } + + 'Script timed out' -match $pattern | Should-BeTrue + 'Script timed out'.Contains($prefix) | Should-BeTrue + } } diff --git a/Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 b/Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 index e9a5e49..dbfe908 100644 --- a/Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 @@ -23,6 +23,7 @@ BeforeAll { $null = New-ItemProperty -Path $script:Key -Name 'Name' -Value 'Widget' $null = New-ItemProperty -Path $script:Key -Name 'Blob' -PropertyType Binary -Value ([byte[]](1, 2, 3)) $null = New-ItemProperty -Path $script:Key -Name 'Long' -Value ('x' * 450) + $null = New-ItemProperty -Path $script:Key -Name 'PSVersion' -Value '5.1' $null = New-Item -Path "$($script:Key)\Child" $null = New-ItemProperty -Path "$($script:Key)\Child" -Name 'Inner' -Value 1 $null = New-Item -Path "$($script:Key)\Child\Grandchild" @@ -35,7 +36,15 @@ Describe 'Get-IslRegistryText' -Tag 'Unit', 'Private' { $lines[0] | Should-BeLikeString '`[*\Policies`]' $lines | Should-ContainCollection ' Name = Widget' - @($lines | Where-Object { $_ -like ' PS*' }) | Should-BeCollection @() + $providerPattern = '^ PS(Path|ParentPath|ChildName|Drive|Provider) = ' + $providerLines = @($lines | Where-Object { $_ -match $providerPattern }) + $providerLines | Should-BeCollection @() + } + + It 'keeps a value of the key whose name starts with PS' { + $lines = Get-Text -Key $script:Key -Depth 0 + + $lines | Should-ContainCollection ' PSVersion = 5.1' @($lines | Where-Object { $_ -like '`[*\Child`]' }) | Should-BeCollection -Count 1 $lines | Should-ContainCollection ' Inner = 1' } @@ -49,11 +58,14 @@ Describe 'Get-IslRegistryText' -Tag 'Unit', 'Private' { $long[0] | Should-Be (' Long = ' + ('x' * 400) + '...') } - It 'goes down as many levels as asked' { + It 'gives Depth + 1 levels of subkeys below the key' { $shallow = Get-Text -Key $script:Key -Depth 0 $deep = Get-Text -Key $script:Key -Depth 1 - @($shallow | Where-Object { $_ -like '`[*' }).Count | Should-Be 2 + # Depth 0: the key and its subkeys, without the grandchild + $shallowKeys = @($shallow | Where-Object { $_ -like '`[*' }) + $shallowKeys | Should-BeCollection -Count 2 + @($shallowKeys | Where-Object { $_ -like '`[*Grandchild`]' }) | Should-BeCollection @() @($deep | Where-Object { $_ -like '`[*Grandchild`]' }) | Should-BeCollection -Count 1 } diff --git a/Tests/Unit/Public/Export-IntuneAgentDiagnostic.Tests.ps1 b/Tests/Unit/Public/Export-IntuneAgentDiagnostic.Tests.ps1 index ea50f65..838c628 100644 --- a/Tests/Unit/Public/Export-IntuneAgentDiagnostic.Tests.ps1 +++ b/Tests/Unit/Public/Export-IntuneAgentDiagnostic.Tests.ps1 @@ -171,6 +171,59 @@ Describe 'Export-IntuneAgentDiagnostic' -Tag 'Unit', 'Public' { Get-ZipEntry -Zip $zip | Should-ContainCollection 'Timeline/events.csv' } + It 'reports a log that cannot be copied, names it in the manifest and writes the rest' { + $partly = Join-Path $TestDrive 'PartlyLocked' + Copy-Item -LiteralPath $script:Logs -Destination $partly -Recurse + $lockedLog = Join-Path $partly 'Locked.log' + [System.IO.File]::WriteAllText($lockedLog, ('x' * 100)) + $zip = Join-Path $TestDrive 'partly.zip' + # A byte range that another stream has locked cannot be read, though the file opens + $holder = [System.IO.File]::Open($lockedLog, 'Open', 'ReadWrite', 'ReadWrite, Delete') + try { + $holder.Lock(0, 100) + $exportSplat = @{ + Path = $zip; LogPath = $partly; SkipRegistry = $true; SkipTimeline = $true + ErrorAction = 'Continue' + } + $output = Export-IntuneAgentDiagnostic @exportSplat 2>&1 + } finally { + $holder.Dispose() + } + $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) + $result = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }) + + $errors | Should-BeCollection -Count 1 + "$($errors[0])" | Should-BeLikeString '*lock*' + $result | Should-BeCollection -Count 1 + $result[0].Logs | Should-Be 2 + $entries = Get-ZipEntry -Zip $zip + $entries | Should-NotContainCollection 'Logs/Locked.log' + $entries | Should-ContainCollection 'Logs/HealthScripts.log' + $manifest = Read-ZipEntry -Zip $zip -Name 'Manifest.txt' + $manifest | Should-BeLikeString '*Logs: 2 file(s)*Logs not copied: Locked.log*' + } + + It 'ends with no package under -ErrorAction Stop when a log cannot be copied' { + $partly = Join-Path $TestDrive 'PartlyLockedStop' + Copy-Item -LiteralPath $script:Logs -Destination $partly -Recurse + $lockedLog = Join-Path $partly 'Locked.log' + [System.IO.File]::WriteAllText($lockedLog, ('x' * 100)) + $zip = Join-Path $TestDrive 'partly-stop.zip' + $holder = [System.IO.File]::Open($lockedLog, 'Open', 'ReadWrite', 'ReadWrite, Delete') + try { + $holder.Lock(0, 100) + $exportSplat = @{ + Path = $zip; LogPath = $partly; SkipRegistry = $true; SkipTimeline = $true + ErrorAction = 'Stop' + } + { Export-IntuneAgentDiagnostic @exportSplat } | Should-Throw -ExceptionMessage '*lock*' + } finally { + $holder.Dispose() + } + + Test-Path -LiteralPath $zip | Should-BeFalse + } + 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') diff --git a/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md b/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md index 49c6977..9223649 100644 --- a/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md +++ b/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md @@ -33,7 +33,8 @@ writes it as one zip file: - Logs\: every log in the agent's folder (IntuneManagementExtension, AppWorkload, HealthScripts, AgentExecutor and the rest, rolled files included), copied with shared - access so the live agent is no obstacle; + access so the live agent is no obstacle, and can still write, rename or rotate a log while it + is copied; - Registry\: the agent's own state under HKLM\SOFTWARE\Microsoft\IntuneManagementExtension (policies, Win32 app states, script reports), the enrollment's FirstSync values, the Enrollment Status Page tracking and the Autopilot diagnostics, as text (skip with @@ -249,6 +250,10 @@ those sections are present) and SizeBytes. Author: Jeffrey Stuhr. The registry is read with the caller's rights; a key that cannot be read is left out of the zip rather than failing the export. dsregcmd /status runs when dsregcmd.exe is on the path. +A log that cannot be copied, such as one that rotated away after the folder was listed, is +reported as a non-terminating error and named on a "Logs not copied" line of Manifest.txt, +and the rest of the package is still written; with -ErrorAction Stop the export ends there +and writes no package. ## RELATED LINKS diff --git a/en-US/IntuneScriptLab-Help.xml b/en-US/IntuneScriptLab-Help.xml index 09a80e5..63c6b13 100644 --- a/en-US/IntuneScriptLab-Help.xml +++ b/en-US/IntuneScriptLab-Help.xml @@ -1370,7 +1370,8 @@ writes it as one zip file: - Logs\: every log in the agent's folder (IntuneManagementExtension, AppWorkload, HealthScripts, AgentExecutor and the rest, rolled files included), copied with shared - access so the live agent is no obstacle; + access so the live agent is no obstacle, and can still write, rename or rotate a log while it + is copied; - Registry\: the agent's own state under HKLM\SOFTWARE\Microsoft\IntuneManagementExtension (policies, Win32 app states, script reports), the enrollment's FirstSync values, the Enrollment Status Page tracking and the Autopilot diagnostics, as text (skip with @@ -1536,7 +1537,11 @@ those sections are present) and SizeBytes. Author: Jeffrey Stuhr. The registry is read with the caller's rights; a key that cannot be read is left out of the -zip rather than failing the export. dsregcmd /status runs when dsregcmd.exe is on the path. +zip rather than failing the export. dsregcmd /status runs when dsregcmd.exe is on the path. +A log that cannot be copied, such as one that rotated away after the folder was listed, is +reported as a non-terminating error and named on a "Logs not copied" line of Manifest.txt, +and the rest of the package is still written; with -ErrorAction Stop the export ends there +and writes no package.