Skip to content
Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ 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: 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
Expand Down
8 changes: 4 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 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
Expand Down
50 changes: 50 additions & 0 deletions Private/ConvertTo-IslSarifLocation.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
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. 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'

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)]
[AllowEmptyString()]
[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 }
}
106 changes: 106 additions & 0 deletions Private/ConvertTo-IslSettingsObject.ps1
Original file line number Diff line number Diff line change
@@ -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
}
}
73 changes: 4 additions & 69 deletions Private/Get-IslSetting.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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
}
}
Expand Down
79 changes: 79 additions & 0 deletions Private/New-IslRequirementCheck.ps1
Original file line number Diff line number Diff line change
@@ -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 }
}
}
Loading