From c0b67878fb6a553e9d00661ba0b37969e1830680 Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:13:22 -0800 Subject: [PATCH 1/3] refactor(helpers): move four nested helpers into their own files The first part of #65. Four functions were nested inside the one function that used them, with no [CmdletBinding()], no help, untyped parameters and no output type (FUN-01, DOC-01, FUN-20, FUN-10, MOD-01). Each is now a private function in its own file, an advanced function with full help, and takes as parameters what it read from the function around it: - Test-RuleSelected in Test-IntuneScript -> Test-IslRuleSelected - Get-Check in Test-IntuneWin32Requirement -> New-IslRequirementCheck - Get-ArtifactLocation in Export-IntuneFindingSarif -> ConvertTo-IslSarifLocation, with the root as -RootPath - ConvertTo-SettingsObject in Get-IslSetting -> ConvertTo-IslSettingsObject, with the lists of allowed values ConvertTo-IslSettingsObject ends with ThrowTerminatingError where the nested copy had to throw, so one of the last two throw statements of the module is gone. Each new function has a test file of its own; the tests of the four commands are unchanged. Refs #65. --- CHANGELOG.md | 5 + CLAUDE.md | 8 +- Private/ConvertTo-IslSarifLocation.ps1 | 48 ++++++++ Private/ConvertTo-IslSettingsObject.ps1 | 106 ++++++++++++++++++ Private/Get-IslSetting.ps1 | 73 +----------- Private/New-IslRequirementCheck.ps1 | 79 +++++++++++++ Private/Test-IslRuleSelected.ps1 | 58 ++++++++++ Public/Export-IntuneFindingSarif.ps1 | 13 +-- Public/Test-IntuneScript.ps1 | 10 +- Public/Test-IntuneWin32Requirement.ps1 | 25 +---- .../ConvertTo-IslSarifLocation.Tests.ps1 | 59 ++++++++++ .../ConvertTo-IslSettingsObject.Tests.ps1 | 104 +++++++++++++++++ .../Private/New-IslRequirementCheck.Tests.ps1 | 64 +++++++++++ .../Private/Test-IslRuleSelected.Tests.ps1 | 54 +++++++++ 14 files changed, 594 insertions(+), 112 deletions(-) create mode 100644 Private/ConvertTo-IslSarifLocation.ps1 create mode 100644 Private/ConvertTo-IslSettingsObject.ps1 create mode 100644 Private/New-IslRequirementCheck.ps1 create mode 100644 Private/Test-IslRuleSelected.ps1 create mode 100644 Tests/Unit/Private/ConvertTo-IslSarifLocation.Tests.ps1 create mode 100644 Tests/Unit/Private/ConvertTo-IslSettingsObject.Tests.ps1 create mode 100644 Tests/Unit/Private/New-IslRequirementCheck.Tests.ps1 create mode 100644 Tests/Unit/Private/Test-IslRuleSelected.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 94b4e32..91a5281 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,11 @@ 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 + advanced function with help and tests (#65). Nothing changes for a caller, except that the error + of a settings value that is not allowed now names `ConvertTo-IslSettingsObject` after + `SettingsInvalid` in its `FullyQualifiedErrorId`. - The README's section headings no longer carry the version that introduced each feature, the tenant pre-flight paragraph no longer says since when each check exists, and the roadmap points at this changelog instead of listing versions; a first-time reader wants the overview, and the diff --git a/CLAUDE.md b/CLAUDE.md index af366ed..9c51f58 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 two `throw` statements that are left are in nested -functions without `[CmdletBinding()]`, which have no `$PSCmdlet` of their own: one passes on the -error it caught, the other throws a record from `New-IslErrorRecord`, and the function that holds -each of them ends with it. +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. `Tests/Unit/Module.ErrorFlow.Tests.ps1` holds the rule on the syntax trees, because behaviour does not show it: a caller that goes on with nothing often returns nothing too, and `Should-Throw` calls diff --git a/Private/ConvertTo-IslSarifLocation.ps1 b/Private/ConvertTo-IslSarifLocation.ps1 new file mode 100644 index 0000000..7eaf328 --- /dev/null +++ b/Private/ConvertTo-IslSarifLocation.ps1 @@ -0,0 +1,48 @@ +function ConvertTo-IslSarifLocation { + <# + .SYNOPSIS + Converts a script path to the artifactLocation of a SARIF result. + + .DESCRIPTION + A path below the root becomes a relative URI with the base %SRCROOT%, so that a code + scanning service shows the finding against the file in the repository. Each segment is + escaped as a URI segment, and the separators become forward slashes. A path outside the root + becomes an absolute file URI with no base. The comparison of the path with the root ignores + letter case, as Windows paths do. + + .PARAMETER FilePath + The full path of the script that a finding is about. + + .PARAMETER RootPath + The full path of the folder the relative URIs start from, without a trailing separator. + + .EXAMPLE + ConvertTo-IslSarifLocation -FilePath 'C:\repo\Remediations\A\Detect.ps1' -RootPath 'C:\repo' + + Returns @{ uri = 'Remediations/A/Detect.ps1'; uriBaseId = '%SRCROOT%' }. + + .INPUTS + None. + + .OUTPUTS + System.Collections.Specialized.OrderedDictionary. The uri, and uriBaseId for a path below + the root. + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [string]$FilePath, + + [Parameter(Mandatory)] + [string]$RootPath + ) + + if ($FilePath.StartsWith($RootPath, [System.StringComparison]::OrdinalIgnoreCase)) { + $relative = $FilePath.Substring($RootPath.Length).TrimStart('\', '/') + $segments = foreach ($segment in $relative -split '[\\/]') { [System.Uri]::EscapeDataString($segment) } + return [ordered]@{ uri = ($segments -join '/'); uriBaseId = '%SRCROOT%' } + } + # Outside the root: an absolute file URI, with no base to resolve against + [ordered]@{ uri = ([System.Uri]::new($FilePath)).AbsoluteUri } +} diff --git a/Private/ConvertTo-IslSettingsObject.ps1 b/Private/ConvertTo-IslSettingsObject.ps1 new file mode 100644 index 0000000..6872448 --- /dev/null +++ b/Private/ConvertTo-IslSettingsObject.ps1 @@ -0,0 +1,106 @@ +function ConvertTo-IslSettingsObject { + <# + .SYNOPSIS + Validates a settings table and converts it to the settings object the analysis reads. + + .DESCRIPTION + The table is the content of an IntuneScriptLab.settings.psd1 file or a hashtable passed as + -Settings. Every key is optional. A key the module does not know is named in a warning and + otherwise ignored. A value outside its set ends the function with the error SettingsInvalid, + which names the source and the first value that is wrong, checked in this order: + MinimumSeverity, ScriptType, Context, Architecture, then the entries of Severity. + + .PARAMETER Table + The settings, in the shape of a settings file. + + .PARAMETER Source + Where the table came from, for the messages: the path of the file, '-Settings', or an empty + string for the empty settings that apply when no file is found. + + .EXAMPLE + $table = @{ MinimumSeverity = 'Warning'; ExcludeRule = 'IslLongSleep' } + ConvertTo-IslSettingsObject -Table $table -Source '-Settings' + + A settings object whose MinimumSeverity is Warning and whose ExcludeRule holds IslLongSleep. + + .INPUTS + None. + + .OUTPUTS + IntuneScriptLab.Settings. Source, ExcludeRule, IncludeRule, MinimumSeverity, Severity, + ScriptType, Context, Architecture and EnforceSignatureCheck. + #> + [CmdletBinding()] + [OutputType('IntuneScriptLab.Settings')] + param( + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [hashtable]$Table, + + [Parameter(Mandatory)] + [AllowEmptyString()] + [string]$Source + ) + + $validTypes = 'Detection', 'Remediation', 'PlatformScript', 'Win32Detection', 'Win32Requirement' + $validSeverities = 'Information', 'Warning', 'Error' + $knownKeys = 'ExcludeRule', 'IncludeRule', 'MinimumSeverity', 'Severity', 'ScriptType', 'Context', + 'Architecture', 'EnforceSignatureCheck' + + $unknown = @($Table.Keys | Where-Object { $_ -notin $knownKeys }) + if ($unknown) { + Write-Warning "Unknown settings key(s) in ${Source}: $($unknown -join ', ')" + } + # Every key is optional. An index reads a key that is not there as $null, where member + # access is an error under strict mode + $minimumSeverity = $Table['MinimumSeverity'] + $scriptType = $Table['ScriptType'] + $context = $Table['Context'] + $architecture = $Table['Architecture'] + $severityTable = $Table['Severity'] + # The first value that is wrong is the one reported + $problem = $null + if ($minimumSeverity -and "$minimumSeverity" -notin $validSeverities) { + $problem = "MinimumSeverity must be one of $($validSeverities -join ', ')" + } elseif ($scriptType -and "$scriptType" -notin $validTypes) { + $problem = "ScriptType must be one of $($validTypes -join ', ')" + } elseif ($context -and "$context" -notin 'System', 'User') { + $problem = 'Context must be System or User' + } elseif ($architecture -and "$architecture" -notin 'x86', 'x64', 'arm64') { + $problem = 'Architecture must be x86, x64 or arm64' + } + $severity = @{} + $severityKeys = if ($severityTable) { @($severityTable.Keys | Where-Object { $null -ne $_ }) } else { @() } + foreach ($key in $severityKeys) { + if ($null -eq $problem -and "$($severityTable[$key])" -notin $validSeverities) { + $problem = "Severity for $key must be one of $($validSeverities -join ', ')" + } + $severity[$key] = "$($severityTable[$key])" + } + if ($null -ne $problem) { + $recordSplat = @{ + Message = "${Source}: $problem" + ErrorId = 'SettingsInvalid' + Category = [System.Management.Automation.ErrorCategory]::InvalidData + TargetObject = $Source + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) + } + + $signatureCheck = $null + if ($Table.ContainsKey('EnforceSignatureCheck')) { + $signatureCheck = [bool]$Table['EnforceSignatureCheck'] + } + [pscustomobject]@{ + PSTypeName = 'IntuneScriptLab.Settings' + Source = $Source + ExcludeRule = @($Table['ExcludeRule'] | Where-Object { $_ }) + IncludeRule = @($Table['IncludeRule'] | Where-Object { $_ }) + MinimumSeverity = if ($minimumSeverity) { "$minimumSeverity" } else { $null } + Severity = $severity + ScriptType = if ($scriptType) { "$scriptType" } else { $null } + Context = if ($context) { "$context" } else { $null } + Architecture = if ($architecture) { "$architecture" } else { $null } + EnforceSignatureCheck = $signatureCheck + } +} diff --git a/Private/Get-IslSetting.ps1 b/Private/Get-IslSetting.ps1 index c49d80d..265e03e 100644 --- a/Private/Get-IslSetting.ps1 +++ b/Private/Get-IslSetting.ps1 @@ -47,80 +47,15 @@ function Get-IslSetting { [hashtable]$Cache = @{} ) - $validTypes = 'Detection', 'Remediation', 'PlatformScript', 'Win32Detection', 'Win32Requirement' - $validSeverities = 'Information', 'Warning', 'Error' - $knownKeys = 'ExcludeRule', 'IncludeRule', 'MinimumSeverity', 'Severity', 'ScriptType', 'Context', - 'Architecture', 'EnforceSignatureCheck' - - function ConvertTo-SettingsObject { - param([hashtable]$Table, [string]$Source) - $unknown = @($Table.Keys | Where-Object { $_ -notin $knownKeys }) - if ($unknown) { - Write-Warning "Unknown settings key(s) in ${Source}: $($unknown -join ', ')" - } - # Every key is optional. An index reads a key that is not there as $null, where member - # access is an error under strict mode - $minimumSeverity = $Table['MinimumSeverity'] - $scriptType = $Table['ScriptType'] - $context = $Table['Context'] - $architecture = $Table['Architecture'] - $severityTable = $Table['Severity'] - # The first value that is wrong is the one reported - $problem = $null - if ($minimumSeverity -and "$minimumSeverity" -notin $validSeverities) { - $problem = "MinimumSeverity must be one of $($validSeverities -join ', ')" - } elseif ($scriptType -and "$scriptType" -notin $validTypes) { - $problem = "ScriptType must be one of $($validTypes -join ', ')" - } elseif ($context -and "$context" -notin 'System', 'User') { - $problem = 'Context must be System or User' - } elseif ($architecture -and "$architecture" -notin 'x86', 'x64', 'arm64') { - $problem = 'Architecture must be x86, x64 or arm64' - } - $severity = @{} - $severityKeys = if ($severityTable) { @($severityTable.Keys | Where-Object { $null -ne $_ }) } else { @() } - foreach ($key in $severityKeys) { - if ($null -eq $problem -and "$($severityTable[$key])" -notin $validSeverities) { - $problem = "Severity for $key must be one of $($validSeverities -join ', ')" - } - $severity[$key] = "$($severityTable[$key])" - } - if ($null -ne $problem) { - # This nested function has no $PSCmdlet of its own. The record is thrown, and the - # function that holds this one ends with it - $recordSplat = @{ - Message = "${Source}: $problem" - ErrorId = 'SettingsInvalid' - Category = [System.Management.Automation.ErrorCategory]::InvalidData - TargetObject = $Source - } - throw (New-IslErrorRecord @recordSplat) - } - [pscustomobject]@{ - PSTypeName = 'IntuneScriptLab.Settings' - Source = $Source - ExcludeRule = @($Table['ExcludeRule'] | Where-Object { $_ }) - IncludeRule = @($Table['IncludeRule'] | Where-Object { $_ }) - MinimumSeverity = if ($minimumSeverity) { "$minimumSeverity" } else { $null } - Severity = $severity - ScriptType = if ($scriptType) { "$scriptType" } else { $null } - Context = if ($context) { "$context" } else { $null } - Architecture = if ($architecture) { "$architecture" } else { $null } - EnforceSignatureCheck = if ($Table.ContainsKey('EnforceSignatureCheck')) { - [bool]$Table['EnforceSignatureCheck'] - } - else { $null } - } - } - # A settings file that cannot be read, and a value in it that is wrong, end the function $found = $null try { if ($Settings -is [hashtable]) { - $found = ConvertTo-SettingsObject -Table $Settings -Source '-Settings' + $found = ConvertTo-IslSettingsObject -Table $Settings -Source '-Settings' } elseif ($null -ne $Settings) { $file = (Resolve-Path -LiteralPath "$Settings" -ErrorAction Stop).ProviderPath $fileTable = Import-PowerShellDataFile -LiteralPath $file -ErrorAction Stop - $found = ConvertTo-SettingsObject -Table $fileTable -Source $file + $found = ConvertTo-IslSettingsObject -Table $fileTable -Source $file } else { $resolved = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath $folder = if (Test-Path -LiteralPath $resolved -PathType Container) { $resolved } @@ -133,12 +68,12 @@ function Get-IslSetting { $candidate = Join-Path -Path $probe -ChildPath 'IntuneScriptLab.settings.psd1' if (Test-Path -LiteralPath $candidate -PathType Leaf) { $candidateTable = Import-PowerShellDataFile -LiteralPath $candidate -ErrorAction Stop - $found = ConvertTo-SettingsObject -Table $candidateTable -Source $candidate + $found = ConvertTo-IslSettingsObject -Table $candidateTable -Source $candidate break } $probe = Split-Path -Path $probe -Parent } - if (-not $found) { $found = ConvertTo-SettingsObject -Table @{} -Source '' } + if (-not $found) { $found = ConvertTo-IslSettingsObject -Table @{} -Source '' } $Cache[$folder] = $found } } diff --git a/Private/New-IslRequirementCheck.ps1 b/Private/New-IslRequirementCheck.ps1 new file mode 100644 index 0000000..5f4c2a3 --- /dev/null +++ b/Private/New-IslRequirementCheck.ps1 @@ -0,0 +1,79 @@ +function New-IslRequirementCheck { + <# + .SYNOPSIS + Builds the result of one requirement that Test-IntuneWin32Requirement checks. + + .DESCRIPTION + One requirement of a Win32 app, such as the architecture or the free disk space, compared + with this device. A check that is met carries no details and no applicability code; one that + is not met carries the text and the code the agent was observed to report for it. + + .PARAMETER Requirement + The name of the requirement, such as Architecture or MinimumFreeDiskSpaceMB. + + .PARAMETER Met + Whether the device meets the requirement. + + .PARAMETER Actual + What the device has, such as its architecture or its free space. + + .PARAMETER Expected + What the requirement asks for. + + .PARAMETER Details + The agent's text for a requirement that is not met. + + .PARAMETER Code + The applicability code the agent reports for a requirement that is not met, such as 1000. + Left out where no code was observed. + + .EXAMPLE + $checkSplat = @{ Requirement = 'Architecture'; Met = $false; Actual = 'arm64'; Expected = 'x64' } + New-IslRequirementCheck @checkSplat -Code 1000 -Details 'Device architecture is not applicable.' + + A check that the device does not meet, with the agent's code and text. + + .INPUTS + None. + + .OUTPUTS + IntuneScriptLab.RequirementCheck. Requirement, Met, Actual, Expected, Details and + Applicability. + #> + [CmdletBinding()] + [OutputType('IntuneScriptLab.RequirementCheck')] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', + Justification = 'Builds an object and changes nothing.')] + param( + [Parameter(Mandatory)] + [string]$Requirement, + + [Parameter()] + [switch]$Met, + + [Parameter()] + [AllowNull()] + [object]$Actual, + + [Parameter()] + [AllowNull()] + [object]$Expected, + + [Parameter()] + [string]$Details = '', + + [Parameter()] + [AllowNull()] + [object]$Code + ) + + [pscustomobject]@{ + PSTypeName = 'IntuneScriptLab.RequirementCheck' + Requirement = $Requirement + Met = [bool]$Met + Actual = $Actual + Expected = $Expected + Details = if ($Met) { '' } else { $Details } + Applicability = if ($Met) { $null } else { $Code } + } +} diff --git a/Private/Test-IslRuleSelected.ps1 b/Private/Test-IslRuleSelected.ps1 new file mode 100644 index 0000000..f2da114 --- /dev/null +++ b/Private/Test-IslRuleSelected.ps1 @@ -0,0 +1,58 @@ +function Test-IslRuleSelected { + <# + .SYNOPSIS + Tells whether a rule name passes an include list and an exclude list of wildcard patterns. + + .DESCRIPTION + The rule filter of Test-IntuneScript, for -IncludeRule, -ExcludeRule and the same keys of a + settings file. A rule is selected when the include list is empty or one of its patterns + matches the name, and no pattern of the exclude list matches it. The patterns are those of + the -like operator, so the comparison ignores letter case. + + .PARAMETER RuleName + The name of the rule without its Find- prefix, such as IslExitCodeIssue. + + .PARAMETER Include + Patterns of the rules to run. Empty or left out, every rule is included. + + .PARAMETER Exclude + Patterns of the rules to skip. An exclusion wins over an inclusion. + + .EXAMPLE + Test-IslRuleSelected -RuleName 'IslLongSleep' -Include 'IslLong*' -Exclude 'IslLongSleep' + + Returns $false: the rule is included by its pattern and then excluded by name. + + .INPUTS + None. + + .OUTPUTS + System.Boolean. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [string]$RuleName, + + [Parameter()] + [AllowEmptyCollection()] + [AllowNull()] + [string[]]$Include, + + [Parameter()] + [AllowEmptyCollection()] + [AllowNull()] + [string[]]$Exclude + ) + + $included = @($Include | Where-Object { $_ }) + $excluded = @($Exclude | Where-Object { $_ }) + if ($included.Count -gt 0 -and @($included | Where-Object { $RuleName -like $_ }).Count -eq 0) { + return $false + } + if (@($excluded | Where-Object { $RuleName -like $_ }).Count -gt 0) { + return $false + } + $true +} diff --git a/Public/Export-IntuneFindingSarif.ps1 b/Public/Export-IntuneFindingSarif.ps1 index aa91085..0a61d17 100644 --- a/Public/Export-IntuneFindingSarif.ps1 +++ b/Public/Export-IntuneFindingSarif.ps1 @@ -60,17 +60,6 @@ function Export-IntuneFindingSarif { } end { - function Get-ArtifactLocation { - param([string]$FilePath) - if ($FilePath.StartsWith($rootPath, [System.StringComparison]::OrdinalIgnoreCase)) { - $relative = $FilePath.Substring($rootPath.Length).TrimStart('\', '/') - $segments = $relative -split '[\\/]' | ForEach-Object { [System.Uri]::EscapeDataString($_) } - return [ordered]@{ uri = ($segments -join '/'); uriBaseId = '%SRCROOT%' } - } - # Outside the root: an absolute file URI, with no base to resolve against - [ordered]@{ uri = ([System.Uri]::new($FilePath)).AbsoluteUri } - } - $ruleIndex = [ordered]@{} $rules = [System.Collections.Generic.List[object]]::new() foreach ($name in @($all | ForEach-Object { $_.RuleName } | Sort-Object -Unique)) { @@ -127,7 +116,7 @@ function Export-IntuneFindingSarif { $result.locations = @( [ordered]@{ physicalLocation = [ordered]@{ - artifactLocation = Get-ArtifactLocation -FilePath $scriptPath + artifactLocation = ConvertTo-IslSarifLocation -FilePath $scriptPath -RootPath $rootPath region = $region } } diff --git a/Public/Test-IntuneScript.ps1 b/Public/Test-IntuneScript.ps1 index 23cd8cf..de3cefb 100644 --- a/Public/Test-IntuneScript.ps1 +++ b/Public/Test-IntuneScript.ps1 @@ -51,12 +51,6 @@ function Test-IntuneScript { } } - function Test-RuleSelected { - param([string]$RuleName, [string[]]$Include, [string[]]$Exclude) - if ($Include -and -not ($Include | Where-Object { $RuleName -like $_ })) { return $false } - if ($Exclude -and ($Exclude | Where-Object { $RuleName -like $_ })) { return $false } - $true - } } process { @@ -110,7 +104,7 @@ function Test-IntuneScript { else { $MinimumSeverity } $filters = @{ Include = $include; Exclude = $exclude } $rules = foreach ($rule in $script:RuleOrder) { - if (Test-RuleSelected -RuleName ($rule -replace '^Find-', '') @filters) { $rule } + if (Test-IslRuleSelected -RuleName ($rule -replace '^Find-', '') @filters) { $rule } } $scriptContextSplat = @{ @@ -135,7 +129,7 @@ function Test-IntuneScript { # Say what was assumed: the wrong type silently skips whole rule sets. The note obeys # the rule filters, so -ExcludeRule IslAssumedContext silences it $noteWanted = $scriptContext.TypeSource -notin 'parameter', 'settings', 'directive' -and - (Test-RuleSelected -RuleName 'IslAssumedContext' @filters) + (Test-IslRuleSelected -RuleName 'IslAssumedContext' @filters) if ($noteWanted) { $findingSplat = @{ RuleName = 'IslAssumedContext' diff --git a/Public/Test-IntuneWin32Requirement.ps1 b/Public/Test-IntuneWin32Requirement.ps1 index f172ed1..fcc513a 100644 --- a/Public/Test-IntuneWin32Requirement.ps1 +++ b/Public/Test-IntuneWin32Requirement.ps1 @@ -31,19 +31,6 @@ function Test-IntuneWin32Requirement { $device = Get-IslDeviceFact $checks = [System.Collections.Generic.List[object]]::new() - function Get-Check { - param([string]$Requirement, [bool]$Met, $Actual, $Expected, [string]$Details, $Code) - [pscustomobject]@{ - PSTypeName = 'IntuneScriptLab.RequirementCheck' - Requirement = $Requirement - Met = $Met - Actual = $Actual - Expected = $Expected - Details = if ($Met) { '' } else { $Details } - Applicability = if ($Met) { $null } else { $Code } - } - } - if ($Architecture) { $checkSplat = @{ Requirement = 'Architecture' @@ -53,7 +40,7 @@ function Test-IntuneWin32Requirement { Code = 1000 Details = 'Device architecture (e.g. x86/amd64) is not applicable for the application.' } - $checks.Add((Get-Check @checkSplat)) + $checks.Add((New-IslRequirementCheck @checkSplat)) } if ($MinimumWindowsRelease) { try { @@ -70,7 +57,7 @@ function Test-IntuneWin32Requirement { Details = ('The operating system release is below the configured minimum (portal text and ' + 'device code not observed)') } - $checks.Add((Get-Check @checkSplat)) + $checks.Add((New-IslRequirementCheck @checkSplat)) } if ($MinimumFreeDiskSpaceMB) { $checkSplat = @{ @@ -81,7 +68,7 @@ function Test-IntuneWin32Requirement { Code = 1001 Details = 'Available disk space on the target device is less than the configured minimum.' } - $checks.Add((Get-Check @checkSplat)) + $checks.Add((New-IslRequirementCheck @checkSplat)) } if ($MinimumMemoryMB) { $checkSplat = @{ @@ -92,7 +79,7 @@ function Test-IntuneWin32Requirement { Code = 1003 Details = 'Amount of RAM on the target device is less than the configured minimum.' } - $checks.Add((Get-Check @checkSplat)) + $checks.Add((New-IslRequirementCheck @checkSplat)) } if ($MinimumProcessors) { $checkSplat = @{ @@ -103,7 +90,7 @@ function Test-IntuneWin32Requirement { Code = 1004 Details = 'Count of logical processors on the target device is less than the configured minimum.' } - $checks.Add((Get-Check @checkSplat)) + $checks.Add((New-IslRequirementCheck @checkSplat)) } if ($MinimumCpuSpeedMHz) { $checkSplat = @{ @@ -115,7 +102,7 @@ function Test-IntuneWin32Requirement { Details = ('The CPU speed is below the configured minimum (portal text and device code not ' + 'observed)') } - $checks.Add((Get-Check @checkSplat)) + $checks.Add((New-IslRequirementCheck @checkSplat)) } $failed = @($checks | Where-Object { -not $_.Met }) diff --git a/Tests/Unit/Private/ConvertTo-IslSarifLocation.Tests.ps1 b/Tests/Unit/Private/ConvertTo-IslSarifLocation.Tests.ps1 new file mode 100644 index 0000000..6a4bfd0 --- /dev/null +++ b/Tests/Unit/Private/ConvertTo-IslSarifLocation.Tests.ps1 @@ -0,0 +1,59 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The artifactLocation of a SARIF result: relative to the root where it can be, absolute + otherwise. +#> + +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-Location { + param([string]$FilePath, [string]$RootPath) + $parameters = @{ FilePath = $FilePath; RootPath = $RootPath } + $scope = @{ Parameters = $parameters } + InModuleScope IntuneScriptLab -Parameters $scope { ConvertTo-IslSarifLocation @Parameters } + } +} + +Describe 'ConvertTo-IslSarifLocation' -Tag 'Unit', 'Private' { + + Context 'Parameter Validation' { + It 'needs the path and the root' { + $command = InModuleScope IntuneScriptLab { Get-Command -Name ConvertTo-IslSarifLocation } + $command | Should-HaveParameter -ParameterName FilePath -Type ([string]) -Mandatory + $command | Should-HaveParameter -ParameterName RootPath -Type ([string]) -Mandatory + } + } + + Context 'Core Functionality' { + It 'gives a path below the root as a relative URI with forward slashes and the source root base' { + $location = ConvertTo-Location 'C:\repo\Remediations\A\Detect.ps1' 'C:\repo' + + $location['uri'] | Should-Be 'Remediations/A/Detect.ps1' + $location['uriBaseId'] | Should-Be '%SRCROOT%' + } + + It 'escapes each segment of the relative URI' { + $location = ConvertTo-Location 'C:\repo\My Scripts\Detect #1.ps1' 'C:\repo' + + $location['uri'] | Should-Be 'My%20Scripts/Detect%20%231.ps1' + } + + It 'compares the path with the root without regard to letter case' { + $location = ConvertTo-Location 'c:\REPO\Detect.ps1' 'C:\repo' + + $location['uri'] | Should-Be 'Detect.ps1' + } + + It 'gives a path outside the root as an absolute file URI with no base' { + $location = ConvertTo-Location 'D:\elsewhere\Detect.ps1' 'C:\repo' + + $location['uri'] | Should-Be 'file:///D:/elsewhere/Detect.ps1' + $location.Contains('uriBaseId') | Should-BeFalse + } + } +} diff --git a/Tests/Unit/Private/ConvertTo-IslSettingsObject.Tests.ps1 b/Tests/Unit/Private/ConvertTo-IslSettingsObject.Tests.ps1 new file mode 100644 index 0000000..7a4fb0d --- /dev/null +++ b/Tests/Unit/Private/ConvertTo-IslSettingsObject.Tests.ps1 @@ -0,0 +1,104 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The validation of a settings table and the object the analysis reads from it. The search for + the file is tested in Get-IslSetting.Tests.ps1. +#> + +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-SettingsTable { + param([hashtable]$Table, [string]$Source = '-Settings') + $parameters = @{ Table = $Table; Source = $Source } + $scope = @{ Parameters = $parameters } + InModuleScope IntuneScriptLab -Parameters $scope { ConvertTo-IslSettingsObject @Parameters } + } +} + +Describe 'ConvertTo-IslSettingsObject' -Tag 'Unit', 'Private' { + + Context 'Parameter Validation' { + It 'needs the table and its source' { + $command = InModuleScope IntuneScriptLab { Get-Command -Name ConvertTo-IslSettingsObject } + $command | Should-HaveParameter -ParameterName Table -Type ([hashtable]) -Mandatory + $command | Should-HaveParameter -ParameterName Source -Type ([string]) -Mandatory + } + } + + Context 'Core Functionality' { + It 'gives empty settings for an empty table' { + $settings = ConvertTo-SettingsTable -Table @{} -Source '' + + $settings | Should-HaveType 'IntuneScriptLab.Settings' + $settings.Source | Should-Be '' + $settings.ExcludeRule | Should-BeCollection @() + $settings.IncludeRule | Should-BeCollection @() + $settings.MinimumSeverity | Should-BeNull + $settings.Severity.Count | Should-Be 0 + $settings.ScriptType | Should-BeNull + $settings.Context | Should-BeNull + $settings.Architecture | Should-BeNull + $settings.EnforceSignatureCheck | Should-BeNull + } + + It 'carries every key that is given' { + $settings = ConvertTo-SettingsTable -Table @{ + ExcludeRule = 'IslLongSleep', ''; IncludeRule = 'Isl*'; MinimumSeverity = 'Warning' + Severity = @{ IslLongSleep = 'Error' }; ScriptType = 'Detection'; Context = 'User' + Architecture = 'x64'; EnforceSignatureCheck = $false + } + + $settings.ExcludeRule | Should-BeCollection @('IslLongSleep') + $settings.IncludeRule | Should-BeCollection @('Isl*') + $settings.MinimumSeverity | Should-Be 'Warning' + $settings.Severity['IslLongSleep'] | Should-Be 'Error' + $settings.ScriptType | Should-Be 'Detection' + $settings.Context | Should-Be 'User' + $settings.Architecture | Should-Be 'x64' + $settings.EnforceSignatureCheck | Should-BeFalse + } + + It 'names a key it does not know in a warning and still converts the table' { + $output = InModuleScope IntuneScriptLab { + ConvertTo-IslSettingsObject -Table @{ Severety = @{}; Context = 'User' } -Source 'x.psd1' 3>&1 + } + $warnings = @($output | Where-Object { $_ -is [System.Management.Automation.WarningRecord] }) + $settings = @($output | Where-Object { $_ -isnot [System.Management.Automation.WarningRecord] }) + + $warnings | Should-BeCollection -Count 1 + "$($warnings[0])" | Should-Be 'Unknown settings key(s) in x.psd1: Severety' + $settings | Should-BeCollection -Count 1 + $settings[0].Context | Should-Be 'User' + } + } + + Context 'Error Handling' { + It 'refuses with SettingsInvalid, naming the source' -ForEach @( + @{ + Case = 'a minimum severity outside the set'; Table = @{ MinimumSeverity = 'Fatal' } + Text = '*MinimumSeverity must be one of*' + } + @{ Case = 'an unknown script type'; Table = @{ ScriptType = 'Script' }; Text = '*ScriptType must be*' } + @{ Case = 'an unknown context'; Table = @{ Context = 'Admin' }; Text = '*Context must be System*' } + @{ Case = 'an unknown architecture'; Table = @{ Architecture = 'ia64' }; Text = '*Architecture must*' } + @{ + Case = 'a severity override outside the set'; Table = @{ Severity = @{ IslLongSleep = 'Loud' } } + Text = '*Severity for IslLongSleep*' + } + ) { + $failure = { ConvertTo-SettingsTable -Table $Table -Source 'C:\repo\IntuneScriptLab.settings.psd1' } | + Should-Throw -ExceptionMessage $Text + $failure.FullyQualifiedErrorId | Should-BeLikeString 'SettingsInvalid,*' + $failure.Exception.Message | Should-BeLikeString 'C:\repo\IntuneScriptLab.settings.psd1: *' + } + + It 'names the first value that is wrong, in the order of the checks' { + { ConvertTo-SettingsTable -Table @{ Context = 'Admin'; ScriptType = 'Script' } } | + Should-Throw -ExceptionMessage '*ScriptType must be one of*' + } + } +} diff --git a/Tests/Unit/Private/New-IslRequirementCheck.Tests.ps1 b/Tests/Unit/Private/New-IslRequirementCheck.Tests.ps1 new file mode 100644 index 0000000..0bcc3f6 --- /dev/null +++ b/Tests/Unit/Private/New-IslRequirementCheck.Tests.ps1 @@ -0,0 +1,64 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The result of one requirement that Test-IntuneWin32Requirement checks. +#> + +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 Invoke-NewCheck { + param([hashtable]$Parameters) + $scope = @{ Parameters = $Parameters } + InModuleScope IntuneScriptLab -Parameters $scope { New-IslRequirementCheck @Parameters } + } +} + +Describe 'New-IslRequirementCheck' -Tag 'Unit', 'Private' { + + Context 'Parameter Validation' { + It 'needs the name of the requirement and takes Met as a switch' { + $command = InModuleScope IntuneScriptLab { Get-Command -Name New-IslRequirementCheck } + $command | Should-HaveParameter -ParameterName Requirement -Type ([string]) -Mandatory + $command | Should-HaveParameter -ParameterName Met -Type ([switch]) + } + } + + Context 'Core Functionality' { + It 'leaves out the details and the code of a requirement that is met' { + $check = Invoke-NewCheck @{ + Requirement = 'Architecture'; Met = $true; Actual = 'x64'; Expected = 'x64' + Details = 'not applicable'; Code = 1000 + } + + $check | Should-HaveType 'IntuneScriptLab.RequirementCheck' + $check.Requirement | Should-Be 'Architecture' + $check.Met | Should-BeTrue + $check.Actual | Should-Be 'x64' + $check.Expected | Should-Be 'x64' + $check.Details | Should-Be '' + $check.Applicability | Should-BeNull + } + + It 'carries the details and the code of a requirement that is not met' { + $check = Invoke-NewCheck @{ + Requirement = 'Architecture'; Met = $false; Actual = 'arm64'; Expected = 'x64' + Details = 'not applicable'; Code = 1000 + } + + $check.Met | Should-BeFalse + $check.Details | Should-Be 'not applicable' + $check.Applicability | Should-Be 1000 + } + + It 'takes a requirement without a code' { + $check = Invoke-NewCheck @{ Requirement = 'MinimumWindowsRelease'; Met = $false; Code = $null } + + $check.Met | Should-BeFalse + $check.Applicability | Should-BeNull + } + } +} diff --git a/Tests/Unit/Private/Test-IslRuleSelected.Tests.ps1 b/Tests/Unit/Private/Test-IslRuleSelected.Tests.ps1 new file mode 100644 index 0000000..a63aeb2 --- /dev/null +++ b/Tests/Unit/Private/Test-IslRuleSelected.Tests.ps1 @@ -0,0 +1,54 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The rule filter of Test-IntuneScript: -IncludeRule, -ExcludeRule and the same keys of a + settings 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 Test-Selected { + param([hashtable]$Parameters) + $scope = @{ Parameters = $Parameters } + InModuleScope IntuneScriptLab -Parameters $scope { Test-IslRuleSelected @Parameters } + } +} + +Describe 'Test-IslRuleSelected' -Tag 'Unit', 'Private' { + + Context 'Parameter Validation' { + It 'needs a rule name and takes both lists as optional' { + $command = InModuleScope IntuneScriptLab { Get-Command -Name Test-IslRuleSelected } + $command | Should-HaveParameter -ParameterName RuleName -Type ([string]) -Mandatory + $command | Should-HaveParameter -ParameterName Include -Type ([string[]]) + $command | Should-HaveParameter -ParameterName Exclude -Type ([string[]]) + } + } + + Context 'Core Functionality' { + It 'returns for ' -ForEach @( + @{ Case = 'no lists'; Include = @(); Exclude = @(); Expected = $true } + @{ Case = 'an include pattern that matches'; Include = @('IslLong*'); Exclude = @(); Expected = $true } + @{ Case = 'an include pattern that misses'; Include = @('IslExit*'); Exclude = @(); Expected = $false } + @{ Case = 'an exclusion by name'; Include = @(); Exclude = @('IslLongSleep'); Expected = $false } + @{ Case = 'both lists matching'; Include = @('Isl*'); Exclude = @('IslLong*'); Expected = $false } + @{ Case = 'another letter case'; Include = @('isllongsleep'); Exclude = @(); Expected = $true } + @{ Case = 'lists of empty entries'; Include = @(''); Exclude = @(''); Expected = $true } + ) { + $result = Test-Selected @{ RuleName = 'IslLongSleep'; Include = $Include; Exclude = $Exclude } + + $result | Should-Be $Expected + } + + It 'returns one Boolean' { + $result = @(Test-Selected @{ RuleName = 'IslLongSleep' }) + + $result | Should-BeCollection -Count 1 + Should-HaveType -Actual $result[0] -Expected ([bool]) + } + } +} From 1555715ee06c7a823fa544ae0f2de6f76a12f50c Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:36:09 -0800 Subject: [PATCH 2/3] docs(changelog): say that the public error ID of a bad setting is unchanged --- CHANGELOG.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91a5281..131a25d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,9 +44,8 @@ entries are carried over from the manifest's release notes. - The helper functions nested in `Test-IntuneScript`, `Test-IntuneWin32Requirement`, `Export-IntuneFindingSarif` and `Get-IslSetting` are private functions of their own, each an - advanced function with help and tests (#65). Nothing changes for a caller, except that the error - of a settings value that is not allowed now names `ConvertTo-IslSettingsObject` after - `SettingsInvalid` in its `FullyQualifiedErrorId`. + 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 tenant pre-flight paragraph no longer says since when each check exists, and the roadmap points at this changelog instead of listing versions; a first-time reader wants the overview, and the From 068949ba7e643585d97768359a839723dce70a8a Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:41:01 -0800 Subject: [PATCH 3/3] fix(analysis): accept the Linux file system root in the SARIF location Export-IntuneFindingSarif removes the trailing separator of -Root, so the root / becomes an empty string, which the mandatory -RootPath of ConvertTo-IslSarifLocation refused at binding. The nested function it replaced compared with the empty string, and every path started with it. -RootPath now allows an empty string. --- Private/ConvertTo-IslSarifLocation.ps1 | 4 +++- Tests/Unit/Private/ConvertTo-IslSarifLocation.Tests.ps1 | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/Private/ConvertTo-IslSarifLocation.ps1 b/Private/ConvertTo-IslSarifLocation.ps1 index 7eaf328..e31c384 100644 --- a/Private/ConvertTo-IslSarifLocation.ps1 +++ b/Private/ConvertTo-IslSarifLocation.ps1 @@ -14,7 +14,8 @@ function ConvertTo-IslSarifLocation { The full path of the script that a finding is about. .PARAMETER RootPath - The full path of the folder the relative URIs start from, without a trailing separator. + The full path of the folder the relative URIs start from, without a trailing separator. The + root of a file system on Linux or macOS, /, is an empty string once its separator is removed. .EXAMPLE ConvertTo-IslSarifLocation -FilePath 'C:\repo\Remediations\A\Detect.ps1' -RootPath 'C:\repo' @@ -35,6 +36,7 @@ function ConvertTo-IslSarifLocation { [string]$FilePath, [Parameter(Mandatory)] + [AllowEmptyString()] [string]$RootPath ) diff --git a/Tests/Unit/Private/ConvertTo-IslSarifLocation.Tests.ps1 b/Tests/Unit/Private/ConvertTo-IslSarifLocation.Tests.ps1 index 6a4bfd0..ba348ef 100644 --- a/Tests/Unit/Private/ConvertTo-IslSarifLocation.Tests.ps1 +++ b/Tests/Unit/Private/ConvertTo-IslSarifLocation.Tests.ps1 @@ -55,5 +55,12 @@ Describe 'ConvertTo-IslSarifLocation' -Tag 'Unit', 'Private' { $location['uri'] | Should-Be 'file:///D:/elsewhere/Detect.ps1' $location.Contains('uriBaseId') | Should-BeFalse } + + It 'gives a path below the file system root of Linux, an empty root, as a relative URI' { + $location = ConvertTo-Location '/repo/Remediations/Detect.ps1' '' + + $location['uri'] | Should-Be 'repo/Remediations/Detect.ps1' + $location['uriBaseId'] | Should-Be '%SRCROOT%' + } } }