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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,22 @@ entries are carried over from the manifest's release notes.
they can read is unchanged. `Get-IntuneScriptHealth` still returns its reports when only the
file of `-MarkdownPath` could not be written, and reports that as an error which
`-ErrorAction Stop` turns into the end of the command.
- `Test-IntuneScript` and `Repair-IntuneScript` report a path that is not there, and a script
that cannot be analyzed or written, as an error for that one item and go on with the other
scripts, where the first such item ended the command. `-ErrorAction Stop` ends the command
there. **A script of your own that gates a build on `Test-IntuneScript` has to pass
`-ErrorAction Stop`, or it passes on scripts that were never analyzed**, unless it runs in the
global scope with `$ErrorActionPreference = 'Stop'`, as one started with `pwsh -File` does.
`Examples/Invoke-IntuneScriptGate.ps1`, the PSScriptAnalyzer rule module and
`Should-PassIntuneAnalysis` pass it: the gate and the assertion fail on such a script. A
`-Settings` argument that is wrong still ends `Test-IntuneScript` before any script is analyzed.
- `Test-IntuneWin32Rule`, `Test-IntuneWin32Requirement`, `Get-IntuneAnalyzerRulePath` and the
`Should-` assertions end on a failure with a terminating error raised the way a compiled cmdlet
raises one, where they used `throw`, with the IDs `RuleOperatorMissing`, `RuleValueMissing`,
`RuleValueNameMissing`, `RegistryHiveUnknown`, `RuleIsScript`, `RuleTypeUnknown`,
`WindowsReleaseUnknown`, `AnalyzerRulesMissing` and `PesterAssertionNotSupported`. A settings
file with a value that is not allowed is `SettingsInvalid`. With this, no command of the module
ends with `throw` any more.
- The module's functions run under strict mode, set once in the root module. A read of a variable
that was never assigned, or of a member that is not there, is an error where it was a silent
`$null`. Graph replies, export rows and the other data with optional members are read through one
Expand Down
18 changes: 12 additions & 6 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,22 +113,28 @@ A function that ends with `$PSCmdlet.ThrowTerminatingError()` ends only itself.
that called it carries on at its next statement with nothing where the result should be, unless the
call is inside a `try` that has a `catch`; a `try` with only a `finally`, a nested helper and a
pipeline do not stop it. A `throw` ended every function above it, which is what the callers were
written for. The module is moving from `throw` to `ThrowTerminatingError` one area at a time (#64),
callers first: the caller gets `try { ... } catch { $PSCmdlet.ThrowTerminatingError($_) }`, then the
function it calls is converted.
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.

`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
inside a `try`, where every error travels all the way up. The test lists the calls that still rely
on a `throw`, and the list must match the code exactly. A `try` with a `catch` covers everything
inside a `try`, where every error travels all the way up. The test fails for any call of a
function that can fail, by a `throw` or by `ThrowTerminatingError`, that is not inside a `try` with
a `catch`, and it checks its own analysis on a sample module. A `try` with a `catch` covers everything
called below it, so a nested function needs no `catch` of its own when every call of it is inside
one, as in `Invoke-IntuneWin32AppTest`; the test accepts that and nothing less.

A command that takes several items reports one that fails with `$PSCmdlet.WriteError($_)` in that
`catch` and goes on with the next, and `-ErrorAction Stop` ends it there. A module function that
calls such a command and needs its result passes `-ErrorAction Stop`: without it the call returns
nothing and no error ends anything. In `Invoke-IntuneWin32AppTest` a detection that returned
nothing read as "detected". `Invoke-CallerScript` in the test helpers
nothing read as "detected", and `Test-IntuneScript` returning nothing reads as a script without
findings: the pre-flight, `Repair-IntuneScript`, `Should-PassIntuneAnalysis`, the PSScriptAnalyzer
rule module and the example gate all pass `-ErrorAction Stop` to it. `Invoke-CallerScript` in the test helpers
runs statements from a script without `try` in a new process, for what such a caller sees.

A failure the module detects itself is raised with a record from `New-IslErrorRecord`, which gives
Expand Down
5 changes: 4 additions & 1 deletion Examples/Invoke-IntuneScriptGate.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,10 @@ $scriptFiles = @(foreach ($item in $Path) {
else { $resolved.ProviderPath }
}
})
$testSplat = @{ Path = $scriptFiles; ScriptType = $ScriptType }
# -ErrorAction Stop: the analysis reports a script it cannot read and goes on with the others,
# and a gate must not pass on scripts that were not analyzed. The preference set above does not
# reach a module's command unless this script runs in the global scope
$testSplat = @{ Path = $scriptFiles; ScriptType = $ScriptType; ErrorAction = 'Stop' }

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

The preference this script sets at its top reaches the module only when the script runs in the global scope, as it does when started with -File. Called with & from another script it does not, and the gate went on to print 0 finding(s) and exit 0 for a folder whose script was never analyzed. The new test in ScriptGate.Tests.ps1 starts the gate that way for this reason.

if ($PSBoundParameters.ContainsKey('Settings')) { $testSplat.Settings = $Settings }
if ($IncludeRule) { $testSplat.IncludeRule = $IncludeRule }
if ($ExcludeRule) { $testSplat.ExcludeRule = $ExcludeRule }
Expand Down
4 changes: 2 additions & 2 deletions PSScriptAnalyzer/IntuneScriptLab.Rules.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function Get-IslAnalysis {
$item = Get-Item -LiteralPath $file -ErrorAction Stop
$key = "$($item.FullName)|$($item.LastWriteTimeUtc.Ticks)|$($item.Length)"
if (-not $script:AnalysisCache.ContainsKey($key)) {
$script:AnalysisCache[$key] = @(Test-IntuneScript -Path $item.FullName)
$script:AnalysisCache[$key] = @(Test-IntuneScript -Path $item.FullName -ErrorAction Stop)
}
return $script:AnalysisCache[$key]
}
Expand All @@ -54,7 +54,7 @@ function Get-IslAnalysis {
$temp = Join-Path -Path $folder -ChildPath "definition-$([guid]::NewGuid().ToString('N')).ps1"
try {
[System.IO.File]::WriteAllText($temp, $text, [System.Text.UTF8Encoding]::new($true))
$script:AnalysisCache[$key] = @(Test-IntuneScript -Path $temp)
$script:AnalysisCache[$key] = @(Test-IntuneScript -Path $temp -ErrorAction Stop)
}
finally {
Remove-Item -LiteralPath $temp -Force -ErrorAction SilentlyContinue
Expand Down
20 changes: 18 additions & 2 deletions Private/ConvertFrom-IslRuleSpec.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,24 @@ function ConvertFrom-IslRuleSpec {
}
if ($null -ne $Rule['ProductVersion']) { $value = "$($Rule['ProductVersion'])" }
}
'Script' { throw 'A PowerShell script rule is run with Invoke-IntuneDetectionTest, not evaluated here' }
default { throw "Rule needs a Type of File, Registry or ProductCode (or a win32LobApp*Rule @odata.type)" }
'Script' {
$recordSplat = @{
Message = 'A PowerShell script rule is run with Invoke-IntuneDetectionTest, not evaluated here'
ErrorId = 'RuleIsScript'
Category = [System.Management.Automation.ErrorCategory]::InvalidArgument
ExceptionType = [System.ArgumentException]
}
$PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat))
}
default {
$recordSplat = @{
Message = 'Rule needs a Type of File, Registry or ProductCode (or a win32LobApp*Rule @odata.type)'
ErrorId = 'RuleTypeUnknown'
Category = [System.Management.Automation.ErrorCategory]::InvalidArgument
ExceptionType = [System.ArgumentException]
}
$PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat))
}
}
if ($operator -and $operator -ne 'notConfigured') { $splat.Operator = $operator }
if ($null -ne $value) { $splat.Value = $value }
Expand Down
86 changes: 53 additions & 33 deletions Private/Get-IslSetting.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -65,26 +65,36 @@ function Get-IslSetting {
$context = $Table['Context']
$architecture = $Table['Architecture']
$severityTable = $Table['Severity']
# The first value that is wrong is the one reported
$problem = $null

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Five throw statements became one. The order of the checks is kept, so the value named for a table with several wrong values is the one that was named before; the test with Context = 'Admin'; ScriptType = 'Script' holds that.

if ($minimumSeverity -and "$minimumSeverity" -notin $validSeverities) {
throw "${Source}: MinimumSeverity must be one of $($validSeverities -join ', ')"
}
if ($scriptType -and "$scriptType" -notin $validTypes) {
throw "${Source}: ScriptType must be one of $($validTypes -join ', ')"
}
if ($context -and "$context" -notin 'System', 'User') {
throw "${Source}: Context must be System or User"
}
if ($architecture -and "$architecture" -notin 'x86', 'x64', 'arm64') {
throw "${Source}: Architecture must be x86, x64 or arm64"
$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 ("$($severityTable[$key])" -notin $validSeverities) {
throw "${Source}: Severity for $key must be one of $($validSeverities -join ', ')"
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)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

A throw on purpose. This nested function has no [CmdletBinding()], so it has no $PSCmdlet to end with (#65). Throwing the record instead of a string keeps the ID and the category: the catch of Get-IslSetting ends with this same record.

}
[pscustomobject]@{
PSTypeName = 'IntuneScriptLab.Settings'
Source = $Source
Expand All @@ -102,29 +112,39 @@ function Get-IslSetting {
}
}

if ($null -ne $Settings) {
if ($Settings -is [hashtable]) { return ConvertTo-SettingsObject -Table $Settings -Source '-Settings' }
$file = (Resolve-Path -LiteralPath "$Settings" -ErrorAction Stop).ProviderPath
return ConvertTo-SettingsObject -Table (Import-PowerShellDataFile -LiteralPath $file) -Source $file
}

$resolved = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath
$folder = if (Test-Path -LiteralPath $resolved -PathType Container) { $resolved }
else { Split-Path -Path $resolved -Parent }
if ($Cache.ContainsKey($folder)) { return $Cache[$folder] }

# A settings file that cannot be read, and a value in it that is wrong, end the function
$found = $null
$probe = $folder
while ($probe) {
$candidate = Join-Path -Path $probe -ChildPath 'IntuneScriptLab.settings.psd1'
if (Test-Path -LiteralPath $candidate -PathType Leaf) {
$candidateTable = Import-PowerShellDataFile -LiteralPath $candidate
$found = ConvertTo-SettingsObject -Table $candidateTable -Source $candidate
break
try {
if ($Settings -is [hashtable]) {
$found = ConvertTo-SettingsObject -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
} else {
$resolved = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath
$folder = if (Test-Path -LiteralPath $resolved -PathType Container) { $resolved }
else { Split-Path -Path $resolved -Parent }
if ($Cache.ContainsKey($folder)) {
$found = $Cache[$folder]
} else {
$probe = $folder
while ($probe) {
$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
break
}
$probe = Split-Path -Path $probe -Parent
}
if (-not $found) { $found = ConvertTo-SettingsObject -Table @{} -Source '' }
$Cache[$folder] = $found
}
}
$probe = Split-Path -Path $probe -Parent
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
if (-not $found) { $found = ConvertTo-SettingsObject -Table @{} -Source '' }
$Cache[$folder] = $found

$found
}
11 changes: 10 additions & 1 deletion Private/Get-IslWindowsReleaseBuild.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ function Get-IslWindowsReleaseBuild {
'Windows11_24H2' = 26100
'Windows11_25H2' = 26200
}
if (-not $builds.ContainsKey($Release)) { throw "Unknown Windows release '$Release'" }
if (-not $builds.ContainsKey($Release)) {
$recordSplat = @{
Message = "Unknown Windows release '$Release'"
ErrorId = 'WindowsReleaseUnknown'
Category = [System.Management.Automation.ErrorCategory]::InvalidArgument
TargetObject = $Release
ExceptionType = [System.ArgumentException]
}
$PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat))
}
$builds[$Release]
}
87 changes: 76 additions & 11 deletions Public/Assert-IntuneResult.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,37 @@
# Should-* aliases (Set-Alias in the module file). Each fails with the diagnosis Intune would give.

function Test-IslPesterAssertionSupport {
# New-ShouldAssertion arrived in Pester 6.2; without it these functions cannot report properly.
<#
.SYNOPSIS
Ends with an error when the Pester that is loaded cannot carry the assertions.

.DESCRIPTION
New-ShouldAssertion arrived in Pester 6.2; without it the Assert- functions of this file
cannot report a failure properly. Returns nothing when the command is there.

.EXAMPLE
Test-IslPesterAssertionSupport

Nothing with Pester 6.2 or later loaded, and a terminating error otherwise.

.INPUTS
None.

.OUTPUTS
None.
#>
[CmdletBinding()]
[OutputType([void])]
param()

if (-not (Get-Command -Name New-ShouldAssertion -ErrorAction SilentlyContinue)) {
throw 'The IntuneScriptLab assertions need Pester 6.2 or later loaded (Import-Module Pester)'
$recordSplat = @{
Message = 'The IntuneScriptLab assertions need Pester 6.2 or later loaded (Import-Module Pester)'
ErrorId = 'PesterAssertionNotSupported'
Category = [System.Management.Automation.ErrorCategory]::NotInstalled
TargetObject = 'Pester'
}
$PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat))
}
}

Expand All @@ -30,7 +58,11 @@ function Assert-HaveIntuneStatus {
[string]$Because
)

Test-IslPesterAssertionSupport
try {
Test-IslPesterAssertionSupport
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
$assert = New-ShouldAssertion -Caller $PSCmdlet -Actual $Actual -Buffer $Input
$Actual = $assert.Actual()

Expand Down Expand Up @@ -67,7 +99,11 @@ function Assert-BeIntuneDetected {
[string]$Because
)

Test-IslPesterAssertionSupport
try {
Test-IslPesterAssertionSupport
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
$assert = New-ShouldAssertion -Caller $PSCmdlet -Actual $Actual -Buffer $Input
$Actual = $assert.Actual()

Expand Down Expand Up @@ -95,7 +131,11 @@ function Assert-NotBeIntuneDetected {
[string]$Because
)

Test-IslPesterAssertionSupport
try {
Test-IslPesterAssertionSupport
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
$assert = New-ShouldAssertion -Caller $PSCmdlet -Actual $Actual -Buffer $Input
$Actual = $assert.Actual()

Expand Down Expand Up @@ -127,7 +167,11 @@ function Assert-HaveIntuneRunState {
[string]$Because
)

Test-IslPesterAssertionSupport
try {
Test-IslPesterAssertionSupport
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
$assert = New-ShouldAssertion -Caller $PSCmdlet -Actual $Actual -Buffer $Input
$Actual = $assert.Actual()

Expand Down Expand Up @@ -165,7 +209,11 @@ function Assert-PassIntuneAnalysis {
[string]$Because
)

Test-IslPesterAssertionSupport
try {
Test-IslPesterAssertionSupport
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
# A file, a folder, or a pipeline of either: every script found is analyzed and the failure
# names each file
$assert = New-ShouldAssertion -Caller $PSCmdlet -Actual $Actual -Buffer $Input
Expand All @@ -174,8 +222,17 @@ function Assert-PassIntuneAnalysis {
if ($item -is [System.IO.FileSystemInfo]) { $item.FullName } else { "$item" }
})

$findings = @(Test-IntuneScript -Path $paths -ScriptType $ScriptType -MinimumSeverity $MinimumSeverity |
Where-Object { $_.RuleName -ne 'IslAssumedContext' })
# A path that cannot be analyzed fails the assertion with its error. Test-IntuneScript reports
# such a path and goes on, and with nothing analyzed there is no finding: the assertion
# would pass
$analysisSplat = @{
Path = $paths; ScriptType = $ScriptType; MinimumSeverity = $MinimumSeverity; ErrorAction = 'Stop'

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Without ErrorAction = 'Stop' here, 'no-such-file.ps1' | Should-PassIntuneAnalysis passes. The test "fails for a path that is not there" fails when the entry is taken out.

}
try {
$findings = @(Test-IntuneScript @analysisSplat | Where-Object { $_.RuleName -ne 'IslAssumedContext' })
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
if ($findings.Count -eq 0) { return }

$list = ($findings | ForEach-Object {
Expand Down Expand Up @@ -205,7 +262,11 @@ function Assert-BeIntuneApplicable {
[string]$Because
)

Test-IslPesterAssertionSupport
try {
Test-IslPesterAssertionSupport
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
$assert = New-ShouldAssertion -Caller $PSCmdlet -Actual $Actual -Buffer $Input
$Actual = $assert.Actual()

Expand Down Expand Up @@ -233,7 +294,11 @@ function Assert-NotBeIntuneApplicable {
[string]$Because
)

Test-IslPesterAssertionSupport
try {
Test-IslPesterAssertionSupport
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
$assert = New-ShouldAssertion -Caller $PSCmdlet -Actual $Actual -Buffer $Input
$Actual = $assert.Actual()

Expand Down
Loading
Loading