From 102b42ebc70f28f94c2d75b6b4ea0f6942618f73 Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:35:04 -0800 Subject: [PATCH 1/2] refactor(helpers): move the Win32 app flow's helpers out The fifth part of #65. The four functions nested in Invoke-IntuneWin32AppTest are private functions in files of their own, advanced functions with full help and output types. They take as parameters what they read from the command: - Invoke-DetectionPass -> Invoke-IslWin32DetectionPass, with the detection settings as -Detection and the warning list as -Warning - Invoke-ContentCommand -> Invoke-IslWin32ContentCommand, with -Context, -Credential, -TimeoutSeconds and -Warning - Get-Outcome -> Get-IslWin32Outcome, with -ReturnCodes - ConvertTo-RelatedResult -> ConvertTo-IslWin32RelatedResult The command passes the shared values through two splats. The two that launch something end with the error of a step that could not be run, inside a catch of their own, where the nested copies relied on the command's try. A detection pass now carries the type name IntuneScriptLab.Win32DetectionPass. Each new function has a test file of its own; the command's tests are unchanged. Refs #65. --- CHANGELOG.md | 2 +- Private/ConvertTo-IslWin32RelatedResult.ps1 | 85 +++++++++ Private/Get-IslWin32Outcome.ps1 | 45 +++++ Private/Invoke-IslWin32ContentCommand.ps1 | 153 ++++++++++++++++ Private/Invoke-IslWin32DetectionPass.ps1 | 104 +++++++++++ Public/Invoke-IntuneWin32AppTest.ps1 | 164 +++--------------- .../ConvertTo-IslWin32RelatedResult.Tests.ps1 | 52 ++++++ .../Private/Get-IslWin32Outcome.Tests.ps1 | 41 +++++ .../Invoke-IslWin32ContentCommand.Tests.ps1 | 84 +++++++++ .../Invoke-IslWin32DetectionPass.Tests.ps1 | 84 +++++++++ 10 files changed, 670 insertions(+), 144 deletions(-) create mode 100644 Private/ConvertTo-IslWin32RelatedResult.ps1 create mode 100644 Private/Get-IslWin32Outcome.ps1 create mode 100644 Private/Invoke-IslWin32ContentCommand.ps1 create mode 100644 Private/Invoke-IslWin32DetectionPass.ps1 create mode 100644 Tests/Unit/Private/ConvertTo-IslWin32RelatedResult.Tests.ps1 create mode 100644 Tests/Unit/Private/Get-IslWin32Outcome.Tests.ps1 create mode 100644 Tests/Unit/Private/Invoke-IslWin32ContentCommand.Tests.ps1 create mode 100644 Tests/Unit/Private/Invoke-IslWin32DetectionPass.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 05d529c..722913c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,7 +43,7 @@ entries are carried over from the manifest's release notes. ### Changed - The helper functions nested in `Test-IntuneScript`, `Test-IntuneWin32Requirement`, - `Test-IntuneAssignmentFilter`, `Export-IntuneFindingSarif`, `Export-IntuneAgentDiagnostic`, + `Invoke-IntuneWin32AppTest`, `Test-IntuneAssignmentFilter`, `Export-IntuneFindingSarif`, `Export-IntuneAgentDiagnostic`, `Get-IslSetting`, `Get-IslAgentLogEvent`, `Invoke-IslGraphRequest` and three analyzer rules (`IslInteractiveCall`, `IslExitCodeIssue`, `IslModuleDependency`) are private functions of their own, each an advanced function with help and tests (#65). Nothing changes for a caller, except that the error diff --git a/Private/ConvertTo-IslWin32RelatedResult.ps1 b/Private/ConvertTo-IslWin32RelatedResult.ps1 new file mode 100644 index 0000000..7073715 --- /dev/null +++ b/Private/ConvertTo-IslWin32RelatedResult.ps1 @@ -0,0 +1,85 @@ +function ConvertTo-IslWin32RelatedResult { + <# + .SYNOPSIS + Builds the result of a dependency or a superseded app in a Win32 app flow. + + .DESCRIPTION + For Invoke-IntuneWin32AppTest, which lists these under Dependencies and Superseded. The + detections are given as the passes Invoke-IslWin32DetectionPass returns, and the result + carries their script results and rules; a pass that did not happen leaves its fields empty. + + .PARAMETER Name + The name of the related app. + + .PARAMETER Relationship + How it relates to the app, such as "dependency (autoInstall)" or "supersedence (replace)". + + .PARAMETER Status + What the flow came to for it, such as Installed after install or Uninstalled. + + .PARAMETER Pre + The detection pass before anything ran. + + .PARAMETER Install + The install run, when there was one. + + .PARAMETER Uninstall + The uninstall run, when there was one. + + .PARAMETER Post + The detection pass after the install or uninstall, when there was one. + + .EXAMPLE + $relatedSplat = @{ Name = 'Runtime'; Relationship = 'dependency (autoInstall)'; Status = 'Installed' } + ConvertTo-IslWin32RelatedResult @relatedSplat -Pre $childPre + + A dependency that was already installed. + + .INPUTS + None. + + .OUTPUTS + IntuneScriptLab.Win32RelatedResult. Name, Relationship, Status, PreDetection, PreRules, + Install, Uninstall, PostDetection and PostRules. + #> + [CmdletBinding()] + [OutputType('IntuneScriptLab.Win32RelatedResult')] + param( + [Parameter(Mandatory)] + [string]$Name, + + [Parameter(Mandatory)] + [string]$Relationship, + + [Parameter(Mandatory)] + [string]$Status, + + [Parameter(Mandatory)] + [psobject]$Pre, + + [Parameter()] + [AllowNull()] + [psobject]$Install, + + [Parameter()] + [AllowNull()] + [psobject]$Uninstall, + + [Parameter()] + [AllowNull()] + [psobject]$Post + ) + + [pscustomobject]@{ + PSTypeName = 'IntuneScriptLab.Win32RelatedResult' + Name = $Name + Relationship = $Relationship + Status = $Status + PreDetection = $Pre.Script + PreRules = $Pre.Rules + Install = $Install + Uninstall = $Uninstall + PostDetection = if ($Post) { $Post.Script } else { $null } + PostRules = if ($Post) { $Post.Rules } else { @() } + } +} diff --git a/Private/Get-IslWin32Outcome.ps1 b/Private/Get-IslWin32Outcome.ps1 new file mode 100644 index 0000000..87f62e2 --- /dev/null +++ b/Private/Get-IslWin32Outcome.ps1 @@ -0,0 +1,45 @@ +function Get-IslWin32Outcome { + <# + .SYNOPSIS + Gets what the agent makes of the exit code of a Win32 app's install or uninstall. + + .DESCRIPTION + For Invoke-IntuneWin32AppTest. A run that was ended at its timeout is timedOut. Otherwise the + exit code is looked up in the app's return codes, such as 0 = success, 3010 = softReboot or + 1618 = retry, and a code that is not there is failed. + + .PARAMETER Run + The run, with TimedOut and ExitCode. + + .PARAMETER ReturnCodes + The app's return codes: exit code to success, softReboot, hardReboot, retry or failed. + + .EXAMPLE + Get-IslWin32Outcome -Run $execution -ReturnCodes @{ 0 = 'success'; 3010 = 'softReboot' } + + softReboot for a run that exited 3010. + + .INPUTS + None. + + .OUTPUTS + System.String. timedOut, failed, or the value of the exit code in the return codes. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [psobject]$Run, + + [Parameter(Mandatory)] + [hashtable]$ReturnCodes + ) + + if ($Run.TimedOut) { + return 'timedOut' + } + if ($null -ne $Run.ExitCode -and $ReturnCodes.ContainsKey($Run.ExitCode)) { + return "$($ReturnCodes[$Run.ExitCode])" + } + 'failed' +} diff --git a/Private/Invoke-IslWin32ContentCommand.ps1 b/Private/Invoke-IslWin32ContentCommand.ps1 new file mode 100644 index 0000000..3aa4e1e --- /dev/null +++ b/Private/Invoke-IslWin32ContentCommand.ps1 @@ -0,0 +1,153 @@ +function Invoke-IslWin32ContentCommand { + <# + .SYNOPSIS + Runs a Win32 app's install or uninstall command line from a copy of its content folder. + + .DESCRIPTION + For Invoke-IntuneWin32AppTest. The content is copied to a run folder, the command line runs + there through the 32-bit cmd.exe, as the agent's own 32-bit process runs it, and the run + folder is removed afterwards. A run as another account gets its folder under ProgramData, + which that account can reach, with Modify access granted to it. + + A command line that starts powershell.exe, or that names a batch file in the content which + does, runs the 32-bit host, where HKLM:\SOFTWARE and Program Files are redirected; that adds + a warning to the list it is given. + + A copy or a launch that fails ends the function with its error. + + .PARAMETER Phase + install or uninstall, for the result and the warnings. + + .PARAMETER Content + The content folder of the app. + + .PARAMETER CommandLine + The install or uninstall command line, as the app defines it. + + .PARAMETER Context + User or System. + + .PARAMETER Credential + The account to run as, with Context User. Left out, the run is the current user's. + + .PARAMETER TimeoutSeconds + How long the command line may run before it is ended. + + .PARAMETER Warning + The list the warnings of the run are collected in. + + .EXAMPLE + $contentSplat = @{ Context = 'User'; TimeoutSeconds = 600; Warning = $warnings } + Invoke-IslWin32ContentCommand -Phase 'install' -Content $ContentPath -CommandLine 'setup.exe /q' @contentSplat + + Runs the install command line as the current user. + + .INPUTS + None. + + .OUTPUTS + IntuneScriptLab.RunResult. Phase, Command, Context, ExitCode, TimedOut, StdOut, StdErr and + Duration. + #> + [CmdletBinding()] + [OutputType('IntuneScriptLab.RunResult')] + param( + [Parameter(Mandatory)] + [string]$Phase, + + [Parameter(Mandatory)] + [string]$Content, + + [Parameter(Mandatory)] + [string]$CommandLine, + + [Parameter(Mandatory)] + [ValidateSet('User', 'System')] + [string]$Context, + + [Parameter()] + [System.Management.Automation.PSCredential] + [System.Management.Automation.Credential()] + $Credential = [System.Management.Automation.PSCredential]::Empty, + + [Parameter(Mandatory)] + [ValidateRange(1, 86400)] + [int]$TimeoutSeconds, + + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [System.Collections.Generic.List[string]]$Warning + ) + + $asAccount = $Credential -ne [System.Management.Automation.PSCredential]::Empty + try { + $source = (Resolve-Path -LiteralPath $Content -ErrorAction Stop).ProviderPath + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } + $hostPattern = '(?i)(^|[\s"])powershell(\.exe)?([\s"]|$)' + if ($CommandLine -match $hostPattern) { + $Warning.Add("powershell.exe in the $Phase command runs the 32-bit host (the agent is a 32-bit " + + 'process); HKLM:\SOFTWARE and Program Files are redirected there') + } else { + # The same host hides inside a batch file the command line names: install.cmd calling + # powershell.exe runs it 32-bit too, from the agent's 32-bit cmd.exe, without the + # command line showing it + $first = if ($CommandLine -match '^\s*"([^"]+)"') { $Matches[1] } + else { ($CommandLine.Trim() -split '\s+', 2)[0] } + $batch = if ($first -match '(?i)\.(cmd|bat)$') { Join-Path -Path $source -ChildPath $first } + else { $null } + if ($batch -and (Test-Path -LiteralPath $batch -PathType Leaf)) { + $hit = Select-String -LiteralPath $batch -Pattern $hostPattern | Select-Object -First 1 + if ($hit) { + $Warning.Add("powershell.exe in $first (line $($hit.LineNumber)), which the $Phase " + + 'command runs through the 32-bit cmd.exe, is the 32-bit host (the agent is a 32-bit ' + + 'process); HKLM:\SOFTWARE and Program Files are redirected there') + } + } + } + $runId = [guid]::NewGuid().ToString('N') + # Another account cannot reach the caller's temp folder; its copy lives under ProgramData + $cache = if ($asAccount) { + Join-Path -Path $env:ProgramData -ChildPath "IntuneScriptLab\Runs\$runId" + } else { + Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "IntuneScriptLab\$runId" + } + $copy = Join-Path -Path $cache -ChildPath 'content' + try { + $null = New-Item -ItemType Directory -Path $copy -Force -ErrorAction Stop @script:IslInternal + $contentItems = Join-Path -Path $source -ChildPath '*' + $copySplat = @{ Path = $contentItems; Destination = $copy; Recurse = $true; Force = $true } + Copy-Item @copySplat -ErrorAction Stop @script:IslInternal + if ($asAccount) { Grant-IslFolderAccess -Path $cache -Account $Credential.UserName } + $cmdFolder = if ([Environment]::Is64BitOperatingSystem) { 'SysWOW64' } else { 'System32' } + $cmd = Join-Path -Path (Join-Path -Path $env:WINDIR -ChildPath $cmdFolder) -ChildPath 'cmd.exe' + $processSplat = @{ + FilePath = $cmd + Arguments = "/C `"$CommandLine`"" + WorkingDirectory = $copy + WorkFolder = $cache + Context = $Context + TimeoutSeconds = $TimeoutSeconds + LauncherBitness = 'x86' + } + if ($asAccount) { $processSplat.Credential = $Credential } + $run = Invoke-IslProcess @processSplat + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } finally { + Remove-Item -LiteralPath $cache -Recurse -Force -ErrorAction SilentlyContinue @script:IslInternal + } + + [pscustomobject]@{ + PSTypeName = 'IntuneScriptLab.RunResult' + Phase = $Phase + Command = $CommandLine + Context = $Context + ExitCode = $run.ExitCode + TimedOut = $run.TimedOut + StdOut = $run.StdOut + StdErr = $run.StdErr + Duration = $run.Duration + } +} diff --git a/Private/Invoke-IslWin32DetectionPass.ps1 b/Private/Invoke-IslWin32DetectionPass.ps1 new file mode 100644 index 0000000..fa88c91 --- /dev/null +++ b/Private/Invoke-IslWin32DetectionPass.ps1 @@ -0,0 +1,104 @@ +function Invoke-IslWin32DetectionPass { + <# + .SYNOPSIS + Runs one detection pass of a Win32 app: its detection script, if any, and each of its rules. + + .DESCRIPTION + For Invoke-IntuneWin32AppTest, for the app itself or for a dependency or a superseded app. + The app counts as detected only when the script and every rule say installed + (W32-MULTI-ONEFALSE, W32-MULTI-BOTHTRUE). Each rule that is not met adds a warning to the + list it is given. + + A script that cannot be run, or a rule that cannot be read, ends the function with its + error. Invoke-IntuneDetectionTest reports a script it cannot run without ending, so it is + called with -ErrorAction Stop: with nothing returned, the app would read as detected. + + .PARAMETER Phase + Pre or Post, for the warnings. + + .PARAMETER Path + The detection script. Left out or empty, the pass has no script. + + .PARAMETER Rule + The detection rules, as hashtables for Test-IntuneWin32Rule -Rule. + + .PARAMETER Label + Text that names the app in the warnings, such as " for dependency Runtime"; empty for the + app under test. + + .PARAMETER Detection + The parameters of Invoke-IntuneDetectionTest that every pass shares: Architecture, Context, + TimeoutSeconds, EnforceSignatureCheck and, for another account, Credential. + + .PARAMETER Warning + The list the warnings of the run are collected in. + + .EXAMPLE + $passSplat = @{ Detection = $detectionSplat; Warning = $warnings } + $pre = Invoke-IslWin32DetectionPass -Phase 'Pre' -Path $DetectionPath -Rule $DetectionRule @passSplat + + The detection before the install. + + .INPUTS + None. + + .OUTPUTS + IntuneScriptLab.Win32DetectionPass. Detected, TimedOut, Script, Rules and Reason. + #> + [CmdletBinding()] + [OutputType('IntuneScriptLab.Win32DetectionPass')] + param( + [Parameter(Mandatory)] + [ValidateSet('Pre', 'Post')] + [string]$Phase, + + [Parameter()] + [string]$Path, + + [Parameter()] + [AllowNull()] + [AllowEmptyCollection()] + [hashtable[]]$Rule, + + [Parameter()] + [string]$Label = '', + + [Parameter(Mandatory)] + [hashtable]$Detection, + + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [System.Collections.Generic.List[string]]$Warning + ) + + $scriptResult = $null + try { + if ($Path) { + $detectionRun = @{ Path = $Path; ErrorAction = 'Stop' } + $scriptResult = Invoke-IntuneDetectionTest @detectionRun @Detection @script:IslInternal + } + $rules = @(foreach ($entry in @($Rule | Where-Object { $_ })) { + Test-IntuneWin32Rule -Rule $entry -RuleType Detection -ErrorAction Stop + }) + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } + + $unmet = @($rules | Where-Object { -not $_.Met }) + $detected = ($null -eq $scriptResult -or $scriptResult.Detected) -and $unmet.Count -eq 0 + $timedOut = $null -ne $scriptResult -and $scriptResult.TimedOut + foreach ($miss in $unmet) { + $Warning.Add("$Phase detection rule not met$Label ($($miss.Kind) $($miss.Operation)): " + $miss.Reason) + } + $reason = if ($scriptResult -and -not $scriptResult.Detected) { $scriptResult.Reason } + elseif ($unmet.Count) { ($unmet | ForEach-Object { $_.Reason }) -join '; ' } + else { 'Script and rules all report installed' } + [pscustomobject]@{ + PSTypeName = 'IntuneScriptLab.Win32DetectionPass' + Detected = $detected + TimedOut = $timedOut + Script = $scriptResult + Rules = $rules + Reason = $reason + } +} diff --git a/Public/Invoke-IntuneWin32AppTest.ps1 b/Public/Invoke-IntuneWin32AppTest.ps1 index 9547972..ffe95d0 100644 --- a/Public/Invoke-IntuneWin32AppTest.ps1 +++ b/Public/Invoke-IntuneWin32AppTest.ps1 @@ -143,138 +143,14 @@ function Invoke-IntuneWin32AppTest { elseif ($env:USERDOMAIN) { "$env:USERDOMAIN\$env:USERNAME" } else { [Environment]::UserName } - # One detection pass for this app or a related one: the script (if any) and every rule; all of - # them must say installed (W32-MULTI-ONEFALSE, W32-MULTI-BOTHTRUE). A script that cannot be run - # or a rule that cannot be read ends the flow, through the try around every call of this - # function. The detection reports such a script without ending, so it is called with - # -ErrorAction Stop: with nothing returned, the app would read as detected below - function Invoke-DetectionPass { - param([string]$Phase, [string]$Path, [hashtable[]]$Rule, [string]$Label) - $script = $null - if ($Path) { - $detectionRun = @{ Path = $Path; ErrorAction = 'Stop' } - $script = Invoke-IntuneDetectionTest @detectionRun @detectionSplat @script:IslInternal - } - $rules = @(foreach ($entry in $Rule) { - Test-IntuneWin32Rule -Rule $entry -RuleType Detection -ErrorAction Stop - }) - $unmet = @($rules | Where-Object { -not $_.Met }) - $detected = ($null -eq $script -or $script.Detected) -and $unmet.Count -eq 0 - $timedOut = $null -ne $script -and $script.TimedOut - foreach ($miss in $unmet) { - $warnings.Add("$Phase detection rule not met$Label ($($miss.Kind) $($miss.Operation)): " + - $miss.Reason) - } - [pscustomobject]@{ - Detected = $detected - TimedOut = $timedOut - Script = $script - Rules = $rules - Reason = if ($script -and -not $script.Detected) { $script.Reason } - elseif ($unmet.Count) { ($unmet | ForEach-Object { $_.Reason }) -join '; ' } - else { 'Script and rules all report installed' } - } - } - - # Runs an install or uninstall command line from a copy of a content folder through the 32-bit - # cmd.exe, as the agent's own 32-bit process does. A copy or a launch that fails ends the flow, - # through the try around every call of this function - function Invoke-ContentCommand { - param([string]$Phase, [string]$Content, [string]$CommandLine) - $source = (Resolve-Path -LiteralPath $Content -ErrorAction Stop).ProviderPath - $hostPattern = '(?i)(^|[\s"])powershell(\.exe)?([\s"]|$)' - if ($CommandLine -match $hostPattern) { - $warnings.Add("powershell.exe in the $Phase command runs the 32-bit host (the agent is a 32-bit " + - 'process); HKLM:\SOFTWARE and Program Files are redirected there') - } - else { - # The same host hides inside a batch file the command line names: install.cmd calling - # powershell.exe runs it 32-bit too, from the agent's 32-bit cmd.exe, without the - # command line showing it - $first = if ($CommandLine -match '^\s*"([^"]+)"') { $Matches[1] } - else { ($CommandLine.Trim() -split '\s+', 2)[0] } - $batch = if ($first -match '(?i)\.(cmd|bat)$') { Join-Path -Path $source -ChildPath $first } - else { $null } - if ($batch -and (Test-Path -LiteralPath $batch -PathType Leaf)) { - $hit = Select-String -LiteralPath $batch -Pattern $hostPattern | Select-Object -First 1 - if ($hit) { - $warnings.Add("powershell.exe in $first (line $($hit.LineNumber)), which the $Phase " + - 'command runs through the 32-bit cmd.exe, is the 32-bit host (the agent is a 32-bit ' + - 'process); HKLM:\SOFTWARE and Program Files are redirected there') - } - } - } - $runId = [guid]::NewGuid().ToString('N') - # Another account cannot reach the caller's temp folder; its copy lives under ProgramData - $cache = if ($Credential) { - Join-Path -Path $env:ProgramData -ChildPath "IntuneScriptLab\Runs\$runId" - } - else { - Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "IntuneScriptLab\$runId" - } - $copy = Join-Path -Path $cache -ChildPath 'content' - try { - $null = New-Item -ItemType Directory -Path $copy -Force -ErrorAction Stop @script:IslInternal - $contentItems = Join-Path -Path $source -ChildPath '*' - $copySplat = @{ Path = $contentItems; Destination = $copy; Recurse = $true; Force = $true } - Copy-Item @copySplat -ErrorAction Stop @script:IslInternal - if ($Credential) { Grant-IslFolderAccess -Path $cache -Account $Credential.UserName } - $cmdFolder = if ([Environment]::Is64BitOperatingSystem) { 'SysWOW64' } else { 'System32' } - $cmd = Join-Path -Path (Join-Path -Path $env:WINDIR -ChildPath $cmdFolder) -ChildPath 'cmd.exe' - $processSplat = @{ - FilePath = $cmd - Arguments = "/C `"$CommandLine`"" - WorkingDirectory = $copy - WorkFolder = $cache - Context = $Context - TimeoutSeconds = $InstallTimeoutSeconds - LauncherBitness = 'x86' - } - if ($Credential) { $processSplat.Credential = $Credential } - $run = Invoke-IslProcess @processSplat - } - finally { - Remove-Item -LiteralPath $cache -Recurse -Force -ErrorAction SilentlyContinue @script:IslInternal - } - [pscustomobject]@{ - PSTypeName = 'IntuneScriptLab.RunResult' - Phase = $Phase - Command = $CommandLine - Context = $Context - ExitCode = $run.ExitCode - TimedOut = $run.TimedOut - StdOut = $run.StdOut - StdErr = $run.StdErr - Duration = $run.Duration - } - } - - function Get-Outcome { - param($Run) - if ($Run.TimedOut) { return 'timedOut' } - if ($ReturnCodes.ContainsKey($Run.ExitCode)) { $ReturnCodes[$Run.ExitCode] } else { 'failed' } - } - - function ConvertTo-RelatedResult { - param([string]$Name, [string]$Relationship, [string]$Status, $Pre, $Install, $Uninstall, $Post) - [pscustomobject]@{ - PSTypeName = 'IntuneScriptLab.Win32RelatedResult' - Name = $Name - Relationship = $Relationship - Status = $Status - PreDetection = $Pre.Script - PreRules = $Pre.Rules - Install = $Install - Uninstall = $Uninstall - PostDetection = if ($Post) { $Post.Script } else { $null } - PostRules = if ($Post) { $Post.Rules } else { @() } - } - } + # What every detection pass and every install or uninstall of the flow share + $passSplat = @{ Detection = $detectionSplat; Warning = $warnings } + $contentSplat = @{ Context = $Context; TimeoutSeconds = $InstallTimeoutSeconds; Warning = $warnings } + if ($Credential) { $contentSplat.Credential = $Credential } - # The whole flow is one transaction. A step that could not be run ends it with that step's - # error; the two nested functions above have no catch of their own and depend on this one + # The whole flow is one transaction. A step that could not be run ends it with that step's error try { - $pre = Invoke-DetectionPass -Phase 'Pre' -Path $DetectionPath -Rule $DetectionRule -Label '' + $pre = Invoke-IslWin32DetectionPass -Phase 'Pre' -Path $DetectionPath -Rule $DetectionRule @passSplat $execution = $null $post = $null $dependencies = [System.Collections.Generic.List[object]]::new() @@ -298,7 +174,7 @@ function Invoke-IntuneWin32AppTest { Rule = $dependency['DetectionRule'] Label = " for dependency $name" } - $childPre = Invoke-DetectionPass -Phase 'Pre' @detect + $childPre = Invoke-IslWin32DetectionPass -Phase 'Pre' @detect @passSplat $childInstall = $null $childPost = $null $childStatus = if ($childPre.TimedOut) { 'TimedOut' } @@ -313,13 +189,13 @@ function Invoke-IntuneWin32AppTest { Content = $dependency['ContentPath'] CommandLine = $dependency['InstallCommand'] } - $childInstall = Invoke-ContentCommand @childRun - switch (Get-Outcome -Run $childInstall) { + $childInstall = Invoke-IslWin32ContentCommand @childRun @contentSplat + switch (Get-IslWin32Outcome -Run $childInstall -ReturnCodes $ReturnCodes) { 'timedOut' { 'TimedOut' } 'retry' { 'Retry' } 'failed' { "Install failed (exit $($childInstall.ExitCode))" } default { - $childPost = Invoke-DetectionPass -Phase 'Post' @detect + $childPost = Invoke-IslWin32DetectionPass -Phase 'Post' @detect @passSplat if ($childPost.Detected) { 'Installed after install' } else { 'Not detected after install' } } @@ -329,7 +205,7 @@ function Invoke-IntuneWin32AppTest { Name = $name; Relationship = "dependency ($type)"; Status = $childStatus Pre = $childPre; Install = $childInstall; Uninstall = $null; Post = $childPost } - $dependencies.Add((ConvertTo-RelatedResult @relatedSplat)) + $dependencies.Add((ConvertTo-IslWin32RelatedResult @relatedSplat)) if ($childStatus -notin 'Installed', 'Installed after install') { $status = 'Not installed (dependency)' $warnings.Add("Dependency $name ($type): $childStatus. The agent does not run this app's " + @@ -352,7 +228,7 @@ function Invoke-IntuneWin32AppTest { Rule = $old['DetectionRule'] Label = " for superseded app $name" } - $oldPre = Invoke-DetectionPass -Phase 'Pre' @detect + $oldPre = Invoke-IslWin32DetectionPass -Phase 'Pre' @detect @passSplat $oldUninstall = $null $oldPost = $null $oldStatus = if ($oldPre.TimedOut) { 'TimedOut' } @@ -367,13 +243,13 @@ function Invoke-IntuneWin32AppTest { Content = $old['ContentPath'] CommandLine = $old['UninstallCommand'] } - $oldUninstall = Invoke-ContentCommand @oldRun - switch (Get-Outcome -Run $oldUninstall) { + $oldUninstall = Invoke-IslWin32ContentCommand @oldRun @contentSplat + switch (Get-IslWin32Outcome -Run $oldUninstall -ReturnCodes $ReturnCodes) { 'timedOut' { 'TimedOut' } 'retry' { 'Retry' } 'failed' { "Uninstall failed (exit $($oldUninstall.ExitCode))" } default { - $oldPost = Invoke-DetectionPass -Phase 'Post' @detect + $oldPost = Invoke-IslWin32DetectionPass -Phase 'Post' @detect @passSplat if ($oldPost.Detected) { 'Still detected after uninstall' } else { 'Uninstalled' } } } @@ -382,7 +258,7 @@ function Invoke-IntuneWin32AppTest { Name = $name; Relationship = "supersedence ($type)"; Status = $oldStatus Pre = $oldPre; Install = $null; Uninstall = $oldUninstall; Post = $oldPost } - $superseded.Add((ConvertTo-RelatedResult @relatedSplat)) + $superseded.Add((ConvertTo-IslWin32RelatedResult @relatedSplat)) if ($type -eq 'replace' -and $oldStatus -notin 'Uninstalled', 'Not installed') { $warnings.Add("Superseded app $name (replace): $oldStatus. The agent removes a replace " + 'target before it installs the new app (W32-SUP-OLD-B), so the old app would still ' + @@ -392,8 +268,9 @@ function Invoke-IntuneWin32AppTest { } if (-not $status) { - $execution = Invoke-ContentCommand -Phase $Intent.ToLower() -Content $ContentPath -CommandLine $command - $outcome = Get-Outcome -Run $execution + $appRun = @{ Phase = $Intent.ToLower(); Content = $ContentPath; CommandLine = $command } + $execution = Invoke-IslWin32ContentCommand @appRun @contentSplat + $outcome = Get-IslWin32Outcome -Run $execution -ReturnCodes $ReturnCodes switch ($outcome) { 'timedOut' { $status = 'TimedOut' } 'retry' { $status = 'Retry' } @@ -403,7 +280,8 @@ function Invoke-IntuneWin32AppTest { $warnings.Add("$Intent returned $($execution.ExitCode): Intune records a $outcome " + 'as pending') } - $post = Invoke-DetectionPass -Phase 'Post' -Path $DetectionPath -Rule $DetectionRule -Label '' + $appDetection = @{ Path = $DetectionPath; Rule = $DetectionRule } + $post = Invoke-IslWin32DetectionPass -Phase 'Post' @appDetection @passSplat if ($post.TimedOut) { $status = 'TimedOut' } elseif ($Intent -eq 'Install') { $status = if ($post.Detected) { 'Installed after install' } diff --git a/Tests/Unit/Private/ConvertTo-IslWin32RelatedResult.Tests.ps1 b/Tests/Unit/Private/ConvertTo-IslWin32RelatedResult.Tests.ps1 new file mode 100644 index 0000000..3462566 --- /dev/null +++ b/Tests/Unit/Private/ConvertTo-IslWin32RelatedResult.Tests.ps1 @@ -0,0 +1,52 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The result of a dependency or a superseded app in a Win32 app flow. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + function script:ConvertTo-Related { + param([hashtable]$Parameters) + InModuleScope IntuneScriptLab -Parameters @{ Parameters = $Parameters } { + ConvertTo-IslWin32RelatedResult @Parameters + } + } + $script:Pre = [pscustomobject]@{ Script = 'pre-script'; Rules = @('pre-rule') } + $script:Post = [pscustomobject]@{ Script = 'post-script'; Rules = @('post-rule') } +} + +Describe 'ConvertTo-IslWin32RelatedResult' -Tag 'Unit', 'Private' { + + It 'carries the name, the status, the runs and what each detection pass found' { + $result = ConvertTo-Related @{ + Name = 'Runtime'; Relationship = 'dependency (autoInstall)'; Status = 'Installed after install' + Pre = $script:Pre; Install = 'install-run'; Post = $script:Post + } + + $result | Should-HaveType 'IntuneScriptLab.Win32RelatedResult' + $result.Name | Should-Be 'Runtime' + $result.Relationship | Should-Be 'dependency (autoInstall)' + $result.Status | Should-Be 'Installed after install' + $result.PreDetection | Should-Be 'pre-script' + $result.PreRules | Should-BeCollection @('pre-rule') + $result.Install | Should-Be 'install-run' + $result.Uninstall | Should-BeNull + $result.PostDetection | Should-Be 'post-script' + $result.PostRules | Should-BeCollection @('post-rule') + } + + It 'leaves the post-detection empty when there was none' { + $result = ConvertTo-Related @{ + Name = 'Old'; Relationship = 'supersedence (update)'; Status = 'Installed (left in place by update)' + Pre = $script:Pre + } + + $result.PostDetection | Should-BeNull + @($result.PostRules) | Should-BeCollection @() + } +} diff --git a/Tests/Unit/Private/Get-IslWin32Outcome.Tests.ps1 b/Tests/Unit/Private/Get-IslWin32Outcome.Tests.ps1 new file mode 100644 index 0000000..dee936d --- /dev/null +++ b/Tests/Unit/Private/Get-IslWin32Outcome.Tests.ps1 @@ -0,0 +1,41 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + What the agent makes of the exit code of a Win32 install or uninstall. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + $script:Codes = @{ 0 = 'success'; 1707 = 'success'; 3010 = 'softReboot'; 1641 = 'hardReboot'; 1618 = 'retry' } + + function script:Get-Outcome { + param($Run) + InModuleScope IntuneScriptLab -Parameters @{ Run = $Run; Codes = $script:Codes } { + Get-IslWin32Outcome -Run $Run -ReturnCodes $Codes + } + } +} + +Describe 'Get-IslWin32Outcome' -Tag 'Unit', 'Private' { + + It 'gives for exit code ' -ForEach @( + @{ ExitCode = 0; Expected = 'success' } + @{ ExitCode = 3010; Expected = 'softReboot' } + @{ ExitCode = 1641; Expected = 'hardReboot' } + @{ ExitCode = 1618; Expected = 'retry' } + @{ ExitCode = 1603; Expected = 'failed' } + ) { + Get-Outcome -Run ([pscustomobject]@{ TimedOut = $false; ExitCode = $ExitCode }) | Should-Be $Expected + } + + It 'gives timedOut for a run that was ended, whatever its exit code' { + Get-Outcome -Run ([pscustomobject]@{ TimedOut = $true; ExitCode = 0 }) | Should-Be 'timedOut' + } + + It 'gives failed for a run without an exit code' { + Get-Outcome -Run ([pscustomobject]@{ TimedOut = $false; ExitCode = $null }) | Should-Be 'failed' + } +} diff --git a/Tests/Unit/Private/Invoke-IslWin32ContentCommand.Tests.ps1 b/Tests/Unit/Private/Invoke-IslWin32ContentCommand.Tests.ps1 new file mode 100644 index 0000000..68e20bd --- /dev/null +++ b/Tests/Unit/Private/Invoke-IslWin32ContentCommand.Tests.ps1 @@ -0,0 +1,84 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + A Win32 install or uninstall command line run from a copy of the content, with the process + launch mocked. Real launches are covered in Tests\Integration\Win32AppWorkflow.Tests.ps1. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + function script:Invoke-Content { + param([hashtable]$Parameters) + InModuleScope IntuneScriptLab -Parameters @{ Parameters = $Parameters } { + Invoke-IslWin32ContentCommand @Parameters + } + } +} + +Describe 'Invoke-IslWin32ContentCommand' -Tag 'Unit', 'Private' { + + BeforeEach { + $script:Content = Join-Path $TestDrive "content-$([guid]::NewGuid().ToString('N'))" + $null = New-Item -ItemType Directory -Path $script:Content + Set-Content -LiteralPath (Join-Path $script:Content 'setup.exe') -Value 'binary' -Encoding ascii + $script:Warnings = [System.Collections.Generic.List[string]]::new() + $script:Seen = @{} + # Records the launch and whether the copy was there while it ran + Mock Invoke-IslProcess -ModuleName IntuneScriptLab { + $script:Seen['Arguments'] = $Arguments + $script:Seen['Bitness'] = $LauncherBitness + $script:Seen['WorkFolder'] = $WorkFolder + $script:Seen['Copied'] = Test-Path -LiteralPath (Join-Path $WorkingDirectory 'setup.exe') + [pscustomobject]@{ + ExitCode = 3010; TimedOut = $false; StdOut = 'done'; StdErr = ''; Duration = [timespan]::Zero + } + } + $script:Base = @{ Context = 'User'; TimeoutSeconds = 600; Warning = $script:Warnings } + } + + It 'runs the command line through the 32-bit cmd.exe on a copy, and removes the copy afterwards' { + $run = @{ Phase = 'install'; Content = $script:Content; CommandLine = 'setup.exe /q' } + $result = Invoke-Content ($run + $script:Base) + + $result | Should-HaveType 'IntuneScriptLab.RunResult' + $result.Phase | Should-Be 'install' + $result.Command | Should-Be 'setup.exe /q' + $result.ExitCode | Should-Be 3010 + $script:Seen['Arguments'] | Should-Be '/C "setup.exe /q"' + $script:Seen['Bitness'] | Should-Be 'x86' + $script:Seen['Copied'] | Should-BeTrue + Test-Path -LiteralPath $script:Seen['WorkFolder'] | Should-BeFalse + $script:Warnings | Should-BeCollection @() + } + + It 'warns about powershell.exe in the command line' { + $line = 'powershell.exe -ExecutionPolicy Bypass -File install.ps1' + $run = @{ Phase = 'install'; Content = $script:Content; CommandLine = $line } + $null = Invoke-Content ($run + $script:Base) + + $script:Warnings | Should-BeCollection -Count 1 + $script:Warnings[0] | Should-BeLikeString 'powershell.exe in the install command runs the 32-bit host*' + } + + It 'warns about powershell.exe in a batch file that the command line names' { + Set-Content -LiteralPath (Join-Path $script:Content 'install.cmd') -Encoding ascii -Value @( + '@echo off', 'powershell.exe -File install.ps1') + $run = @{ Phase = 'install'; Content = $script:Content; CommandLine = 'install.cmd' } + $null = Invoke-Content ($run + $script:Base) + + $script:Warnings | Should-BeCollection -Count 1 + $script:Warnings[0] | Should-BeLikeString 'powershell.exe in install.cmd (line 2)*' + } + + It 'ends without starting anything when the content folder is not there' { + $missing = Join-Path $TestDrive 'no-content' + + { Invoke-Content (@{ Phase = 'install'; Content = $missing; CommandLine = 'setup.exe' } + $script:Base) } | + Should-Throw -FullyQualifiedErrorId 'PathNotFound,*' + Should-Invoke Invoke-IslProcess -ModuleName IntuneScriptLab -Times 0 -Exactly + } +} diff --git a/Tests/Unit/Private/Invoke-IslWin32DetectionPass.Tests.ps1 b/Tests/Unit/Private/Invoke-IslWin32DetectionPass.Tests.ps1 new file mode 100644 index 0000000..e69975e --- /dev/null +++ b/Tests/Unit/Private/Invoke-IslWin32DetectionPass.Tests.ps1 @@ -0,0 +1,84 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + One detection pass of a Win32 app, with the detection script and the rules mocked. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + function script:Invoke-Pass { + param([hashtable]$Parameters) + InModuleScope IntuneScriptLab -Parameters @{ Parameters = $Parameters } { + Invoke-IslWin32DetectionPass @Parameters + } + } + $script:MetRule = @{ Type = 'File'; Path = 'C:\x'; FileOrFolderName = 'present.txt' } + $script:UnmetRule = @{ Type = 'File'; Path = 'C:\x'; FileOrFolderName = 'missing.txt' } +} + +Describe 'Invoke-IslWin32DetectionPass' -Tag 'Unit', 'Private' { + + BeforeEach { + $script:Warnings = [System.Collections.Generic.List[string]]::new() + Mock Test-IntuneWin32Rule -ModuleName IntuneScriptLab { + $met = $Rule.FileOrFolderName -ne 'missing.txt' + [pscustomobject]@{ Met = $met; Kind = 'File'; Operation = 'Exists'; Reason = "reason $met" } + } + Mock Invoke-IntuneDetectionTest -ModuleName IntuneScriptLab { + [pscustomobject]@{ Detected = $true; TimedOut = $false; Reason = 'Exit 0 with stdout and no stderr' } + } + } + + It 'says detected when the script and every rule say installed' { + $pass = Invoke-Pass @{ + Phase = 'Pre'; Path = 'C:\lab\detect.ps1'; Rule = @($script:MetRule) + Detection = @{ Architecture = 'x64' }; Warning = $script:Warnings + } + + $pass | Should-HaveType 'IntuneScriptLab.Win32DetectionPass' + $pass.Detected | Should-BeTrue + $pass.Reason | Should-Be 'Script and rules all report installed' + $script:Warnings | Should-BeCollection @() + Should-Invoke Invoke-IntuneDetectionTest -ModuleName IntuneScriptLab -Times 1 -Exactly -ParameterFilter { + $Path -eq 'C:\lab\detect.ps1' -and $Architecture -eq 'x64' -and $ErrorAction -eq 'Stop' + } + } + + It 'says not detected for one rule that is not met, and adds a warning for it' { + $pass = Invoke-Pass @{ + Phase = 'Post'; Rule = @($script:MetRule, $script:UnmetRule); Label = ' for dependency Runtime' + Detection = @{}; Warning = $script:Warnings + } + + $pass.Detected | Should-BeFalse + $pass.Reason | Should-Be 'reason False' + $script:Warnings | Should-BeCollection -Count 1 + $expected = 'Post detection rule not met for dependency Runtime (File Exists): reason False' + $script:Warnings[0] | Should-Be $expected + Should-Invoke Invoke-IntuneDetectionTest -ModuleName IntuneScriptLab -Times 0 -Exactly + } + + It 'gives the script''s reason when the script says not installed' { + Mock Invoke-IntuneDetectionTest -ModuleName IntuneScriptLab { + [pscustomobject]@{ Detected = $false; TimedOut = $true; Reason = 'Timed out after 3 s' } + } + + $passSplat = @{ Phase = 'Pre'; Path = 'C:\lab\detect.ps1'; Detection = @{}; Warning = $script:Warnings } + $pass = Invoke-Pass $passSplat + + $pass.Detected | Should-BeFalse + $pass.TimedOut | Should-BeTrue + $pass.Reason | Should-Be 'Timed out after 3 s' + } + + It 'ends with the error of a detection script that cannot be run' { + Mock Invoke-IntuneDetectionTest -ModuleName IntuneScriptLab { throw 'The host could not be started.' } + + $passSplat = @{ Phase = 'Pre'; Path = 'C:\lab\detect.ps1'; Detection = @{}; Warning = $script:Warnings } + { Invoke-Pass $passSplat } | Should-Throw -ExceptionMessage '*host could not be started*' + } +} From 183aa88798f9c4ac3878256ddf44db2e20f33d68 Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:50:14 -0800 Subject: [PATCH 2/2] fix(win32): refuse an empty detection rule instead of leaving it out Invoke-IslWin32DetectionPass filtered null entries out of -Rule. A dependency or superseded app whose DetectionRule held only nulls passed the command's upfront check, since a list of two nulls is true, and its pass then had no script and no rules, which reads as detected: the dependency was reported Installed without being checked or installed. The nested function this replaced passed each entry to Test-IntuneWin32Rule, which refused the null. A null entry now ends the pass with DetectionRuleEmpty, and a pass with neither a script nor a rule ends with DetectionMissing. --- Private/Invoke-IslWin32DetectionPass.ps1 | 30 +++++++++++++++++-- .../Invoke-IslWin32DetectionPass.Tests.ps1 | 24 +++++++++++++++ .../Invoke-IntuneWin32AppTest.Tests.ps1 | 12 ++++++++ 3 files changed, 63 insertions(+), 3 deletions(-) diff --git a/Private/Invoke-IslWin32DetectionPass.ps1 b/Private/Invoke-IslWin32DetectionPass.ps1 index fa88c91..b75a89f 100644 --- a/Private/Invoke-IslWin32DetectionPass.ps1 +++ b/Private/Invoke-IslWin32DetectionPass.ps1 @@ -10,8 +10,10 @@ function Invoke-IslWin32DetectionPass { list it is given. A script that cannot be run, or a rule that cannot be read, ends the function with its - error. Invoke-IntuneDetectionTest reports a script it cannot run without ending, so it is - called with -ErrorAction Stop: with nothing returned, the app would read as detected. + error. An entry of -Rule that is null ends it with DetectionRuleEmpty, and a pass with + neither a script nor a rule with DetectionMissing: either would read as detected. + Invoke-IntuneDetectionTest reports a script it cannot run without ending, so it is called + with -ErrorAction Stop: with nothing returned, the app would read as detected. .PARAMETER Phase Pre or Post, for the warnings. @@ -71,13 +73,35 @@ function Invoke-IslWin32DetectionPass { [System.Collections.Generic.List[string]]$Warning ) + # A null entry is a rule that is missing, not one to leave out + $entries = @(if ($null -ne $Rule) { $Rule }) + $problem = $null + for ($index = 0; $index -lt $entries.Count; $index++) { + if ($null -eq $entries[$index]) { + $problem = @{ Id = 'DetectionRuleEmpty'; Text = "Detection rule $($index + 1)$Label is empty" } + break + } + } + if ($null -eq $problem -and -not $Path -and $entries.Count -eq 0) { + $problem = @{ Id = 'DetectionMissing'; Text = "The $Phase detection$Label has no script and no rules" } + } + if ($null -ne $problem) { + $recordSplat = @{ + Message = $problem['Text'] + ErrorId = $problem['Id'] + Category = [System.Management.Automation.ErrorCategory]::InvalidArgument + TargetObject = $Rule + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) + } + $scriptResult = $null try { if ($Path) { $detectionRun = @{ Path = $Path; ErrorAction = 'Stop' } $scriptResult = Invoke-IntuneDetectionTest @detectionRun @Detection @script:IslInternal } - $rules = @(foreach ($entry in @($Rule | Where-Object { $_ })) { + $rules = @(foreach ($entry in $entries) { Test-IntuneWin32Rule -Rule $entry -RuleType Detection -ErrorAction Stop }) } catch { diff --git a/Tests/Unit/Private/Invoke-IslWin32DetectionPass.Tests.ps1 b/Tests/Unit/Private/Invoke-IslWin32DetectionPass.Tests.ps1 index e69975e..f3945f0 100644 --- a/Tests/Unit/Private/Invoke-IslWin32DetectionPass.Tests.ps1 +++ b/Tests/Unit/Private/Invoke-IslWin32DetectionPass.Tests.ps1 @@ -75,6 +75,30 @@ Describe 'Invoke-IslWin32DetectionPass' -Tag 'Unit', 'Private' { $pass.Reason | Should-Be 'Timed out after 3 s' } + It 'ends with DetectionRuleEmpty for a rule entry that is null, and runs nothing' { + $pass = @{ + Phase = 'Pre'; Rule = @($script:MetRule, $null); Label = ' for dependency Runtime' + Detection = @{}; Warning = $script:Warnings + } + + { Invoke-Pass $pass } | Should-Throw -FullyQualifiedErrorId 'DetectionRuleEmpty,*' -ExceptionMessage ( + 'Detection rule 2 for dependency Runtime is empty') + Should-Invoke Test-IntuneWin32Rule -ModuleName IntuneScriptLab -Times 0 -Exactly + } + + It 'ends with DetectionRuleEmpty for rules that are all null, as an entry of -DependsOn can give' { + $pass = @{ Phase = 'Pre'; Rule = @($null, $null); Detection = @{}; Warning = $script:Warnings } + + { Invoke-Pass $pass } | Should-Throw -FullyQualifiedErrorId 'DetectionRuleEmpty,*' + } + + It 'ends with DetectionMissing for a pass with neither a script nor a rule' { + $pass = @{ Phase = 'Post'; Label = ' for superseded app Old'; Detection = @{}; Warning = $script:Warnings } + + { Invoke-Pass $pass } | Should-Throw -FullyQualifiedErrorId 'DetectionMissing,*' -ExceptionMessage ( + 'The Post detection for superseded app Old has no script and no rules') + } + It 'ends with the error of a detection script that cannot be run' { Mock Invoke-IntuneDetectionTest -ModuleName IntuneScriptLab { throw 'The host could not be started.' } diff --git a/Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 b/Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 index bb65260..0e68511 100644 --- a/Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 +++ b/Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1 @@ -583,6 +583,18 @@ Describe 'Invoke-IntuneWin32AppTest' -Tag 'Unit', 'Public' { { Invoke-IntuneWin32AppTest @script:ParentSplat -Supersedes $noDetection } | Should-Throw -FullyQualifiedErrorId 'RelatedAppDetectionMissing,*' } + + It 'installs neither the dependency nor the parent when the dependency''s rules are all empty' { + $empty = @{ + Name = 'Runtime'; DetectionRule = @($null, $null); ContentPath = $script:Child.Content + InstallCommand = 'setup.exe /mark child /exit 0' + } + + $failure = { Invoke-IntuneWin32AppTest @script:ParentSplat -DependsOn $empty } | + Should-Throw -FullyQualifiedErrorId 'DetectionRuleEmpty,*' + $failure.Exception.Message | Should-BeLikeString '*for dependency Runtime*' + Should-Invoke Invoke-IslProcess -ModuleName IntuneScriptLab -Times 0 -Exactly + } } Context 'Error Handling' {