diff --git a/CHANGELOG.md b/CHANGELOG.md index 131a25d..0895c83 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: a settings value that is not allowed still ends `Test-IntuneScript` with `SettingsInvalid,Test-IntuneScript`. - The README's section headings no longer carry the version that introduced each feature, the @@ -151,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/CLAUDE.md b/CLAUDE.md index 9c51f58..9db53f8 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 @@ -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, diff --git a/Private/Compress-IslFolder.ps1 b/Private/Compress-IslFolder.ps1 new file mode 100644 index 0000000..bb156f5 --- /dev/null +++ b/Private/Compress-IslFolder.ps1 @@ -0,0 +1,77 @@ +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. 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. 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. + + .PARAMETER Destination + The full path of the zip archive to create. + + .EXAMPLE + $entryCount = Compress-IslFolder -Folder $staging -Destination $zip + + 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()] + [OutputType([int])] + param( + [Parameter(Mandatory)] + [string]$Folder, + + [Parameter(Mandatory)] + [string]$Destination + ) + + $archive = $null + $count = 0 + try { + 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 { + $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() } + } + $count +} diff --git a/Private/ConvertTo-IslNamedGroupPattern.ps1 b/Private/ConvertTo-IslNamedGroupPattern.ps1 new file mode 100644 index 0000000..d35160d --- /dev/null +++ b/Private/ConvertTo-IslNamedGroupPattern.ps1 @@ -0,0 +1,103 @@ +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. + + 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. + + .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 + ) + + # 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) { + $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 = $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 = $text.Append("(?<$Prefix$count>") + continue + } + $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 new file mode 100644 index 0000000..831c766 --- /dev/null +++ b/Private/Copy-IslSharedFile.ps1 @@ -0,0 +1,68 @@ +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 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; 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. + + .PARAMETER Destination + The full path of the copy. Its folder must exist. + + .EXAMPLE + Copy-IslSharedFile -Source $log.FullName -Destination $copy + + Copies a log of the agent that the agent is still writing. + + .INPUTS + None. + + .OUTPUTS + None. + #> + [CmdletBinding()] + [OutputType([void])] + param( + [Parameter(Mandatory)] + [string]$Source, + + [Parameter(Mandatory)] + [string]$Destination + ) + + $in = $null + $out = $null + try { + $in = [System.IO.File]::Open($Source, 'Open', 'Read', 'ReadWrite, Delete') + $out = [System.IO.File]::Create($Destination) + $in.CopyTo($out) + } catch { + $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-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..ad384b5 --- /dev/null +++ b/Private/Get-IslGraphRetryDelay.ps1 @@ -0,0 +1,78 @@ +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. 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. + + .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 + $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 } + } + if ($status -notin 429, 503, 504) { return } + + $delay = 0 + # 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) { + $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) } + [int][Math]::Min($delay, 60) +} diff --git a/Private/Get-IslRegexLiteralPrefix.ps1 b/Private/Get-IslRegexLiteralPrefix.ps1 new file mode 100644 index 0000000..687b792 --- /dev/null +++ b/Private/Get-IslRegexLiteralPrefix.ps1 @@ -0,0 +1,77 @@ +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. 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. + + .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 or has alternatives at its top level. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [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) { + $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..3729328 --- /dev/null +++ b/Private/Get-IslRegistryText.ps1 @@ -0,0 +1,68 @@ +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 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". + + .PARAMETER Key + The path of the key in a PowerShell registry drive, such as + HKLM:\SOFTWARE\Microsoft\IntuneManagementExtension. + + .PARAMETER Depth + 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, three levels of subkeys 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 -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 -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/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..2f78b8d --- /dev/null +++ b/Private/Write-IslTextFile.ps1 @@ -0,0 +1,60 @@ +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. 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. + + .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 + + Writes the device facts into the staging folder of a package. + + .INPUTS + None. + + .OUTPUTS + None. + #> + [CmdletBinding()] + [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 + # Assigned, not taken from an if expression, which would unroll an empty array to nothing + [string[]]$text = @() + if ($null -ne $Line) { $text = $Line } + 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 c8143fd..569f7a8 100644 --- a/Public/Export-IntuneAgentDiagnostic.ps1 +++ b/Public/Export-IntuneAgentDiagnostic.ps1 @@ -42,80 +42,34 @@ 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 # 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 - Copy-SharedFile -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") @@ -139,10 +93,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 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 $manifest.Add('Device: system.txt, dsregcmd.txt') } else { $manifest.Add('Device: system.txt (dsregcmd not available)') } @@ -159,8 +114,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 } $manifest.Add("Registry: $(($keys | ForEach-Object { $_.Name }) -join ', ')") } @@ -188,14 +144,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 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 } catch { # Whatever failed, the package is not complete: the command ends without a result @@ -210,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 new file mode 100644 index 0000000..f646a36 --- /dev/null +++ b/Tests/Unit/Private/Compress-IslFolder.Tests.ps1 @@ -0,0 +1,84 @@ +#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 + } + + $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 the archive when -WhatIf reached it through the preference, as the command has asked' { + $zip = Join-Path $TestDrive 'preview.zip' + $count = InModuleScope IntuneScriptLab -Parameters @{ Folder = $script:Folder; Zip = $zip } { + $WhatIfPreference = $true + Compress-IslFolder -Folder $Folder -Destination $Zip + } + + $count | Should-Be 3 + 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') + + { + 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/ConvertTo-IslNamedGroupPattern.Tests.ps1 b/Tests/Unit/Private/ConvertTo-IslNamedGroupPattern.Tests.ps1 new file mode 100644 index 0000000..8887aeb --- /dev/null +++ b/Tests/Unit/Private/ConvertTo-IslNamedGroupPattern.Tests.ps1 @@ -0,0 +1,73 @@ +#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 } + @{ 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 + + $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 + } + + 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 new file mode 100644 index 0000000..2e749d1 --- /dev/null +++ b/Tests/Unit/Private/Copy-IslSharedFile.Tests.ps1 @@ -0,0 +1,115 @@ +#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 + } + } +} + +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 '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' + [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' + + $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-IslGraphRetryDelay.Tests.ps1 b/Tests/Unit/Private/Get-IslGraphRetryDelay.Tests.ps1 new file mode 100644 index 0000000..6d0796f --- /dev/null +++ b/Tests/Unit/Private/Get-IslGraphRetryDelay.Tests.ps1 @@ -0,0 +1,98 @@ +#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 '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) + + @(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..b8fb236 --- /dev/null +++ b/Tests/Unit/Private/Get-IslRegexLiteralPrefix.Tests.ps1 @@ -0,0 +1,59 @@ +#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' } + @{ 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 { + 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 + } + + 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 new file mode 100644 index 0000000..dbfe908 --- /dev/null +++ b/Tests/Unit/Private/Get-IslRegistryText.Tests.ps1 @@ -0,0 +1,106 @@ +#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-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" +} + +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' + $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' + } + + 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 '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 + + # 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 + } + + 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/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..70a60fe --- /dev/null +++ b/Tests/Unit/Private/Write-IslTextFile.Tests.ps1 @@ -0,0 +1,71 @@ +#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 + } + } +} + +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 the file when -WhatIf reached it through the preference, as the command has asked' { + InModuleScope IntuneScriptLab -Parameters @{ Root = $script:Root } { + $WhatIfPreference = $true + Write-IslTextFile -Root $Root -RelativePath 'Preview\x.txt' -Line 'x' + } + + [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*' + } +} 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.