From b4e7b49e9343710698eb6822328ca2084fb8b8f4 Mon Sep 17 00:00:00 2001
From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com>
Date: Mon, 23 Nov 2026 18:42:41 -0800
Subject: [PATCH] fix(analysis)!: end the analysis and rule commands the cmdlet
way
The last area of #64. Test-IntuneWin32Rule,
Test-IntuneWin32Requirement, Get-IntuneAnalyzerRulePath, the Should-
assertions and the private functions below them ended on a failure
with throw (ERR-10, ERR-11, ERR-14). Each failure is now an error
record with an ID and a category, raised with ThrowTerminatingError,
and every call of a function that can fail is inside a try with a
catch. No command of the module ends with throw any more.
Test-IntuneScript and Repair-IntuneScript take several paths. A path
that is not there, and a script that cannot be analyzed or written, is
reported for that one item and the other scripts are still processed
(ERR-13). A -Settings argument is read once in begin, so one that is
wrong still ends the command before any script is analyzed.
A caller that needs the findings must now ask the analysis to stop:
with nothing returned, a script reads as one without findings. The
tenant pre-flight, Repair-IntuneScript, Should-PassIntuneAnalysis, the
PSScriptAnalyzer rule module and Examples/Invoke-IntuneScriptGate.ps1
pass -ErrorAction Stop. The gate, called from another script, passed
on a script that was never analyzed without it.
The contract test has no list of exceptions left. It fails for any
call of a function that can fail outside a try with a catch, and
checks its own analysis on a sample module of four functions.
Closes #64.
BREAKING CHANGE: Test-IntuneScript and Repair-IntuneScript report a
path that is not there, or a script they cannot analyze, as a
non-terminating error and go on with the other scripts. A script that
gates a build on Test-IntuneScript has to pass -ErrorAction Stop. The
other commands of this area end with a terminating error, after which
a script without try and without $ErrorActionPreference = 'Stop' goes
on at its next statement, where it used to end.
---
CHANGELOG.md | 16 ++
CLAUDE.md | 18 +-
Examples/Invoke-IntuneScriptGate.ps1 | 5 +-
PSScriptAnalyzer/IntuneScriptLab.Rules.psm1 | 4 +-
Private/ConvertFrom-IslRuleSpec.ps1 | 20 +-
Private/Get-IslSetting.ps1 | 86 ++++---
Private/Get-IslWindowsReleaseBuild.ps1 | 11 +-
Public/Assert-IntuneResult.ps1 | 87 ++++++-
Public/Get-IntuneAnalyzerRulePath.ps1 | 9 +-
Public/Repair-IntuneScript.ps1 | 212 ++++++++++--------
Public/Test-IntuneDeployedScript.ps1 | 3 +
Public/Test-IntuneScript.ps1 | 172 ++++++++------
Public/Test-IntuneWin32Requirement.ps1 | 6 +-
Public/Test-IntuneWin32Rule.ps1 | 40 +++-
README.md | 2 +-
Tests/Integration/ScriptGate.Tests.ps1 | 37 +++
Tests/Unit/Module.ErrorFlow.Tests.ps1 | 127 ++++++++---
.../Private/ConvertFrom-IslRuleSpec.Tests.ps1 | 5 +-
Tests/Unit/Private/Get-IslSetting.Tests.ps1 | 9 +-
.../Get-IslWindowsReleaseBuild.Tests.ps1 | 3 +-
.../Assert-PassIntuneAnalysis.Tests.ps1 | 14 ++
.../Get-IntuneAnalyzerRulePath.Tests.ps1 | 8 +
.../Unit/Public/Repair-IntuneScript.Tests.ps1 | 49 ++++
Tests/Unit/Public/Test-IntuneScript.Tests.ps1 | 64 +++++-
.../Public/Test-IntuneWin32Rule.Tests.ps1 | 23 +-
.../Assert-PassIntuneAnalysis.md | 3 +
docs/IntuneScriptLab/Repair-IntuneScript.md | 4 +
docs/IntuneScriptLab/Test-IntuneScript.md | 7 +
en-US/IntuneScriptLab-Help.xml | 20 +-
29 files changed, 779 insertions(+), 285 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ce1b556..9c1c377 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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
diff --git a/CLAUDE.md b/CLAUDE.md
index 102af20..af366ed 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -113,14 +113,18 @@ 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.
@@ -128,7 +132,9 @@ A command that takes several items reports one that fails with `$PSCmdlet.WriteE
`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
diff --git a/Examples/Invoke-IntuneScriptGate.ps1 b/Examples/Invoke-IntuneScriptGate.ps1
index 0fbe95d..9fc591b 100644
--- a/Examples/Invoke-IntuneScriptGate.ps1
+++ b/Examples/Invoke-IntuneScriptGate.ps1
@@ -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' }
if ($PSBoundParameters.ContainsKey('Settings')) { $testSplat.Settings = $Settings }
if ($IncludeRule) { $testSplat.IncludeRule = $IncludeRule }
if ($ExcludeRule) { $testSplat.ExcludeRule = $ExcludeRule }
diff --git a/PSScriptAnalyzer/IntuneScriptLab.Rules.psm1 b/PSScriptAnalyzer/IntuneScriptLab.Rules.psm1
index 76d9f49..8233e99 100644
--- a/PSScriptAnalyzer/IntuneScriptLab.Rules.psm1
+++ b/PSScriptAnalyzer/IntuneScriptLab.Rules.psm1
@@ -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]
}
@@ -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
diff --git a/Private/ConvertFrom-IslRuleSpec.ps1 b/Private/ConvertFrom-IslRuleSpec.ps1
index 0f72270..548eec1 100644
--- a/Private/ConvertFrom-IslRuleSpec.ps1
+++ b/Private/ConvertFrom-IslRuleSpec.ps1
@@ -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 }
diff --git a/Private/Get-IslSetting.ps1 b/Private/Get-IslSetting.ps1
index 7acc495..c49d80d 100644
--- a/Private/Get-IslSetting.ps1
+++ b/Private/Get-IslSetting.ps1
@@ -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
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)
+ }
[pscustomobject]@{
PSTypeName = 'IntuneScriptLab.Settings'
Source = $Source
@@ -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
}
diff --git a/Private/Get-IslWindowsReleaseBuild.ps1 b/Private/Get-IslWindowsReleaseBuild.ps1
index 9046c9e..736363c 100644
--- a/Private/Get-IslWindowsReleaseBuild.ps1
+++ b/Private/Get-IslWindowsReleaseBuild.ps1
@@ -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]
}
diff --git a/Public/Assert-IntuneResult.ps1 b/Public/Assert-IntuneResult.ps1
index 1c5d726..1599c4d 100644
--- a/Public/Assert-IntuneResult.ps1
+++ b/Public/Assert-IntuneResult.ps1
@@ -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))
}
}
@@ -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()
@@ -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()
@@ -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()
@@ -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()
@@ -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
@@ -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'
+ }
+ try {
+ $findings = @(Test-IntuneScript @analysisSplat | Where-Object { $_.RuleName -ne 'IslAssumedContext' })
+ } catch {
+ $PSCmdlet.ThrowTerminatingError($_)
+ }
if ($findings.Count -eq 0) { return }
$list = ($findings | ForEach-Object {
@@ -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()
@@ -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()
diff --git a/Public/Get-IntuneAnalyzerRulePath.ps1 b/Public/Get-IntuneAnalyzerRulePath.ps1
index 4f4101b..a13ea83 100644
--- a/Public/Get-IntuneAnalyzerRulePath.ps1
+++ b/Public/Get-IntuneAnalyzerRulePath.ps1
@@ -12,7 +12,14 @@ function Get-IntuneAnalyzerRulePath {
$folder = Join-Path -Path $moduleBase -ChildPath 'PSScriptAnalyzer'
$path = Join-Path -Path $folder -ChildPath 'IntuneScriptLab.Rules.psm1'
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
- throw "The PSScriptAnalyzer rule module is missing from the module at $moduleBase"
+ $recordSplat = @{
+ Message = "The PSScriptAnalyzer rule module is missing from the module at $moduleBase"
+ ErrorId = 'AnalyzerRulesMissing'
+ Category = [System.Management.Automation.ErrorCategory]::ObjectNotFound
+ TargetObject = $path
+ ExceptionType = [System.IO.FileNotFoundException]
+ }
+ $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat))
}
$path
}
diff --git a/Public/Repair-IntuneScript.ps1 b/Public/Repair-IntuneScript.ps1
index d199cc9..882bc10 100644
--- a/Public/Repair-IntuneScript.ps1
+++ b/Public/Repair-IntuneScript.ps1
@@ -31,8 +31,15 @@ function Repair-IntuneScript {
)
process {
+ # A path that is not there is reported, and the other paths are still repaired
$files = foreach ($item in $Path) {
- foreach ($resolved in (Resolve-Path -Path $item -ErrorAction Stop)) {
+ try {
+ $resolvedItems = @(Resolve-Path -Path $item -ErrorAction Stop)
+ } catch {
+ $PSCmdlet.WriteError($_)
+ continue
+ }
+ foreach ($resolved in $resolvedItems) {
if (Test-Path -LiteralPath $resolved.ProviderPath -PathType Container) {
Get-ChildItem -LiteralPath $resolved.ProviderPath -Recurse -Filter *.ps1 -File |
ForEach-Object { $_.FullName }
@@ -42,111 +49,124 @@ function Repair-IntuneScript {
}
foreach ($file in $files) {
- # The analysis sees the script the way the caller deploys it, so the findings, their
- # fixes and the Remaining count are the ones Test-IntuneScript would give for the same
- # options
- $testSplat = @{
- Path = $file; ScriptType = $ScriptType; Context = $Context; Architecture = $Architecture
- }
- if ($EnforceSignatureCheck) { $testSplat.EnforceSignatureCheck = $true }
- if ($IncludeRule) { $testSplat.IncludeRule = $IncludeRule }
- if ($ExcludeRule) { $testSplat.ExcludeRule = $ExcludeRule }
- if ($PSBoundParameters.ContainsKey('Settings')) { $testSplat.Settings = $Settings }
- $findings = @(Test-IntuneScript @testSplat)
- $fixable = @($findings | Where-Object { $_.Fix })
- $fixes = [System.Collections.Generic.List[object]]::new()
- $written = $false
-
- if ($fixable) {
- $bytes = [System.IO.File]::ReadAllBytes($file)
- $encoding = if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) {
- [System.Text.Encoding]::Unicode
- }
- elseif ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFE -and $bytes[1] -eq 0xFF) {
- [System.Text.Encoding]::BigEndianUnicode
- }
- elseif ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and
- $bytes[2] -eq 0xBF) {
- [System.Text.UTF8Encoding]::new($true)
+ # A script that cannot be analyzed or written is reported, and the next one is still
+ # repaired
+ try {
+ # The analysis sees the script the way the caller deploys it, so the findings, their
+ # fixes and the Remaining count are the ones Test-IntuneScript would give for the same
+ # options
+ # -ErrorAction Stop: the analysis reports a script it cannot read and goes on, and
+ # with no findings this command would call the script repaired
+ $testSplat = @{
+ Path = $file; ScriptType = $ScriptType; Context = $Context; Architecture = $Architecture
+ ErrorAction = 'Stop'
}
- else {
- # No BOM: UTF-8 when the bytes decode as such, otherwise the ANSI code page
- # Windows PowerShell 5.1 reads it in (a UTF-8 decode would turn every non-ASCII
- # character into U+FFFD and lose it for good)
- try {
- $null = [System.Text.UTF8Encoding]::new($false, $true).GetString($bytes)
- [System.Text.UTF8Encoding]::new($false)
+ if ($EnforceSignatureCheck) { $testSplat.EnforceSignatureCheck = $true }
+ if ($IncludeRule) { $testSplat.IncludeRule = $IncludeRule }
+ if ($ExcludeRule) { $testSplat.ExcludeRule = $ExcludeRule }
+ if ($PSBoundParameters.ContainsKey('Settings')) { $testSplat.Settings = $Settings }
+ $findings = @(Test-IntuneScript @testSplat)
+ $fixable = @($findings | Where-Object { $_.Fix })
+ $fixes = [System.Collections.Generic.List[object]]::new()
+ $written = $false
+
+ if ($fixable) {
+ $bytes = [System.IO.File]::ReadAllBytes($file)
+ $encoding = if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) {
+ [System.Text.Encoding]::Unicode
+ }
+ elseif ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFE -and $bytes[1] -eq 0xFF) {
+ [System.Text.Encoding]::BigEndianUnicode
+ }
+ elseif ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and
+ $bytes[2] -eq 0xBF) {
+ [System.Text.UTF8Encoding]::new($true)
+ }
+ else {
+ # No BOM: UTF-8 when the bytes decode as such, otherwise the ANSI code page
+ # Windows PowerShell 5.1 reads it in (a UTF-8 decode would turn every non-ASCII
+ # character into U+FFFD and lose it for good)
+ try {
+ $null = [System.Text.UTF8Encoding]::new($false, $true).GetString($bytes)
+ [System.Text.UTF8Encoding]::new($false)
+ }
+ catch { Get-IslOemEncoding -Kind ANSI }
+ }
+ $text = $encoding.GetString($bytes).TrimStart([char]0xFEFF)
+ $lineStarts = [System.Collections.Generic.List[int]]::new()
+ $lineStarts.Add(0)
+ for ($i = 0; $i -lt $text.Length; $i++) {
+ if ($text[$i] -eq "`n") { $lineStarts.Add($i + 1) }
}
- catch { Get-IslOemEncoding -Kind ANSI }
- }
- $text = $encoding.GetString($bytes).TrimStart([char]0xFEFF)
- $lineStarts = [System.Collections.Generic.List[int]]::new()
- $lineStarts.Add(0)
- for ($i = 0; $i -lt $text.Length; $i++) {
- if ($text[$i] -eq "`n") { $lineStarts.Add($i + 1) }
- }
- # Text edits from the end of the file backwards, so earlier offsets stay valid
- $edits = foreach ($finding in $fixable) {
- if (-not $finding.Fix.ContainsKey('Replacement')) { continue }
- if ($finding.Line -lt 1 -or $finding.Line -gt $lineStarts.Count) { continue }
- $start = $lineStarts[$finding.Line - 1] + $finding.Column - 1
- $before = "$($finding.Text)"
- $current = if ($start + $before.Length -le $text.Length) {
- $text.Substring($start, $before.Length)
+ # Text edits from the end of the file backwards, so earlier offsets stay valid
+ $edits = foreach ($finding in $fixable) {
+ if (-not $finding.Fix.ContainsKey('Replacement')) { continue }
+ if ($finding.Line -lt 1 -or $finding.Line -gt $lineStarts.Count) { continue }
+ $start = $lineStarts[$finding.Line - 1] + $finding.Column - 1
+ $before = "$($finding.Text)"
+ $current = if ($start + $before.Length -le $text.Length) {
+ $text.Substring($start, $before.Length)
+ }
+ else { '' }
+ if ($current -ne $before) {
+ $place = "$file line $($finding.Line)"
+ Write-Warning "${place}: the text changed since the analysis; skipped"
+ continue
+ }
+ [pscustomobject]@{ Start = $start; Finding = $finding; Before = $before }
}
- else { '' }
- if ($current -ne $before) {
- Write-Warning "$file line $($finding.Line): the text changed since the analysis; skipped"
- continue
+ foreach ($edit in ($edits | Sort-Object Start -Descending)) {
+ $after = "$($edit.Finding.Fix.Replacement)"
+ $tail = $text.Substring($edit.Start + $edit.Before.Length)
+ $text = $text.Substring(0, $edit.Start) + $after + $tail
+ $fixes.Add([pscustomobject]@{
+ PSTypeName = 'IntuneScriptLab.Fix'
+ RuleName = $edit.Finding.RuleName
+ Line = $edit.Finding.Line
+ Before = $edit.Before
+ After = $after
+ })
+ }
+ $encodingFix = @($fixable | Where-Object { $_.Fix.ContainsKey('Encoding') }) |
+ Select-Object -First 1
+ $target = $encoding
+ if ($encodingFix) {
+ $target = [System.Text.UTF8Encoding]::new($true)
+ $fixes.Add([pscustomobject]@{
+ PSTypeName = 'IntuneScriptLab.Fix'
+ RuleName = $encodingFix.RuleName
+ Line = 0
+ Before = $encoding.WebName
+ After = 'utf-8 with BOM'
+ })
}
- [pscustomobject]@{ Start = $start; Finding = $finding; Before = $before }
- }
- foreach ($edit in ($edits | Sort-Object Start -Descending)) {
- $after = "$($edit.Finding.Fix.Replacement)"
- $tail = $text.Substring($edit.Start + $edit.Before.Length)
- $text = $text.Substring(0, $edit.Start) + $after + $tail
- $fixes.Add([pscustomobject]@{
- PSTypeName = 'IntuneScriptLab.Fix'
- RuleName = $edit.Finding.RuleName
- Line = $edit.Finding.Line
- Before = $edit.Before
- After = $after
- })
- }
- $encodingFix = @($fixable | Where-Object { $_.Fix.ContainsKey('Encoding') }) |
- Select-Object -First 1
- $target = $encoding
- if ($encodingFix) {
- $target = [System.Text.UTF8Encoding]::new($true)
- $fixes.Add([pscustomobject]@{
- PSTypeName = 'IntuneScriptLab.Fix'
- RuleName = $encodingFix.RuleName
- Line = 0
- Before = $encoding.WebName
- After = 'utf-8 with BOM'
- })
- }
- if ($fixes.Count -gt 0) {
- $rules = @($fixes | ForEach-Object { $_.RuleName } | Sort-Object -Unique) -join ', '
- if ($PSCmdlet.ShouldProcess($file, "Apply $($fixes.Count) fix(es): $rules")) {
- [System.IO.File]::WriteAllText($file, $text, $target)
- $written = $true
+ if ($fixes.Count -gt 0) {
+ $rules = @($fixes | ForEach-Object { $_.RuleName } | Sort-Object -Unique) -join ', '
+ if ($PSCmdlet.ShouldProcess($file, "Apply $($fixes.Count) fix(es): $rules")) {
+ [System.IO.File]::WriteAllText($file, $text, $target)
+ $written = $true
+ }
}
}
- }
- $remaining = if ($written) { @(Test-IntuneScript @testSplat).Count }
- else { $findings.Count - $fixes.Count }
- [pscustomobject]@{
- PSTypeName = 'IntuneScriptLab.Repair'
- Path = $file
- Applied = $fixes.Count
- Remaining = $remaining
- Written = $written
- Fixes = $fixes.ToArray()
+ $remaining = if ($written) { @(Test-IntuneScript @testSplat).Count }
+ else { $findings.Count - $fixes.Count }
+ $repair = [pscustomobject]@{
+ PSTypeName = 'IntuneScriptLab.Repair'
+ Path = $file
+ Applied = $fixes.Count
+ Remaining = $remaining
+ Written = $written
+ Fixes = $fixes.ToArray()
+ }
+ } catch {
+ $PSCmdlet.WriteError($_)
+ continue
}
+
+ $repair
}
}
}
diff --git a/Public/Test-IntuneDeployedScript.ps1 b/Public/Test-IntuneDeployedScript.ps1
index 3cf5a24..7271157 100644
--- a/Public/Test-IntuneDeployedScript.ps1
+++ b/Public/Test-IntuneDeployedScript.ps1
@@ -118,6 +118,9 @@ function Test-IntuneDeployedScript {
Architecture = $architecture
EnforceSignatureCheck = [bool]$EnforceSignatureCheck
MinimumSeverity = $MinimumSeverity
+ # The analysis reports a script it cannot read and goes on. Here that would leave a
+ # policy without findings, which reads as a policy without problems
+ ErrorAction = 'Stop'
}
if ($settingsGiven) { $testSplat.Settings = $Settings }
if ($IncludeRule) { $testSplat.IncludeRule = $IncludeRule }
diff --git a/Public/Test-IntuneScript.ps1 b/Public/Test-IntuneScript.ps1
index 1f588f7..eb8d29e 100644
--- a/Public/Test-IntuneScript.ps1
+++ b/Public/Test-IntuneScript.ps1
@@ -40,6 +40,16 @@ function Test-IntuneScript {
begin {
$severityRank = @{ Information = 0; Warning = 1; Error = 2 }
$settingsCache = @{}
+ # -Settings is the same for every script. It is read once, and one that is wrong ends the
+ # command here instead of failing each script in turn
+ $givenSettings = $null
+ if ($PSBoundParameters.ContainsKey('Settings')) {
+ try {
+ $givenSettings = Get-IslSetting -Path $PWD.Path -Settings $Settings
+ } catch {
+ $PSCmdlet.ThrowTerminatingError($_)
+ }
+ }
function Test-RuleSelected {
param([string]$RuleName, [string[]]$Include, [string[]]$Exclude)
@@ -50,8 +60,15 @@ function Test-IntuneScript {
}
process {
+ # A path that is not there is reported, and the other paths are still analyzed
$files = foreach ($item in $Path) {
- foreach ($resolved in (Resolve-Path -Path $item -ErrorAction Stop)) {
+ try {
+ $resolvedItems = @(Resolve-Path -Path $item -ErrorAction Stop)
+ } catch {
+ $PSCmdlet.WriteError($_)
+ continue
+ }
+ foreach ($resolved in $resolvedItems) {
if (Test-Path -LiteralPath $resolved.ProviderPath -PathType Container) {
Get-ChildItem -LiteralPath $resolved.ProviderPath -Recurse -Filter *.ps1 -File |
ForEach-Object { $_.FullName }
@@ -61,84 +78,95 @@ function Test-IntuneScript {
}
foreach ($file in $files) {
- # Parameters beat the settings file; the settings file beats inference
- $settingsSplat = @{ Path = $file; Cache = $settingsCache }
- if ($PSBoundParameters.ContainsKey('Settings')) { $settingsSplat.Settings = $Settings }
- $fileSettings = Get-IslSetting @settingsSplat
- $include = if ($PSBoundParameters.ContainsKey('IncludeRule')) { $IncludeRule }
- else { $fileSettings.IncludeRule }
- # An explicit -IncludeRule names what to run, so the file's exclusions stand aside for it
- $exclude = if ($PSBoundParameters.ContainsKey('IncludeRule')) { @($ExcludeRule) }
- else { @($ExcludeRule) + @($fileSettings.ExcludeRule) }
- $exclude = @($exclude | Where-Object { $_ })
- $minimum = if ($PSBoundParameters.ContainsKey('MinimumSeverity')) { $MinimumSeverity }
- elseif ($fileSettings.MinimumSeverity) { $fileSettings.MinimumSeverity }
- else { $MinimumSeverity }
- $filters = @{ Include = $include; Exclude = $exclude }
- $rules = foreach ($rule in $script:RuleOrder) {
- if (Test-RuleSelected -RuleName ($rule -replace '^Find-', '') @filters) { $rule }
- }
+ # A script that cannot be analyzed, as when the settings file above it is wrong, is
+ # reported, and the next script is still analyzed
+ try {
+ # Parameters beat the settings file; the settings file beats inference
+ $fileSettings = $givenSettings
+ if ($null -eq $fileSettings) {
+ $fileSettings = Get-IslSetting -Path $file -Cache $settingsCache
+ }
+ $include = if ($PSBoundParameters.ContainsKey('IncludeRule')) { $IncludeRule }
+ else { $fileSettings.IncludeRule }
+ # An explicit -IncludeRule names what to run, so the file's exclusions stand aside for it
+ $exclude = if ($PSBoundParameters.ContainsKey('IncludeRule')) { @($ExcludeRule) }
+ else { @($ExcludeRule) + @($fileSettings.ExcludeRule) }
+ $exclude = @($exclude | Where-Object { $_ })
+ $minimum = if ($PSBoundParameters.ContainsKey('MinimumSeverity')) { $MinimumSeverity }
+ elseif ($fileSettings.MinimumSeverity) { $fileSettings.MinimumSeverity }
+ else { $MinimumSeverity }
+ $filters = @{ Include = $include; Exclude = $exclude }
+ $rules = foreach ($rule in $script:RuleOrder) {
+ if (Test-RuleSelected -RuleName ($rule -replace '^Find-', '') @filters) { $rule }
+ }
- $scriptContextSplat = @{
- Path = $file
- ScriptType = $ScriptType
- Context = $Context
- Architecture = $Architecture
- Settings = $fileSettings
- }
- # Bound either way it is explicit: the pre-flight passes the policy's own false value
- if ($PSBoundParameters.ContainsKey('EnforceSignatureCheck')) {
- $scriptContextSplat.EnforceSignatureCheck = if ($EnforceSignatureCheck) { 'True' } else { 'False' }
- }
- $scriptContext = Get-IslScriptContext @scriptContextSplat
- Write-Verbose ("$file : $($scriptContext.ScriptType) ($($scriptContext.TypeSource)), " +
- "$($scriptContext.Context), $($scriptContext.Architecture)")
-
- $findings = @(foreach ($rule in $rules) {
- & $rule -Context $scriptContext
- })
- # 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)
- if ($noteWanted) {
- $findingSplat = @{
- RuleName = 'IslAssumedContext'
- Severity = 'Information'
- Context = $scriptContext
- Message = ("Analyzed as $($scriptContext.ScriptType) ($($scriptContext.TypeSource)), " +
- "$($scriptContext.Context) context, $($scriptContext.Architecture): the portal " +
- 'defaults where nothing said otherwise; a deployment through the Graph API or IaC ' +
- 'gets 64-bit SYSTEM. Pass ' +
- "-ScriptType/-Context/-Architecture or add a '# IntuneScriptLab:' " +
- 'directive if that is wrong')
- Evidence = ('Portal defaults: platform scripts run as the user in 32-bit, remediations ' +
- 'as SYSTEM in 32-bit, Win32 detection in 64-bit; Graph stores runAs32Bit=false and ' +
- 'runAsAccount=system when omitted (Graph API defaults)')
+ $scriptContextSplat = @{
+ Path = $file
+ ScriptType = $ScriptType
+ Context = $Context
+ Architecture = $Architecture
+ Settings = $fileSettings
+ }
+ # Bound either way it is explicit: the pre-flight passes the policy's own false value
+ if ($PSBoundParameters.ContainsKey('EnforceSignatureCheck')) {
+ $signatureText = if ($EnforceSignatureCheck) { 'True' } else { 'False' }
+ $scriptContextSplat.EnforceSignatureCheck = $signatureText
+ }
+ $scriptContext = Get-IslScriptContext @scriptContextSplat
+ Write-Verbose ("$file : $($scriptContext.ScriptType) ($($scriptContext.TypeSource)), " +
+ "$($scriptContext.Context), $($scriptContext.Architecture)")
+
+ $findings = @(foreach ($rule in $rules) {
+ & $rule -Context $scriptContext
+ })
+ # 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)
+ if ($noteWanted) {
+ $findingSplat = @{
+ RuleName = 'IslAssumedContext'
+ Severity = 'Information'
+ Context = $scriptContext
+ Message = ("Analyzed as $($scriptContext.ScriptType) ($($scriptContext.TypeSource)), " +
+ "$($scriptContext.Context) context, $($scriptContext.Architecture): the portal " +
+ 'defaults where nothing said otherwise; a deployment through the Graph API or IaC ' +
+ 'gets 64-bit SYSTEM. Pass ' +
+ "-ScriptType/-Context/-Architecture or add a '# IntuneScriptLab:' " +
+ 'directive if that is wrong')
+ Evidence = ('Portal defaults: platform scripts run as the user in 32-bit, remediations ' +
+ 'as SYSTEM in 32-bit, Win32 detection in 64-bit; Graph stores runAs32Bit=false and ' +
+ 'runAsAccount=system when omitted (Graph API defaults)')
+ }
+ $findings = @(New-IslFinding @findingSplat) + $findings
}
- $findings = @(New-IslFinding @findingSplat) + $findings
- }
- # Severity overrides from the settings file, then the suppressions in the script
- foreach ($finding in $findings) {
- if ($fileSettings.Severity.ContainsKey($finding.RuleName)) {
- $finding.Severity = $fileSettings.Severity[$finding.RuleName]
+ # Severity overrides from the settings file, then the suppressions in the script
+ foreach ($finding in $findings) {
+ if ($fileSettings.Severity.ContainsKey($finding.RuleName)) {
+ $finding.Severity = $fileSettings.Severity[$finding.RuleName]
+ }
}
- }
- $suppressions = @(Get-IslSuppression -Context $scriptContext)
- foreach ($finding in $findings) {
- foreach ($suppression in $suppressions) {
- if ($finding.RuleName -like $suppression.Rule -and
- ($suppression.Line -eq 0 -or $suppression.Line -eq $finding.Line)) {
- $finding.Suppressed = $true
- break
+ $suppressions = @(Get-IslSuppression -Context $scriptContext)
+ foreach ($finding in $findings) {
+ foreach ($suppression in $suppressions) {
+ if ($finding.RuleName -like $suppression.Rule -and
+ ($suppression.Line -eq 0 -or $suppression.Line -eq $finding.Line)) {
+ $finding.Suppressed = $true
+ break
+ }
}
}
+ $selected = @($findings | Where-Object {
+ $severityRank[$_.Severity] -ge $severityRank[$minimum] -and
+ ($IncludeSuppressed -or -not $_.Suppressed)
+ })
+ } catch {
+ $PSCmdlet.WriteError($_)
+ continue
}
- $findings | Where-Object {
- $severityRank[$_.Severity] -ge $severityRank[$minimum] -and
- ($IncludeSuppressed -or -not $_.Suppressed)
- }
+
+ $selected
}
}
}
diff --git a/Public/Test-IntuneWin32Requirement.ps1 b/Public/Test-IntuneWin32Requirement.ps1
index cb070fe..f172ed1 100644
--- a/Public/Test-IntuneWin32Requirement.ps1
+++ b/Public/Test-IntuneWin32Requirement.ps1
@@ -56,7 +56,11 @@ function Test-IntuneWin32Requirement {
$checks.Add((Get-Check @checkSplat))
}
if ($MinimumWindowsRelease) {
- $required = Get-IslWindowsReleaseBuild -Release $MinimumWindowsRelease
+ try {
+ $required = Get-IslWindowsReleaseBuild -Release $MinimumWindowsRelease
+ } catch {
+ $PSCmdlet.ThrowTerminatingError($_)
+ }
$checkSplat = @{
Requirement = 'MinimumWindowsRelease'
Met = $device.Build -ge $required
diff --git a/Public/Test-IntuneWin32Rule.ps1 b/Public/Test-IntuneWin32Rule.ps1
index ff0b97b..3ae78a8 100644
--- a/Public/Test-IntuneWin32Rule.ps1
+++ b/Public/Test-IntuneWin32Rule.ps1
@@ -54,11 +54,21 @@ function Test-IntuneWin32Rule {
)
Write-Verbose "Starting $($MyInvocation.MyCommand.Name) ($($PSCmdlet.ParameterSetName))"
+ $argumentError = @{
+ Category = [System.Management.Automation.ErrorCategory]::InvalidArgument
+ ExceptionType = [System.ArgumentException]
+ }
if ($PSCmdlet.ParameterSetName -eq 'Rule') {
- $splat = ConvertFrom-IslRuleSpec -Rule $Rule
- if ($Rule.ContainsKey('RuleType') -and $Rule.RuleType) { $splat.RuleType = $Rule.RuleType }
- else { $splat.RuleType = $RuleType }
- return Test-IntuneWin32Rule @splat
+ # A rule that cannot be read, or that the parameters refuse, ends this call as well
+ try {
+ $splat = ConvertFrom-IslRuleSpec -Rule $Rule
+ if ($Rule.ContainsKey('RuleType') -and $Rule.RuleType) { $splat.RuleType = $Rule.RuleType }
+ else { $splat.RuleType = $RuleType }
+ $ruleResult = Test-IntuneWin32Rule @splat
+ } catch {
+ $PSCmdlet.ThrowTerminatingError($_)
+ }
+ return $ruleResult
}
$kind = $PSCmdlet.ParameterSetName
@@ -82,10 +92,14 @@ function Test-IntuneWin32Rule {
}
$needsValue = $operation -notin 'Exists', 'DoesNotExist'
if ($needsValue -and -not $Operator) {
- throw "A $kind $operation rule needs -Operator and -Value"
+ $message = "A $kind $operation rule needs -Operator and -Value"
+ $record = New-IslErrorRecord -Message $message -ErrorId 'RuleOperatorMissing' @argumentError
+ $PSCmdlet.ThrowTerminatingError($record)
}
if ($needsValue -and -not $PSBoundParameters.ContainsKey('Value')) {
- throw "A $kind $operation rule needs -Value"
+ $message = "A $kind $operation rule needs -Value"
+ $record = New-IslErrorRecord -Message $message -ErrorId 'RuleValueMissing' @argumentError
+ $PSCmdlet.ThrowTerminatingError($record)
}
switch ($kind) {
@@ -174,7 +188,11 @@ function Test-IntuneWin32Rule {
'^(HKEY_CLASSES_ROOT|HKCR)$' { 'ClassesRoot' }
'^(HKEY_USERS|HKU)$' { 'Users' }
'^(HKEY_CURRENT_CONFIG|HKCC)$' { 'CurrentConfig' }
- default { throw "Registry key path must start with a hive (HKEY_LOCAL_MACHINE\...): $KeyPath" }
+ default {
+ $message = "Registry key path must start with a hive (HKEY_LOCAL_MACHINE\...): $KeyPath"
+ $record = New-IslErrorRecord -Message $message -ErrorId 'RegistryHiveUnknown' @argumentError
+ $PSCmdlet.ThrowTerminatingError($record)
+ }
}
$result.Target = if ($ValueName) { "$KeyPath : $ValueName" } else { $KeyPath }
$viewLabel = if ($view -eq 'Registry32') { '32-bit view' } else { '64-bit view' }
@@ -207,7 +225,13 @@ function Test-IntuneWin32Rule {
"in the $viewLabel (registry DoesNotExist is evaluated, W32-REG-KEY-NOTEXIST)"
}
default {
- if (-not $ValueName) { throw "A registry $operation rule needs -ValueName" }
+ if (-not $ValueName) {
+ $recordSplat = @{
+ Message = "A registry $operation rule needs -ValueName"
+ ErrorId = 'RuleValueNameMissing'
+ }
+ $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat @argumentError))
+ }
if (-not $valueExists) {
$result.Reason = "The value does not exist in the $viewLabel, so the rule is not met"
break
diff --git a/README.md b/README.md
index a36d966..af330a9 100644
--- a/README.md
+++ b/README.md
@@ -744,7 +744,7 @@ Install-PSResource Microsoft.PowerShell.PlatyPS # 1.0.3 or later, once
| `-Context System` says "run elevated" | `Register-ScheduledTask` needs an administrator session. Restart PowerShell as administrator; the current-user runs need no elevation. |
| `-Architecture x64` refused on an ARM64 PC | ARM64 Windows has no x64 `powershell.exe`; only x86 (emulated) and arm64 (native) exist there, which is what Intune's agent uses too. Test x64 on an x64 machine. |
| Runtime result differs from what Intune showed | Compare what the result carries as Intune reports it: `IntuneOutput` and `IntuneError` on a remediation result, `StdOut`, `StdErr` and `ExitCode` on a detection, platform script or requirement result (OEM code page; the 2,048-character tail where the portal caps it). The `-Verbose` switch prints each step. |
-| A script goes on after a command failed | The log commands (`Get-IntuneAgentLog`, `Get-IntuneAgentTimeline`, `Export-IntuneAgentDiagnostic`), the five `Invoke-Intune*Test` commands and the tenant commands (`Test-IntuneDeployedScript`, `Compare-IntuneDeployedScript`, `Get-IntuneScriptHealth`, `Test-IntuneAssignmentFilter`) end on a failure with a terminating error, as a compiled cmdlet does: the command ends, and the script decides whether it stops too. Start the script with `$ErrorActionPreference = 'Stop'`, or make the call inside `try`. The error's `FullyQualifiedErrorId` says what failed, for example `UnknownAgentLogEvent`, `DiagnosticPackageExists`, `HostArchitectureUnavailable`, `ScheduledTaskNotRegistered` or `GraphModuleNotLoaded`; a request that Graph refused ends the command with Graph's own error. One item among several is reported for that item and the others are still processed: a path that does not exist and a log that cannot be parsed (`CmTraceTimestampInvalid`) for the log commands, a script that cannot be run for `Invoke-IntuneDetectionTest`, `Invoke-IntuneRequirementTest` and `Invoke-IntunePlatformScriptTest`. `-ErrorAction Stop` ends the command there. |
+| A script goes on after a command failed | Every command of the module ends on a failure with a terminating error, as a compiled cmdlet does: the command ends, and the script decides whether it stops too. Start the script with `$ErrorActionPreference = 'Stop'`, or make the call inside `try`. The error's `FullyQualifiedErrorId` says what failed, for example `UnknownAgentLogEvent`, `DiagnosticPackageExists`, `HostArchitectureUnavailable`, `ScheduledTaskNotRegistered` or `GraphModuleNotLoaded`; a request that Graph refused ends the command with Graph's own error. One item among several is reported for that item and the others are still processed: a path that does not exist and a log that cannot be parsed (`CmTraceTimestampInvalid`) for the log commands, a script that cannot be run for `Invoke-IntuneDetectionTest`, `Invoke-IntuneRequirementTest` and `Invoke-IntunePlatformScriptTest`, a path that is not there or a script that cannot be analyzed for `Test-IntuneScript` and `Repair-IntuneScript`. `-ErrorAction Stop` ends the command there, and a script that gates a build on `Test-IntuneScript` passes it, as [Invoke-IntuneScriptGate.ps1](Examples/Invoke-IntuneScriptGate.ps1) does. |
| Pester says `Should-HaveIntuneStatus` is not recognised | The aliases come from this module, not Pester: `Import-Module IntuneScriptLab` in `BeforeAll`, and use Pester 6.2 or later (`New-ShouldAssertion`). |
## Blog posts
diff --git a/Tests/Integration/ScriptGate.Tests.ps1 b/Tests/Integration/ScriptGate.Tests.ps1
index 32d13c1..acfb42a 100644
--- a/Tests/Integration/ScriptGate.Tests.ps1
+++ b/Tests/Integration/ScriptGate.Tests.ps1
@@ -70,6 +70,43 @@ Describe 'Invoke-IntuneScriptGate' -Tag 'Integration', 'Gate' {
($clean.Output -join "`n") | Should-BeLikeString '*0 finding(s) in 0 script(s)*'
}
+ It 'fails, and says why, when a script cannot be analyzed' {
+ # The analysis reports such a script and goes on with the others; a gate that went on too
+ # would pass on scripts nobody looked at
+ $folder = Join-Path $TestDrive 'Unreadable'
+ $null = New-Item -ItemType Directory -Path $folder -Force
+ $utf8Bom = [System.Text.UTF8Encoding]::new($true)
+ [System.IO.File]::WriteAllText((Join-Path $folder 'Detect-Thing.ps1'),
+ "Write-Output 'checked'`r`nexit 0`r`n", $utf8Bom)
+ Set-Content -LiteralPath (Join-Path $folder 'IntuneScriptLab.settings.psd1') -Encoding ascii -Value (
+ "@{ MinimumSeverity = 'Fatal' }")
+
+ # Called from a command, as another script calls it, and not with -File: started with
+ # -File the gate runs in the global scope, where its own error preference reaches the
+ # module, and the test would pass without the gate asking the analysis to stop.
+ # The error stream goes to a file: read with 2>&1, Windows PowerShell 5.1 turns each line
+ # of it into an error record of this test
+ $outFile = Join-Path $TestDrive 'gate-out.txt'
+ $errFile = Join-Path $TestDrive 'gate-err.txt'
+ $call = "& '$($script:Gate)' -Path '$folder'"
+ $processSplat = @{
+ FilePath = $script:HostExe
+ ArgumentList = "-NoProfile -NonInteractive -Command `"$call`""
+ RedirectStandardOutput = $outFile
+ RedirectStandardError = $errFile
+ Wait = $true
+ PassThru = $true
+ WindowStyle = 'Hidden'
+ }
+ $gate = Start-Process @processSplat
+ $written = (Get-Content -LiteralPath $outFile, $errFile) -join ' '
+
+ $gate.ExitCode | Should-NotBe 0
+ # The host wraps the error to its own width, so only the name of the setting is looked for
+ $written | Should-BeLikeString '*MinimumSeverity*'
+ $written | Should-NotBeLikeString '*finding(s) in*'
+ }
+
It 'fails on warnings when asked, and honours the rule filters' {
$note = Invoke-GateFile -Arguments @('-Path', $script:Scripts, '-FailOn', 'Warning',
'-IncludeRule', 'IslAssumedContext')
diff --git a/Tests/Unit/Module.ErrorFlow.Tests.ps1 b/Tests/Unit/Module.ErrorFlow.Tests.ps1
index eb64dbd..dc5f2e1 100644
--- a/Tests/Unit/Module.ErrorFlow.Tests.ps1
+++ b/Tests/Unit/Module.ErrorFlow.Tests.ps1
@@ -11,9 +11,9 @@
travels all the way up. So the rule is checked as a rule: no call to a function that can end
with ThrowTerminatingError outside a try with a catch.
- The module is being moved from throw to ThrowTerminatingError one area at a time (#64). The
- calls that still rely on a throw in the function they call are listed below, and the list has
- to match what is in the code exactly, so it shrinks with every area that is converted.
+ The module was moved from throw to ThrowTerminatingError one area at a time (#64), with a
+ list here of the calls that still relied on a throw. The list is empty now and gone: a call
+ to a function that can fail, by either means, has to be inside a try with a catch.
#>
BeforeAll {
@@ -28,8 +28,8 @@ BeforeAll {
Every function of Public, Private and Private\Rules is a node, and so is every function
nested in one of them. A node can fail when it has a throw outside a try with a catch,
when it calls ThrowTerminatingError, or when it makes an unguarded call to a node that
- can fail. Returns one object for each unguarded call to a node that can fail, with
- Caller, Callee, Call (both names) and EndsQuietly: whether the callee ends with
+ can fail. Returns one object for each call to a node that can fail, with Caller,
+ Callee, Call (both names), Guarded, and EndsQuietly: whether the callee ends with
ThrowTerminatingError, which lets the caller carry on.
A call is guarded when it is inside a try that has a catch. A call made in a nested
@@ -173,10 +173,11 @@ BeforeAll {
}
} while ($changed)
+ # One line for each pair of names, and an unguarded call wins over a guarded one
$seen = @{}
- foreach ($call in $calls) {
+ foreach ($call in ($calls | Sort-Object -Property Guarded)) {
$text = "$($call.Caller) -> $($call.Callee)"
- if ($call.Guarded -or -not $canFail.ContainsKey($call.Callee) -or $seen.ContainsKey($text)) {
+ if (-not $canFail.ContainsKey($call.Callee) -or $seen.ContainsKey($text)) {
continue
}
$seen[$text] = $true
@@ -184,51 +185,103 @@ BeforeAll {
Caller = $call.Caller
Callee = $call.Callee
Call = $text
+ Guarded = $call.Guarded
EndsQuietly = $endsQuietly.ContainsKey($call.Callee)
}
}
}
- $script:Unguarded = @(Get-ErrorFlowCall -ModuleRoot $script:ModuleRoot)
+ $script:Calls = @(Get-ErrorFlowCall -ModuleRoot $script:ModuleRoot)
}
Describe 'How a failure travels through the module' -Tag 'Unit', 'Contract' {
It 'finds the module''s functions and the calls between them' {
- # Guards the two tests below against an analysis that found nothing to check
- $script:Unguarded.Count | Should-BeGreaterThan 0
- @($script:Unguarded | Where-Object { $_.Caller -eq 'Get-IntuneAgentTimeline' }) |
- Should-BeCollection -Count 0
+ # Guards the test below against an analysis that found nothing to check
+ $script:Calls.Count | Should-BeGreaterThan 40
+ $launchCall = 'Invoke-IntuneDetectionTest -> Invoke-IslScriptRun'
+ $launch = @($script:Calls | Where-Object { $_.Call -eq $launchCall })
+ $launch | Should-BeCollection -Count 1
+ $launch[0].Guarded | Should-BeTrue
+ $launch[0].EndsQuietly | Should-BeTrue
}
- It 'never calls a function that ends with ThrowTerminatingError outside a try with a catch' {
- # The caller would carry on with nothing where the result should be
- $quiet = @($script:Unguarded | Where-Object { $_.EndsQuietly } | ForEach-Object { $_.Call } | Sort-Object)
+ It 'never calls a function that can fail outside a try with a catch' {
+ # After a function that ends with ThrowTerminatingError, the caller would carry on with
+ # nothing where the result should be
+ $unguarded = @($script:Calls | Where-Object { -not $_.Guarded } | ForEach-Object { $_.Call } | Sort-Object)
- $quiet | Should-BeCollection @()
+ $unguarded | Should-BeCollection @()
}
+}
- It 'lists every call that still relies on a throw in the function it calls, and no other' {
- # Not yet converted (#64). A line goes when its caller gets the try and the catch; a new
- # line is a call that was added without them
- $pending = @(
- 'Assert-BeIntuneApplicable -> Test-IslPesterAssertionSupport'
- 'Assert-BeIntuneDetected -> Test-IslPesterAssertionSupport'
- 'Assert-HaveIntuneRunState -> Test-IslPesterAssertionSupport'
- 'Assert-HaveIntuneStatus -> Test-IslPesterAssertionSupport'
- 'Assert-NotBeIntuneApplicable -> Test-IslPesterAssertionSupport'
- 'Assert-NotBeIntuneDetected -> Test-IslPesterAssertionSupport'
- 'Assert-PassIntuneAnalysis -> Test-IntuneScript'
- 'Assert-PassIntuneAnalysis -> Test-IslPesterAssertionSupport'
- 'Get-IslSetting -> Get-IslSetting::ConvertTo-SettingsObject'
- 'Repair-IntuneScript -> Test-IntuneScript'
- 'Test-IntuneScript -> Get-IslSetting'
- 'Test-IntuneWin32Requirement -> Get-IslWindowsReleaseBuild'
- 'Test-IntuneWin32Rule -> ConvertFrom-IslRuleSpec'
- )
- $relying = @($script:Unguarded | Where-Object { -not $_.EndsQuietly } | ForEach-Object { $_.Call })
+Describe 'The analysis itself, on a module of four functions' -Tag 'Unit', 'Contract' {
+
+ BeforeAll {
+ $root = Join-Path $TestDrive 'SampleModule'
+ foreach ($folder in 'Public', 'Private', 'Private\Rules') {
+ $null = New-Item -ItemType Directory -Path (Join-Path $root $folder) -Force
+ }
+ $files = @{
+ 'Private\Get-Inner.ps1' = @'
+function Get-Inner {
+ [CmdletBinding()]
+ param()
+ $PSCmdlet.ThrowTerminatingError($record)
+}
+'@
+ 'Public\Get-Careless.ps1' = @'
+function Get-Careless {
+ [CmdletBinding()]
+ param()
+ try { $value = Get-Inner } finally { $null = $value }
+}
+'@
+ 'Public\Get-Careful.ps1' = @'
+function Get-Careful {
+ [CmdletBinding()]
+ param()
+ function Get-Nested { Get-Inner }
+ try { Get-Nested } catch { $PSCmdlet.ThrowTerminatingError($_) }
+}
+'@
+ 'Public\Get-HalfCareful.ps1' = @'
+function Get-HalfCareful {
+ [CmdletBinding()]
+ param()
+ function Get-Nested { Get-Inner }
+ try { Get-Nested } catch { $PSCmdlet.ThrowTerminatingError($_) }
+ Get-Nested
+}
+'@
+ }
+ foreach ($name in $files.Keys) {
+ Set-Content -LiteralPath (Join-Path $root $name) -Value $files[$name] -Encoding ascii
+ }
+ $script:Sample = @(Get-ErrorFlowCall -ModuleRoot $root)
+ }
+
+ It 'reports a call that has only a finally around it' {
+ $call = @($script:Sample | Where-Object { $_.Call -eq 'Get-Careless -> Get-Inner' })
+
+ $call | Should-BeCollection -Count 1
+ $call[0].Guarded | Should-BeFalse
+ $call[0].EndsQuietly | Should-BeTrue
+ }
+
+ It 'accepts a call in a nested function when every call of that nested function is guarded' {
+ $nested = @($script:Sample | Where-Object { $_.Caller -like 'Get-Careful*' })
+
+ $nested.Count | Should-BeGreaterThan 0
+ @($nested | Where-Object { -not $_.Guarded }) | Should-BeCollection @()
+ }
+
+ It 'reports the call in a nested function when one call of that nested function is not guarded' {
+ $unguarded = @($script:Sample | Where-Object { $_.Caller -like 'Get-HalfCareful*' -and -not $_.Guarded } |
+ ForEach-Object { $_.Call } | Sort-Object)
- @($relying | Where-Object { $_ -notin $pending } | Sort-Object) | Should-BeCollection @()
- @($pending | Where-Object { $_ -notin $relying } | Sort-Object) | Should-BeCollection @()
+ $unguarded | Should-BeCollection -Count 2
+ $unguarded[0] | Should-Be 'Get-HalfCareful -> Get-HalfCareful::Get-Nested'
+ $unguarded[1] | Should-Be 'Get-HalfCareful::Get-Nested -> Get-Inner'
}
}
diff --git a/Tests/Unit/Private/ConvertFrom-IslRuleSpec.Tests.ps1 b/Tests/Unit/Private/ConvertFrom-IslRuleSpec.Tests.ps1
index f1f3a93..92b398a 100644
--- a/Tests/Unit/Private/ConvertFrom-IslRuleSpec.Tests.ps1
+++ b/Tests/Unit/Private/ConvertFrom-IslRuleSpec.Tests.ps1
@@ -60,7 +60,8 @@ Describe 'ConvertFrom-IslRuleSpec' -Tag 'Unit', 'Private' {
It 'refuses a script rule and an unknown shape' {
{ Convert-Spec @{ '@odata.type' = '#microsoft.graph.win32LobAppPowerShellScriptRule' } } |
- Should-Throw -ExceptionMessage '*Invoke-IntuneDetectionTest*'
- { Convert-Spec @{ Path = 'C:\x' } } | Should-Throw -ExceptionMessage '*Type of File, Registry*'
+ Should-Throw -FullyQualifiedErrorId 'RuleIsScript,*' -ExceptionMessage '*Invoke-IntuneDetectionTest*'
+ { Convert-Spec @{ Path = 'C:\x' } } |
+ Should-Throw -FullyQualifiedErrorId 'RuleTypeUnknown,*' -ExceptionMessage '*Type of File, Registry*'
}
}
diff --git a/Tests/Unit/Private/Get-IslSetting.Tests.ps1 b/Tests/Unit/Private/Get-IslSetting.Tests.ps1
index a1fe363..1d9de3c 100644
--- a/Tests/Unit/Private/Get-IslSetting.Tests.ps1
+++ b/Tests/Unit/Private/Get-IslSetting.Tests.ps1
@@ -109,8 +109,13 @@ Describe 'Get-IslSetting' -Tag 'Unit', 'Private' {
Should-Throw -ExceptionMessage '*ScriptType must be one of*'
{ Get-Setting 'Other\Run.ps1' -Settings @{ Severity = @{ IslLongSleep = 'Loud' } } } |
Should-Throw -ExceptionMessage '*Severity for IslLongSleep*'
- { Get-Setting 'Other\Run.ps1' -Settings @{ Context = 'Admin' } } | Should-Throw
- { Get-Setting 'Other\Run.ps1' -Settings @{ Architecture = 'ia64' } } | Should-Throw
+ { Get-Setting 'Other\Run.ps1' -Settings @{ Context = 'Admin' } } |
+ Should-Throw -FullyQualifiedErrorId 'SettingsInvalid*' -ExceptionMessage '*Context must be System*'
+ { Get-Setting 'Other\Run.ps1' -Settings @{ Architecture = 'ia64' } } |
+ Should-Throw -FullyQualifiedErrorId 'SettingsInvalid*' -ExceptionMessage '*Architecture must be*'
+ # The first value that is wrong is the one named
+ { Get-Setting 'Other\Run.ps1' -Settings @{ Context = 'Admin'; ScriptType = 'Script' } } |
+ Should-Throw -ExceptionMessage '*ScriptType must be one of*'
$result = InModuleScope IntuneScriptLab -Parameters @{ Path = (Join-Path $script:Tree 'Other\Run.ps1') } {
Get-IslSetting -Path $Path -Settings @{ Colour = 'blue' } -WarningVariable w 3>$null
$w
diff --git a/Tests/Unit/Private/Get-IslWindowsReleaseBuild.Tests.ps1 b/Tests/Unit/Private/Get-IslWindowsReleaseBuild.Tests.ps1
index ac95964..53285af 100644
--- a/Tests/Unit/Private/Get-IslWindowsReleaseBuild.Tests.ps1
+++ b/Tests/Unit/Private/Get-IslWindowsReleaseBuild.Tests.ps1
@@ -37,7 +37,8 @@ Describe 'Get-IslWindowsReleaseBuild' -Tag 'Unit', 'Private' {
}
It 'refuses an unknown release' {
- { InModuleScope IntuneScriptLab { Get-IslWindowsReleaseBuild -Release 'Windows12' } } |
+ $failure = { InModuleScope IntuneScriptLab { Get-IslWindowsReleaseBuild -Release 'Windows12' } } |
Should-Throw -ExceptionMessage "*Unknown Windows release 'Windows12'*"
+ $failure.FullyQualifiedErrorId | Should-BeLikeString 'WindowsReleaseUnknown,*'
}
}
diff --git a/Tests/Unit/Public/Assert-PassIntuneAnalysis.Tests.ps1 b/Tests/Unit/Public/Assert-PassIntuneAnalysis.Tests.ps1
index bfd67a0..4da003a 100644
--- a/Tests/Unit/Public/Assert-PassIntuneAnalysis.Tests.ps1
+++ b/Tests/Unit/Public/Assert-PassIntuneAnalysis.Tests.ps1
@@ -40,6 +40,20 @@ Describe 'Assert-PassIntuneAnalysis' -Tag 'Unit', 'Public' {
$message | Should-NotBeLikeString '*Detect-Clean.ps1:*'
}
+ It 'fails for a path that is not there, where it would pass on nothing analyzed' {
+ $missing = Join-Path $TestDrive 'not-there.ps1'
+
+ { $missing | Should-PassIntuneAnalysis } | Should-Throw -FullyQualifiedErrorId 'PathNotFound,*'
+ }
+
+ It 'says that Pester 6.2 is needed when New-ShouldAssertion is not there' {
+ $assertionCommand = { $Name -eq 'New-ShouldAssertion' }
+ Mock Get-Command -ModuleName IntuneScriptLab { $null } -ParameterFilter $assertionCommand
+
+ { $script:Clean | Should-PassIntuneAnalysis } |
+ Should-Throw -FullyQualifiedErrorId 'PesterAssertionNotSupported,*'
+ }
+
It 'limits MinimumSeverity and ScriptType to the analyzer values' {
$command = Get-Command Assert-PassIntuneAnalysis
$command.Parameters['MinimumSeverity'].Attributes.ValidValues |
diff --git a/Tests/Unit/Public/Get-IntuneAnalyzerRulePath.Tests.ps1 b/Tests/Unit/Public/Get-IntuneAnalyzerRulePath.Tests.ps1
index a622622..4034078 100644
--- a/Tests/Unit/Public/Get-IntuneAnalyzerRulePath.Tests.ps1
+++ b/Tests/Unit/Public/Get-IntuneAnalyzerRulePath.Tests.ps1
@@ -29,4 +29,12 @@ Describe 'Get-IntuneAnalyzerRulePath' -Tag 'Unit', 'Public' {
$source | Should-BeLikeString '*IslAssumedContext*'
$source | Should-BeLikeString '*Export-ModuleMember*'
}
+
+ It 'says where the rule module should be when it is not there' {
+ Mock Test-Path -ModuleName IntuneScriptLab { $false }
+
+ $failure = { Get-IntuneAnalyzerRulePath } | Should-Throw
+ $failure.FullyQualifiedErrorId | Should-BeLikeString 'AnalyzerRulesMissing,*'
+ $failure.Exception.Message | Should-BeLikeString 'The PSScriptAnalyzer rule module is missing*'
+ }
}
diff --git a/Tests/Unit/Public/Repair-IntuneScript.Tests.ps1 b/Tests/Unit/Public/Repair-IntuneScript.Tests.ps1
index 414ef99..b2efe3d 100644
--- a/Tests/Unit/Public/Repair-IntuneScript.Tests.ps1
+++ b/Tests/Unit/Public/Repair-IntuneScript.Tests.ps1
@@ -258,4 +258,53 @@ Describe 'Repair-IntuneScript' -Tag 'Unit', 'Public' {
[System.Text.Encoding]::UTF8.GetString($bytes, 3, $bytes.Length - 3) | Should-Be $text
}
}
+
+ Context 'Error Handling' {
+ It 'reports a path that does not exist and still repairs the others' {
+ $body = "if (Test-Path C:\x) { return 'ok' }`r`nexit 1`r`n"
+ $path = New-TestScript 'Remediations\Mixed\Detect.ps1' $body -Bom
+ $missing = Join-Path $TestDrive 'not-there.ps1'
+
+ $output = Repair-IntuneScript -Path $missing, $path -ErrorAction Continue 2>&1
+ $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] })
+ $repairs = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] })
+
+ $errors | Should-BeCollection -Count 1
+ $errors[0].FullyQualifiedErrorId | Should-BeLikeString 'PathNotFound,*'
+ $repairs | Should-BeCollection -Count 1
+ $repairs[0].Path | Should-Be $path
+ $repairs[0].Written | Should-BeTrue
+ }
+
+ It 'reports a script it cannot write and still repairs the next one' {
+ $body = "if (Test-Path C:\x) { return 'ok' }`r`nexit 1`r`n"
+ $locked = New-TestScript 'Remediations\ReadOnly\Detect.ps1' $body -Bom
+ $open = New-TestScript 'Remediations\Writable\Detect.ps1' $body -Bom
+ Set-ItemProperty -LiteralPath $locked -Name IsReadOnly -Value $true
+ try {
+ $output = Repair-IntuneScript -Path $locked, $open -ErrorAction Continue 2>&1
+ } finally {
+ Set-ItemProperty -LiteralPath $locked -Name IsReadOnly -Value $false
+ }
+ $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] })
+ $repairs = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] })
+
+ $errors | Should-BeCollection -Count 1
+ $errors[0].Exception.GetBaseException() | Should-HaveType ([System.UnauthorizedAccessException])
+ $repairs | Should-BeCollection -Count 1
+ $repairs[0].Path | Should-Be $open
+ $repairs[0].Written | Should-BeTrue
+ }
+
+ It 'ends at the script it cannot write when the caller asks it to stop' {
+ $body = "if (Test-Path C:\x) { return 'ok' }`r`nexit 1`r`n"
+ $locked = New-TestScript 'Remediations\ReadOnlyStop\Detect.ps1' $body -Bom
+ Set-ItemProperty -LiteralPath $locked -Name IsReadOnly -Value $true
+ try {
+ { Repair-IntuneScript -Path $locked -ErrorAction Stop } | Should-Throw
+ } finally {
+ Set-ItemProperty -LiteralPath $locked -Name IsReadOnly -Value $false
+ }
+ }
+ }
}
diff --git a/Tests/Unit/Public/Test-IntuneScript.Tests.ps1 b/Tests/Unit/Public/Test-IntuneScript.Tests.ps1
index d2218c7..2de61ba 100644
--- a/Tests/Unit/Public/Test-IntuneScript.Tests.ps1
+++ b/Tests/Unit/Public/Test-IntuneScript.Tests.ps1
@@ -35,8 +35,68 @@ Describe 'Test-IntuneScript' -Tag 'Unit', 'Public' {
@($findings.ScriptPath | Sort-Object -Unique).Count | Should-Be 2
}
- It 'fails on a path that does not exist' {
- { Test-IntuneScript -Path (Join-Path $TestDrive 'missing.ps1') } | Should-Throw
+ It 'reports a path that does not exist and still analyzes the others' {
+ $good = New-TestScript 'mix\Detect-Good.ps1' 'exit 2'
+ $missing = Join-Path $TestDrive 'missing.ps1'
+ $analysisSplat = @{
+ Path = $missing, $good; IncludeRule = 'IslExitCodeIssue'; ErrorAction = 'Continue'
+ }
+
+ $output = Test-IntuneScript @analysisSplat 2>&1
+ $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] })
+ $findings = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] })
+
+ $errors | Should-BeCollection -Count 1
+ $errors[0].FullyQualifiedErrorId | Should-BeLikeString 'PathNotFound,*'
+ $findings.Count | Should-BeGreaterThan 0
+ @($findings.ScriptPath | Sort-Object -Unique) | Should-BeCollection @($good)
+ }
+
+ It 'ends at a path that does not exist when the caller asks it to stop' {
+ { Test-IntuneScript -Path (Join-Path $TestDrive 'missing.ps1') -ErrorAction Stop } |
+ Should-Throw -FullyQualifiedErrorId 'PathNotFound,*'
+ }
+
+ It 'reports a script whose settings file is wrong and still analyzes a script elsewhere' {
+ $broken = New-TestScript 'badsettings\Detect-One.ps1' 'exit 2'
+ $settingsFile = Join-Path (Split-Path $broken -Parent) 'IntuneScriptLab.settings.psd1'
+ Set-Content -LiteralPath $settingsFile -Value "@{ MinimumSeverity = 'Fatal' }" -Encoding ascii
+ $good = New-TestScript 'goodsettings\Detect-Two.ps1' 'exit 2'
+ $analysisSplat = @{ Path = $broken, $good; IncludeRule = 'IslExitCodeIssue'; ErrorAction = 'Continue' }
+
+ $output = Test-IntuneScript @analysisSplat 2>&1
+ $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] })
+ $findings = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] })
+
+ $errors | Should-BeCollection -Count 1
+ $errors[0].FullyQualifiedErrorId | Should-BeLikeString 'SettingsInvalid*'
+ $errors[0].Exception.Message | Should-BeLikeString '*MinimumSeverity must be one of*'
+ @($findings.ScriptPath | Sort-Object -Unique) | Should-BeCollection @($good)
+ }
+
+ It 'ends before any script is analyzed when -Settings itself is wrong' {
+ $one = New-TestScript 'given\Detect-One.ps1' 'exit 2'
+ $two = New-TestScript 'given\Detect-Two.ps1' 'exit 2'
+ Mock Get-IslScriptContext -ModuleName IntuneScriptLab { }
+
+ { Test-IntuneScript -Path $one, $two -Settings @{ MinimumSeverity = 'Fatal' } } |
+ Should-Throw -FullyQualifiedErrorId 'SettingsInvalid*'
+ Should-Invoke Get-IslScriptContext -ModuleName IntuneScriptLab -Times 0 -Exactly
+ }
+
+ It 'leaves a calling script one error for a path that is not there, and the findings of the other' {
+ $good = New-TestScript 'caller\Detect-Good.ps1' 'exit 2'
+ $missing = Join-Path $TestDrive 'caller\missing.ps1'
+
+ $run = Invoke-CallerScript -Statement @(
+ "`$findings = @(Test-IntuneScript -Path '$missing', '$good' -IncludeRule IslExitCodeIssue)"
+ "'analyzed: ' + @(`$findings.ScriptPath | Sort-Object -Unique).Count"
+ )
+
+ $run.ReachedEnd | Should-BeTrue
+ $run.Output | Should-BeCollection @('analyzed: 1')
+ $run.ErrorId | Should-BeCollection -Count 1
+ $run.ErrorId[0] | Should-BeLikeString 'PathNotFound,*'
}
}
diff --git a/Tests/Unit/Public/Test-IntuneWin32Rule.Tests.ps1 b/Tests/Unit/Public/Test-IntuneWin32Rule.Tests.ps1
index 5766165..db81b9a 100644
--- a/Tests/Unit/Public/Test-IntuneWin32Rule.Tests.ps1
+++ b/Tests/Unit/Public/Test-IntuneWin32Rule.Tests.ps1
@@ -53,13 +53,29 @@ Describe 'Test-IntuneWin32Rule' -Tag 'Unit', 'Public' {
Context 'Parameter Validation' {
It 'refuses a comparison without an operator and value' {
+ $expected = @{
+ FullyQualifiedErrorId = 'RuleOperatorMissing,*'; ExceptionMessage = '*-Operator and -Value*'
+ }
{ Test-IntuneWin32Rule -Path $script:Fixtures -FileOrFolderName 'big.bin' -FileOperation SizeInMB } |
- Should-Throw -ExceptionMessage '*-Operator and -Value*'
+ Should-Throw @expected
}
It 'refuses a registry key path without a hive' {
{ Test-IntuneWin32Rule -KeyPath 'SOFTWARE\X' -RegistryOperation Exists } |
- Should-Throw -ExceptionMessage '*hive*'
+ Should-Throw -FullyQualifiedErrorId 'RegistryHiveUnknown,*' -ExceptionMessage '*hive*'
+ }
+
+ It 'ends with the error of a rule it cannot read' {
+ { Test-IntuneWin32Rule -Rule @{ Path = 'C:\x' } } |
+ Should-Throw -FullyQualifiedErrorId 'RuleTypeUnknown,*'
+ $scriptRule = @{ '@odata.type' = '#microsoft.graph.win32LobAppPowerShellScriptRule' }
+ { Test-IntuneWin32Rule -Rule $scriptRule } | Should-Throw -FullyQualifiedErrorId 'RuleIsScript,*'
+ }
+
+ It 'ends with the error of the parameters when a rule in a hashtable leaves a value out' {
+ $sizeRule = @{ Type = 'File'; Path = 'C:\x'; FileOrFolderName = 'big.bin'; OperationType = 'SizeInMB' }
+ { Test-IntuneWin32Rule -Rule $sizeRule } |
+ Should-Throw -FullyQualifiedErrorId 'RuleOperatorMissing,*'
}
It 'limits the operations and operators' {
@@ -319,7 +335,8 @@ Describe 'Test-IntuneWin32Rule' -Tag 'Unit', 'Public' {
Operator = 'Equal'
Value = 'x'
}
- { Test-IntuneWin32Rule @intuneWin32RuleSplat2 } | Should-Throw -ExceptionMessage '*-ValueName*'
+ { Test-IntuneWin32Rule @intuneWin32RuleSplat2 } |
+ Should-Throw -FullyQualifiedErrorId 'RuleValueNameMissing,*' -ExceptionMessage '*-ValueName*'
}
It 'reads the 32-bit view with the switch (W32-REG-VIEW-64, W32-REG-VIEW-32)' -Skip:(
diff --git a/docs/IntuneScriptLab/Assert-PassIntuneAnalysis.md b/docs/IntuneScriptLab/Assert-PassIntuneAnalysis.md
index 1f1470c..596921d 100644
--- a/docs/IntuneScriptLab/Assert-PassIntuneAnalysis.md
+++ b/docs/IntuneScriptLab/Assert-PassIntuneAnalysis.md
@@ -32,6 +32,9 @@ Runs Test-IntuneScript on the path, folder or pipeline of files and fails with t
findings, each with its file, line, severity, rule and message, so the test output is the fix
list. The IslAssumedContext note is never counted.
+A path that is not there, or a script that cannot be analyzed, fails the assertion with the
+error of the analysis.
+
## EXAMPLES
### EXAMPLE 1
diff --git a/docs/IntuneScriptLab/Repair-IntuneScript.md b/docs/IntuneScriptLab/Repair-IntuneScript.md
index 0912d4e..27d5e3f 100644
--- a/docs/IntuneScriptLab/Repair-IntuneScript.md
+++ b/docs/IntuneScriptLab/Repair-IntuneScript.md
@@ -73,6 +73,10 @@ whose text no longer matches the file is skipped with a warning.
The command supports
-WhatIf and -Confirm; nothing is written under -WhatIf.
+A path that is not there, and a script that cannot be analyzed or written, are each reported
+as an error for that one item, and the other scripts are still repaired.
+-ErrorAction Stop ends the command at the first such error.
+
## EXAMPLES
### EXAMPLE 1
diff --git a/docs/IntuneScriptLab/Test-IntuneScript.md b/docs/IntuneScriptLab/Test-IntuneScript.md
index 140ce13..2906dee 100644
--- a/docs/IntuneScriptLab/Test-IntuneScript.md
+++ b/docs/IntuneScriptLab/Test-IntuneScript.md
@@ -66,6 +66,13 @@ And a file named IntuneScriptLab.settings.psd1 in the scripts' folder or any fol
(the nearest wins) carries the exclusions, severity overrides and default type, context,
architecture and signature check a team would otherwise repeat on every call; see -Settings.
+A path that is not there, and a script that cannot be analyzed, as when the settings file
+above it has a value that is not allowed, are each reported as an error for that one item, and
+the other scripts are still analyzed.
+-ErrorAction Stop ends the command at the first such error; a script that gates a build on the
+findings needs it, or it passes on scripts that were never analyzed.
+A -Settings argument that is wrong ends the command before any script is analyzed.
+
## EXAMPLES
### EXAMPLE 1
diff --git a/en-US/IntuneScriptLab-Help.xml b/en-US/IntuneScriptLab-Help.xml
index e76bba1..2d35ca7 100644
--- a/en-US/IntuneScriptLab-Help.xml
+++ b/en-US/IntuneScriptLab-Help.xml
@@ -899,7 +899,10 @@ Validation\Findings.md (documented vs observed Intune behaviour).
Runs Test-IntuneScript on the path, folder or pipeline of files and fails with the list of
findings, each with its file, line, severity, rule and message, so the test output is the fix
-list. The IslAssumedContext note is never counted.
+list. The IslAssumedContext note is never counted.
+
+A path that is not there, or a script that cannot be analyzed, fails the assertion with the
+error of the analysis.
@@ -4508,7 +4511,11 @@ Text edits are applied from the
end of the file backwards so line numbers stay valid, line endings are kept, and an edit
whose text no longer matches the file is skipped with a warning.
The command supports
--WhatIf and -Confirm; nothing is written under -WhatIf.
+-WhatIf and -Confirm; nothing is written under -WhatIf.
+
+A path that is not there, and a script that cannot be analyzed or written, are each reported
+as an error for that one item, and the other scripts are still repaired.
+-ErrorAction Stop ends the command at the first such error.
@@ -5400,7 +5407,14 @@ file, on a line of its own for the next line of code, at the end of a line for t
And a file named IntuneScriptLab.settings.psd1 in the scripts' folder or any folder above them
(the nearest wins) carries the exclusions, severity overrides and default type, context,
-architecture and signature check a team would otherwise repeat on every call; see -Settings.
+architecture and signature check a team would otherwise repeat on every call; see -Settings.
+
+A path that is not there, and a script that cannot be analyzed, as when the settings file
+above it has a value that is not allowed, are each reported as an error for that one item, and
+the other scripts are still analyzed.
+-ErrorAction Stop ends the command at the first such error; a script that gates a build on the
+findings needs it, or it passes on scripts that were never analyzed.
+A -Settings argument that is wrong ends the command before any script is analyzed.