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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
14 changes: 10 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 <name>).description` from inside the module.

### Never `Publish-PSResource -Path .`

This repository *is* the module root, so packaging it directly ships the whole working tree,
Expand Down
77 changes: 77 additions & 0 deletions Private/Compress-IslFolder.ps1
Original file line number Diff line number Diff line change
@@ -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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Pre-existing (not from this change, not blocking): when CreateEntryFromFile fails part-way (a file locked or removed in the staging folder, a full disk), the finally disposes the archive and leaves a valid but incomplete zip at Destination. Export-IntuneAgentDiagnostic has already removed the previous package under -Force and then ends with an error, so the path holds a zip that opens and looks like a package. Fix: in the catch, remove Destination when this function created it (dispose first), and say in the help that a failure leaves no archive.

🤖 Generated with Claude Code

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Fixed in 65ba5c3. When filling the archive fails, the catch disposes the archive and deletes the file this call created. A failure at ZipFile.Open, such as an archive that is there already, leaves that file alone, as the existing test checks. If removing the part archive fails as well, a warning names it, and the compression's own error is the one the function ends with. The help says so. The new test holds one staged file open for writing, so it cannot be added, and checks that no zip is left.

🤖 Generated with Claude Code

$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
}
103 changes: 103 additions & 0 deletions Private/ConvertTo-IslNamedGroupPattern.ps1
Original file line number Diff line number Diff line change
@@ -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
(?<name>...), 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<n> outside a character class, whose n is one of the
pattern's own groups, is therefore written as \k<prefix n>. 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 (?<e3g1>-?\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 '?')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Pre-existing (not from this change, not blocking): after renaming, a numbered backreference in a pattern (\1, \k<1>) no longer points at that pattern's own group. In the combined alternation every group is named, and .NET numbers named groups after all others in the whole expression, so \1 in the fifth pattern refers to the first named group of the combined regex. No pattern in the table uses a backreference today, and the help does not say this. Fix: rewrite \<n> to \k<prefix<n>> while renaming, or state in the help that patterns must not use numbered backreferences.

🤖 Generated with Claude Code

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Fixed in 65ba5c3. A \n or \k<n> outside a character class, whose n is one of the pattern's own groups, becomes \k<prefix n>. The text is kept in pieces until the number of groups is known, so a reference that comes before its group works as well. A larger number, \0, an escaped backslash and a reference inside a class are left as they are. The help names a numbered conditional such as (?(1)...) as not rewritten. A new test joins two converted patterns the way the reader does and checks that \1 in the second one matches its own capture.

🤖 Generated with Claude Code

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 }
}
68 changes: 68 additions & 0 deletions Private/Copy-IslSharedFile.ps1
Original file line number Diff line number Diff line change
@@ -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() }
}
}
66 changes: 5 additions & 61 deletions Private/Get-IslAgentLogEvent.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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 <prefix><n>, 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
Expand All @@ -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++
Expand Down
Loading