From 29a823892030192bfb3bb53541d9fe9037a63efa Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:14:50 -0800 Subject: [PATCH 1/2] fix(module): run under strict mode and fail the import on a load error The root module set no strict mode, so a read of a member that was not there gave $null with no error anywhere in the module. Its loader dot-sourced each file without a try and read the folders with -ErrorAction SilentlyContinue: a file that did not parse wrote an error and the module still imported, without the commands of that file, and a missing Private or Public folder was not an error at all. The root module now sets Set-StrictMode -Version Latest and loads Private, Private/Rules and Public in one loop that fails on a missing folder and rethrows when a file fails to load. With strict mode on, 415 of the 998 unit tests failed, for a small number of causes, all of them reads of a member that is optional: - Hashtables that the module's caller writes (a settings table, a directive, a detection rule, a -DependsOn entry) are read with an index, which gives $null for a key that is not there. - Data from outside is read through Get-IslPropertyValue, a new private accessor that returns nothing for a missing input, key or property and takes a dictionary and an object alike: Graph replies in Test-IntuneDeployedScript, Compare-IntuneDeployedScript, Get-IntuneScriptHealth, Get-IslExportReport and Invoke-IslGraphRequest, the result of a CIM method in Get-IslLogonSession, and the two shapes of finding that Export-IntuneFindingSarif takes. - Find-IslModuleDependency no longer reads the required modules of a script that has no #Requires line, and the event table of Get-IslAgentLogEvent is assigned before its first read. The tests needed three kinds of change. Fakes of a run result named only the members their test was about; they go through ConvertTo-FakeRunResult, which adds the rest. The Graph mock of the health tests matched a run summary URI with two patterns and returned two objects, which member enumeration had hidden. Test code inside InModuleScope runs under the module's strict mode and reads no variable that was never set. Tests/Invoke-Tests.ps1 still turns strict mode off around the Pester run, for the suites and the validation kit. The module no longer depends on that. Refs #63 --- CHANGELOG.md | 9 + CLAUDE.md | 27 ++- IntuneScriptLab.psm1 | 35 ++-- Private/ConvertFrom-IslRuleSpec.ps1 | 38 ++-- Private/Get-IslAgentLogEvent.ps1 | 4 + Private/Get-IslExportReport.ps1 | 15 +- Private/Get-IslLogonSession.ps1 | 11 +- Private/Get-IslPropertyValue.ps1 | 65 +++++++ Private/Get-IslScriptContext.ps1 | 23 ++- Private/Get-IslSetting.ps1 | 36 ++-- Private/Invoke-IslGraphRequest.ps1 | 6 +- Private/Rules/Find-IslModuleDependency.ps1 | 8 +- Public/Compare-IntuneDeployedScript.ps1 | 92 +++++++--- Public/Export-IntuneFindingSarif.ps1 | 20 ++- Public/Get-IntuneScriptHealth.ps1 | 107 +++++++---- Public/Invoke-IntuneWin32AppTest.ps1 | 40 +++-- Public/Test-IntuneDeployedScript.ps1 | 166 +++++++++++------- Tests/Invoke-Tests.ps1 | 6 +- Tests/TestHelpers/TestHelpers.ps1 | 52 ++++++ Tests/Unit/Module.Contract.Tests.ps1 | 108 ++++++++++++ .../Private/Get-IslPropertyValue.Tests.ps1 | 134 ++++++++++++++ Tests/Unit/Private/Get-IslSetting.Tests.ps1 | 5 +- .../Private/Invoke-IslScriptRun.Tests.ps1 | 6 +- .../Public/Get-IntuneScriptHealth.Tests.ps1 | 4 +- .../Invoke-IntuneDetectionTest.Tests.ps1 | 22 +-- .../Invoke-IntunePlatformScriptTest.Tests.ps1 | 16 +- .../Invoke-IntuneRemediationTest.Tests.ps1 | 27 ++- .../Invoke-IntuneRequirementTest.Tests.ps1 | 12 +- 28 files changed, 833 insertions(+), 261 deletions(-) create mode 100644 Private/Get-IslPropertyValue.ps1 create mode 100644 Tests/Unit/Private/Get-IslPropertyValue.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 54ea5e9..7261a20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,6 +59,15 @@ entries are carried over from the manifest's release notes. without the key. - CI installs Pester 6.2.0 and PSScriptAnalyzer 1.25.0 exactly, where it took any Pester 6 from 6.2.0 on and the newest PSScriptAnalyzer. +- 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 + private accessor that takes a dictionary and an object alike, so a reply that leaves out an + optional field, such as a policy without a run schedule or a remediation script, is read as + before. +- Importing the module fails when its `Private`, `Private\Rules` or `Public` folder is missing or + when one of their files fails to load. A file that did not parse wrote an error and left the + module imported without the commands of that file. ### Removed diff --git a/CLAUDE.md b/CLAUDE.md index 809d968..d49dfa0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -81,6 +81,28 @@ always false. Name locals so they cannot collide with a parameter, and capture w function needs from `$PSBoundParameters` into a plain variable before defining it. 0.26.0 fixed both, with tests. +### The module runs under strict mode, and optional members are read through one accessor + +`IntuneScriptLab.psm1` sets `Set-StrictMode -Version Latest`, so in every function a read of a +member that is not there is a terminating error: `$reply.runSchedule` on a Graph reply without a +schedule, `$table.Severity` on a settings table without that key, `$result.Sid` on a CIM call that +returned nothing. A hashtable the module's own caller wrote is read with an index +(`$Rule['Operator']`), which gives `$null` for a missing key. Everything that comes from outside - +a Graph reply, an export row, a CIM result, an object that has one of two shapes - is read with +`Get-IslPropertyValue`, which returns nothing for a missing input, key or property and works for a +dictionary and an object alike. `Invoke-MgGraphRequest` returns dictionaries and a recorded fixture +read with `ConvertFrom-Json` returns objects, so member syntax that passes against one can fail +against the other. + +Code inside `InModuleScope` runs under the module's strict mode too. A mock body does not: it +stays in the test file's scope, where it can also call the helpers in `Tests/TestHelpers`. A fake +of a run result goes through `ConvertTo-FakeRunResult`, so that it has every member the real one +has. + +The loader fails the import when `Private`, `Private/Rules` or `Public` is missing or a file in +them fails to load. A file that does not parse used to leave the module imported without its +commands. + ### A nested function returning `@()` hands the caller `$null` Several public commands use nested helper functions. PowerShell unrolls an empty array on the @@ -175,5 +197,6 @@ under Windows PowerShell 5.1 as well before pushing: powershell -NoProfile -File ./Tests/Invoke-Tests.ps1 -TestType Unit ``` -The script sets strict mode for itself and turns it off around the Pester run, because the suites, -the validation kit and the module are not written for strict mode yet. Remove that when they are. +The script sets strict mode for itself and turns it off around the Pester run, because the suites +and the validation kit are not written for strict mode yet. Remove that when they are. The module +does not depend on it: it sets its own strict mode in the root module. diff --git a/IntuneScriptLab.psm1 b/IntuneScriptLab.psm1 index f81adc1..3193c07 100644 --- a/IntuneScriptLab.psm1 +++ b/IntuneScriptLab.psm1 @@ -5,23 +5,30 @@ # detection/remediation scripts, platform scripts and Win32 app detection/requirement scripts. # Every rule is backed by an observation in ..\Validation\Findings.md rather than by the docs. -$ModuleRoot = $PSScriptRoot -Write-Verbose "Initializing IntuneScriptLab module from: $ModuleRoot" +Set-StrictMode -Version Latest -# Import Private functions (helpers first, then the rules that use them) -foreach ($folder in 'Private', 'Private\Rules') { - $functions = Get-ChildItem -Path "$ModuleRoot\$folder\*.ps1" -ErrorAction SilentlyContinue - foreach ($function in $functions) { - Write-Verbose "Loading private function: $($function.Name)" - . $function.FullName +# Private helpers first, then the rules that use them, then the public functions. A folder that +# is missing or a file that fails to load fails the import: without that the module would import +# with commands missing. +$privateFolder = Join-Path -Path $PSScriptRoot -ChildPath 'Private' +$functionFolders = @( + $privateFolder + (Join-Path -Path $privateFolder -ChildPath 'Rules') + (Join-Path -Path $PSScriptRoot -ChildPath 'Public') +) +foreach ($functionFolder in $functionFolders) { + if (-not (Test-Path -LiteralPath $functionFolder -PathType Container)) { + throw "The module folder '$functionFolder' is missing." } -} -# Import Public functions -$publicFunctions = Get-ChildItem -Path "$ModuleRoot\Public\*.ps1" -ErrorAction SilentlyContinue -foreach ($function in $publicFunctions) { - Write-Verbose "Loading public function: $($function.Name)" - . $function.FullName + foreach ($functionFile in Get-ChildItem -LiteralPath $functionFolder -Filter '*.ps1' -File) { + try { + Write-Verbose "Loading $($functionFile.FullName)" + . $functionFile.FullName + } catch { + throw + } + } } # Rule registry: every Find-* function in Private\Rules is a rule. Test-IntuneScript runs them diff --git a/Private/ConvertFrom-IslRuleSpec.ps1 b/Private/ConvertFrom-IslRuleSpec.ps1 index 0f1cae3..0f72270 100644 --- a/Private/ConvertFrom-IslRuleSpec.ps1 +++ b/Private/ConvertFrom-IslRuleSpec.ps1 @@ -26,8 +26,8 @@ function ConvertFrom-IslRuleSpec { [hashtable]$Rule ) - $kind = if ($Rule.Type) { "$($Rule.Type)" } - elseif ($Rule.'@odata.type' -match '(?i)win32LobApp(FileSystem|Registry|ProductCode|PowerShellScript)') { + $kind = if ($Rule['Type']) { "$($Rule['Type'])" } + elseif ($Rule['@odata.type'] -match '(?i)win32LobApp(FileSystem|Registry|ProductCode|PowerShellScript)') { switch ($Matches[1].ToLower()) { 'filesystem' { 'File' } 'registry' { 'Registry' } @@ -38,32 +38,32 @@ function ConvertFrom-IslRuleSpec { else { '' } $splat = @{} - $operator = if ($Rule.Operator) { "$($Rule.Operator)" } else { '' } - $value = if ($null -ne $Rule.ComparisonValue) { "$($Rule.ComparisonValue)" } - elseif ($null -ne $Rule.Value) { "$($Rule.Value)" } + $operator = if ($Rule['Operator']) { "$($Rule['Operator'])" } else { '' } + $value = if ($null -ne $Rule['ComparisonValue']) { "$($Rule['ComparisonValue'])" } + elseif ($null -ne $Rule['Value']) { "$($Rule['Value'])" } else { $null } switch ($kind) { 'File' { - $splat.Path = "$($Rule.Path)" - $splat.FileOrFolderName = "$($Rule.FileOrFolderName)" - $splat.FileOperation = if ($Rule.OperationType) { "$($Rule.OperationType)" } - else { "$($Rule.FileOperation)" } - $splat.Check32BitOn64System = [bool]$Rule.Check32BitOn64System + $splat.Path = "$($Rule['Path'])" + $splat.FileOrFolderName = "$($Rule['FileOrFolderName'])" + $splat.FileOperation = if ($Rule['OperationType']) { "$($Rule['OperationType'])" } + else { "$($Rule['FileOperation'])" } + $splat.Check32BitOn64System = [bool]$Rule['Check32BitOn64System'] } 'Registry' { - $splat.KeyPath = "$($Rule.KeyPath)" - if ($Rule.ValueName) { $splat.ValueName = "$($Rule.ValueName)" } - $splat.RegistryOperation = if ($Rule.OperationType) { "$($Rule.OperationType)" } - else { "$($Rule.RegistryOperation)" } - $splat.Check32BitOn64System = [bool]$Rule.Check32BitOn64System + $splat.KeyPath = "$($Rule['KeyPath'])" + if ($Rule['ValueName']) { $splat.ValueName = "$($Rule['ValueName'])" } + $splat.RegistryOperation = if ($Rule['OperationType']) { "$($Rule['OperationType'])" } + else { "$($Rule['RegistryOperation'])" } + $splat.Check32BitOn64System = [bool]$Rule['Check32BitOn64System'] } 'ProductCode' { - $splat.ProductCode = "$($Rule.ProductCode)" - if ($Rule.ProductVersionOperator -and "$($Rule.ProductVersionOperator)" -ne 'notConfigured') { - $operator = "$($Rule.ProductVersionOperator)" + $splat.ProductCode = "$($Rule['ProductCode'])" + if ($Rule['ProductVersionOperator'] -and "$($Rule['ProductVersionOperator'])" -ne 'notConfigured') { + $operator = "$($Rule['ProductVersionOperator'])" } - if ($null -ne $Rule.ProductVersion) { $value = "$($Rule.ProductVersion)" } + 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)" } diff --git a/Private/Get-IslAgentLogEvent.ps1 b/Private/Get-IslAgentLogEvent.ps1 index 6991b95..fdc044d 100644 --- a/Private/Get-IslAgentLogEvent.ps1 +++ b/Private/Get-IslAgentLogEvent.ps1 @@ -288,6 +288,10 @@ function Get-IslAgentLogEvent { } } +# The event table, compiled by the first call of Get-IslAgentLogEvent. It is assigned here so +# that the test for it in the function reads a variable that exists, which strict mode requires. +$script:IslAgentLogEvents = $null + $script:IslAgentLogGuidRegex = [regex]::new( '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}', [System.Text.RegularExpressions.RegexOptions]::Compiled) diff --git a/Private/Get-IslExportReport.ps1 b/Private/Get-IslExportReport.ps1 index 8c6ef86..50b97bb 100644 --- a/Private/Get-IslExportReport.ps1 +++ b/Private/Get-IslExportReport.ps1 @@ -46,22 +46,27 @@ function Get-IslExportReport { if ($Select) { $body.select = $Select } $jobs = '/beta/deviceManagement/reports/exportJobs' $job = Invoke-IslGraphRequest -Uri $jobs -Method POST -Body $body + $jobStatus = "$(Get-IslPropertyValue -InputObject $job -Name 'status')" $deadline = (Get-Date).AddSeconds($TimeoutSeconds) - while ("$($job.status)" -in 'notStarted', 'inProgress') { + while ($jobStatus -in 'notStarted', 'inProgress') { if ((Get-Date) -gt $deadline) { throw "The $ReportName export job did not complete within $TimeoutSeconds seconds" } Start-Sleep -Seconds 5 - $job = Invoke-IslGraphRequest -Uri "$jobs/$($job.id)" + $jobId = Get-IslPropertyValue -InputObject $job -Name 'id' + $job = Invoke-IslGraphRequest -Uri "$jobs/$jobId" + $jobStatus = "$(Get-IslPropertyValue -InputObject $job -Name 'status')" } - if ("$($job.status)" -ne 'completed' -or -not $job.url) { - throw "The $ReportName export job ended with status '$($job.status)'" + # The download address is there only once the job has completed + $jobUrl = Get-IslPropertyValue -InputObject $job -Name 'url' + if ($jobStatus -ne 'completed' -or -not $jobUrl) { + throw "The $ReportName export job ended with status '$jobStatus'" } $zipName = "IntuneScriptLab-$([guid]::NewGuid().ToString('N')).zip" $zip = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath $zipName try { - Invoke-WebRequest -Uri $job.url -OutFile $zip -UseBasicParsing + Invoke-WebRequest -Uri $jobUrl -OutFile $zip -UseBasicParsing Add-Type -AssemblyName System.IO.Compression.FileSystem $archive = [System.IO.Compression.ZipFile]::OpenRead($zip) try { diff --git a/Private/Get-IslLogonSession.ps1 b/Private/Get-IslLogonSession.ps1 index 8dd205b..89491d0 100644 --- a/Private/Get-IslLogonSession.ps1 +++ b/Private/Get-IslLogonSession.ps1 @@ -29,16 +29,19 @@ function Get-IslLogonSession { $shells = @(Get-CimInstance -ClassName Win32_Process -Filter $filter -ErrorAction SilentlyContinue) $seen = @{} foreach ($shell in ($shells | Sort-Object -Property SessionId, Name)) { + # Either call returns nothing for a process that ended or that this session may not ask about $owner = Invoke-CimMethod -InputObject $shell -MethodName GetOwner -ErrorAction SilentlyContinue - $sid = (Invoke-CimMethod -InputObject $shell -MethodName GetOwnerSid -ErrorAction SilentlyContinue).Sid - if (-not $sid -or -not $owner.User) { continue } + $ownerSid = Invoke-CimMethod -InputObject $shell -MethodName GetOwnerSid -ErrorAction SilentlyContinue + $sid = Get-IslPropertyValue -InputObject $ownerSid -Name 'Sid' + $userName = Get-IslPropertyValue -InputObject $owner -Name 'User' + if (-not $sid -or -not $userName) { continue } $key = "$($shell.SessionId)|$sid" if ($seen.ContainsKey($key)) { continue } $seen[$key] = $true [pscustomobject]@{ PSTypeName = 'IntuneScriptLab.LogonSession' - UserName = $owner.User - Domain = $owner.Domain + UserName = $userName + Domain = Get-IslPropertyValue -InputObject $owner -Name 'Domain' Sid = $sid Id = [int]$shell.SessionId } diff --git a/Private/Get-IslPropertyValue.ps1 b/Private/Get-IslPropertyValue.ps1 new file mode 100644 index 0000000..ef6f591 --- /dev/null +++ b/Private/Get-IslPropertyValue.ps1 @@ -0,0 +1,65 @@ +function Get-IslPropertyValue { + <# + .SYNOPSIS + Gets a named value from a dictionary or an object, or nothing when it has none. + + .DESCRIPTION + Data that reaches the module from outside has optional members and comes in two shapes: a + Graph reply is a dictionary or an object depending on how it was read, a rule or a settings + table is a hashtable the caller wrote, and a CIM call that fails returns nothing at all. + Under strict mode a read of a member that is not there is an error, so every such read goes + through this function, which returns nothing for a missing input, a missing key and a + missing property alike. + + A collection is unrolled on the way out, like the output of any function. Wrap the call in + @() where the value is a list. + + .PARAMETER InputObject + The dictionary or object to read from. Nothing is returned when it is $null. + + .PARAMETER Name + The key or property name. + + .EXAMPLE + Get-IslPropertyValue -InputObject $page -Name '@odata.nextLink' + + The address of the next page of a Graph reply, or nothing on the last page. + + .EXAMPLE + @(Get-IslPropertyValue -InputObject $policy -Name 'assignments') + + The assignments of a policy as an array, empty when the reply has none. + + .INPUTS + None. + + .OUTPUTS + System.Object. The value, or nothing when the input has no such member. + #> + [CmdletBinding()] + [OutputType([object])] + param( + [Parameter()] + [AllowNull()] + [object]$InputObject, + + [Parameter(Mandatory)] + [string]$Name + ) + + if ($null -eq $InputObject) { + return + } + + if ($InputObject -is [System.Collections.IDictionary]) { + if ($InputObject.Contains($Name)) { + return $InputObject[$Name] + } + return + } + + $property = $InputObject.PSObject.Properties[$Name] + if ($null -ne $property) { + return $property.Value + } +} diff --git a/Private/Get-IslScriptContext.ps1 b/Private/Get-IslScriptContext.ps1 index 8ce84d8..e62d462 100644 --- a/Private/Get-IslScriptContext.ps1 +++ b/Private/Get-IslScriptContext.ps1 @@ -91,10 +91,17 @@ function Get-IslScriptContext { '(?i)(^|[^a-z])(remediat\w*|fix)([^a-z]|$)' { 'Remediation'; break } default { 'PlatformScript' } } + # -Settings is optional, and a directive names only some of the four keys. An index reads a + # key the directive lacks as $null, and the accessor does the same for the settings object + $settingsType = Get-IslPropertyValue -InputObject $Settings -Name 'ScriptType' + $settingsContext = Get-IslPropertyValue -InputObject $Settings -Name 'Context' + $settingsArchitecture = Get-IslPropertyValue -InputObject $Settings -Name 'Architecture' + $settingsSignatureCheck = Get-IslPropertyValue -InputObject $Settings -Name 'EnforceSignatureCheck' + $typeSource = 'parameter' if ($ScriptType -eq 'Auto') { - if ($directive.ScriptType) { $ScriptType = $directive.ScriptType; $typeSource = 'directive' } - elseif ($Settings.ScriptType) { $ScriptType = $Settings.ScriptType; $typeSource = 'settings' } + if ($directive['ScriptType']) { $ScriptType = $directive['ScriptType']; $typeSource = 'directive' } + elseif ($settingsType) { $ScriptType = $settingsType; $typeSource = 'settings' } else { $ScriptType = $inferredType; $typeSource = $inferredSource } } @@ -102,23 +109,23 @@ function Get-IslScriptContext { # (Findings.md, "Graph API defaults"); these are the portal ones because that is what most # scripts get, and they are the more restrictive assumption for the rules. if ($Context -eq 'Auto') { - $Context = if ($directive.Context) { $directive.Context } - elseif ($Settings.Context) { $Settings.Context } + $Context = if ($directive['Context']) { $directive['Context'] } + elseif ($settingsContext) { $settingsContext } elseif ($ScriptType -eq 'PlatformScript') { 'User' } # portal default for platform scripts else { 'System' } } if ($Architecture -eq 'Auto') { - $Architecture = if ($directive.Architecture) { $directive.Architecture } - elseif ($Settings.Architecture) { $Settings.Architecture } + $Architecture = if ($directive['Architecture']) { $directive['Architecture'] } + elseif ($settingsArchitecture) { $settingsArchitecture } elseif ($ScriptType -in 'Win32Detection', 'Win32Requirement') { 'x64' } # 64-bit by default else { 'x86' } # scripts/remediations: 32-bit } $signatureCheck = if ($EnforceSignatureCheck -ne 'Auto') { $EnforceSignatureCheck -eq 'True' } elseif ($directive.ContainsKey('EnforceSignatureCheck')) { - "$($directive.EnforceSignatureCheck)" -in 'true', '1', 'yes' + "$($directive['EnforceSignatureCheck'])" -in 'true', '1', 'yes' } - elseif ($null -ne $Settings.EnforceSignatureCheck) { [bool]$Settings.EnforceSignatureCheck } + elseif ($null -ne $settingsSignatureCheck) { [bool]$settingsSignatureCheck } else { $false } [pscustomobject]@{ diff --git a/Private/Get-IslSetting.ps1 b/Private/Get-IslSetting.ps1 index 317f016..7acc495 100644 --- a/Private/Get-IslSetting.ps1 +++ b/Private/Get-IslSetting.ps1 @@ -58,37 +58,45 @@ function Get-IslSetting { if ($unknown) { Write-Warning "Unknown settings key(s) in ${Source}: $($unknown -join ', ')" } - if ($Table.MinimumSeverity -and "$($Table.MinimumSeverity)" -notin $validSeverities) { + # Every key is optional. An index reads a key that is not there as $null, where member + # access is an error under strict mode + $minimumSeverity = $Table['MinimumSeverity'] + $scriptType = $Table['ScriptType'] + $context = $Table['Context'] + $architecture = $Table['Architecture'] + $severityTable = $Table['Severity'] + if ($minimumSeverity -and "$minimumSeverity" -notin $validSeverities) { throw "${Source}: MinimumSeverity must be one of $($validSeverities -join ', ')" } - if ($Table.ScriptType -and "$($Table.ScriptType)" -notin $validTypes) { + if ($scriptType -and "$scriptType" -notin $validTypes) { throw "${Source}: ScriptType must be one of $($validTypes -join ', ')" } - if ($Table.Context -and "$($Table.Context)" -notin 'System', 'User') { + if ($context -and "$context" -notin 'System', 'User') { throw "${Source}: Context must be System or User" } - if ($Table.Architecture -and "$($Table.Architecture)" -notin 'x86', 'x64', 'arm64') { + if ($architecture -and "$architecture" -notin 'x86', 'x64', 'arm64') { throw "${Source}: Architecture must be x86, x64 or arm64" } $severity = @{} - foreach ($key in @($Table.Severity.Keys | Where-Object { $null -ne $_ })) { - if ("$($Table.Severity[$key])" -notin $validSeverities) { + $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 ', ')" } - $severity[$key] = "$($Table.Severity[$key])" + $severity[$key] = "$($severityTable[$key])" } [pscustomobject]@{ PSTypeName = 'IntuneScriptLab.Settings' Source = $Source - ExcludeRule = @($Table.ExcludeRule | Where-Object { $_ }) - IncludeRule = @($Table.IncludeRule | Where-Object { $_ }) - MinimumSeverity = if ($Table.MinimumSeverity) { "$($Table.MinimumSeverity)" } else { $null } + ExcludeRule = @($Table['ExcludeRule'] | Where-Object { $_ }) + IncludeRule = @($Table['IncludeRule'] | Where-Object { $_ }) + MinimumSeverity = if ($minimumSeverity) { "$minimumSeverity" } else { $null } Severity = $severity - ScriptType = if ($Table.ScriptType) { "$($Table.ScriptType)" } else { $null } - Context = if ($Table.Context) { "$($Table.Context)" } else { $null } - Architecture = if ($Table.Architecture) { "$($Table.Architecture)" } else { $null } + ScriptType = if ($scriptType) { "$scriptType" } else { $null } + Context = if ($context) { "$context" } else { $null } + Architecture = if ($architecture) { "$architecture" } else { $null } EnforceSignatureCheck = if ($Table.ContainsKey('EnforceSignatureCheck')) { - [bool]$Table.EnforceSignatureCheck + [bool]$Table['EnforceSignatureCheck'] } else { $null } } diff --git a/Private/Invoke-IslGraphRequest.ps1 b/Private/Invoke-IslGraphRequest.ps1 index 31762a0..66b9076 100644 --- a/Private/Invoke-IslGraphRequest.ps1 +++ b/Private/Invoke-IslGraphRequest.ps1 @@ -122,8 +122,10 @@ function Invoke-IslGraphRequest { while ($next) { $requestSplat.Uri = $next $page = Invoke-Once -Splat $requestSplat - if ($page.value) { $items.AddRange([object[]]$page.value) } - $next = $page.'@odata.nextLink' + # The last page has no next link, and an empty collection may come without a value + $pageItems = @(Get-IslPropertyValue -InputObject $page -Name 'value') + if ($pageItems.Count -gt 0) { $items.AddRange([object[]]$pageItems) } + $next = Get-IslPropertyValue -InputObject $page -Name '@odata.nextLink' } $items.ToArray() } diff --git a/Private/Rules/Find-IslModuleDependency.ps1 b/Private/Rules/Find-IslModuleDependency.ps1 index 8ce0e9d..6b629ca 100644 --- a/Private/Rules/Find-IslModuleDependency.ps1 +++ b/Private/Rules/Find-IslModuleDependency.ps1 @@ -64,7 +64,13 @@ function Find-IslModuleDependency { New-IslFinding @findingSplat } - foreach ($required in @($Context.Ast.ScriptRequirements.RequiredModules | Where-Object { $_ })) { + # A script without a #Requires line has no requirements object at all + $requirements = $Context.Ast.ScriptRequirements + $requiredModules = @() + if ($null -ne $requirements) { + $requiredModules = @($requirements.RequiredModules | Where-Object { $_ }) + } + foreach ($required in $requiredModules) { if (-not (Test-InBox -Name "$($required.Name)")) { Write-Missing -Name $required.Name -Extent $Context.Ast.Extent -How '#Requires -Modules' } diff --git a/Public/Compare-IntuneDeployedScript.ps1 b/Public/Compare-IntuneDeployedScript.ps1 index d323f49..00f7bb7 100644 --- a/Public/Compare-IntuneDeployedScript.ps1 +++ b/Public/Compare-IntuneDeployedScript.ps1 @@ -45,10 +45,11 @@ function Compare-IntuneDeployedScript { function Test-Wanted { param($Policy) - $displayName = "$($Policy.displayName)" + $displayName = "$(Get-IslPropertyValue -InputObject $Policy -Name 'displayName')" + $policyId = "$(Get-IslPropertyValue -InputObject $Policy -Name 'id')" # -Id alone selects by id: -Name's default of '*' only counts when -Name was given or -Id was not $byName = ($nameGiven -or -not $Id) -and @($Name | Where-Object { $displayName -like $_ }).Count -gt 0 - $byId = $Id -and "$($Policy.id)" -in $Id + $byId = $Id -and $policyId -in $Id $byName -or $byId } @@ -61,8 +62,10 @@ function Compare-IntuneDeployedScript { function Get-MapEntry { param($Policy) if (-not $Map) { return $null } + $policyName = "$(Get-IslPropertyValue -InputObject $Policy -Name 'displayName')" + $policyId = "$(Get-IslPropertyValue -InputObject $Policy -Name 'id')" foreach ($key in $Map.Keys) { - if ("$key" -eq "$($Policy.displayName)" -or "$key" -eq "$($Policy.id)") { + if ("$key" -eq $policyName -or "$key" -eq $policyId) { $mapped["$key"] = $true return $Map[$key] } @@ -88,7 +91,7 @@ function Compare-IntuneDeployedScript { else { Join-Path -Path $root -ChildPath "$value" } return @([pscustomobject]@{ FullName = $full }) } - $key = Get-NameKey -Value "$($Policy.displayName)" + $key = Get-NameKey -Value "$(Get-IslPropertyValue -InputObject $Policy -Name 'displayName')" $named = @($folders | Where-Object { (Get-NameKey -Value $_.Name) -eq $key }) $inside = @(foreach ($folder in $named) { $files | Where-Object { $_.DirectoryName -eq $folder.FullName } @@ -246,8 +249,8 @@ function Compare-IntuneDeployedScript { [pscustomobject]@{ PSTypeName = 'IntuneScriptLab.DriftResult' Kind = $PolicyKind - PolicyName = "$($Policy.displayName)" - PolicyId = "$($Policy.id)" + PolicyName = "$(Get-IslPropertyValue -InputObject $Policy -Name 'displayName')" + PolicyId = "$(Get-IslPropertyValue -InputObject $Policy -Name 'id')" Role = $Role State = $State Differences = @($Differences | Where-Object { $_ }) @@ -255,7 +258,7 @@ function Compare-IntuneDeployedScript { LocalPath = $LocalPath LocalHash = $LocalHash TenantHash = $TenantHash - TenantModified = $Policy.lastModifiedDateTime + TenantModified = Get-IslPropertyValue -InputObject $Policy -Name 'lastModifiedDateTime' } } @@ -280,8 +283,9 @@ function Compare-IntuneDeployedScript { $tenantHash = Get-Hash -Bytes $tenantBytes $tenantShort = $tenantHash.Substring(0, 12) if ($candidates.Count -eq 0) { + $policyName = Get-IslPropertyValue -InputObject $Policy -Name 'displayName' ConvertTo-Result @base -State 'Missing' -TenantHash $tenantShort -Detail ( - "no local file for the $label of '$($Policy.displayName)' under $root") + "no local file for the $label of '$policyName' under $root") return } if ($candidates.Count -gt 1) { @@ -341,20 +345,26 @@ function Compare-IntuneDeployedScript { if ('Remediation' -in $Kind) { $remediations = '/beta/deviceManagement/deviceHealthScripts' foreach ($summary in (Get-WantedPolicy -Uri "$remediations`?`$select=id,displayName")) { - $policy = Invoke-IslGraphRequest -Uri "$remediations/$($summary.id)" + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $policy = Invoke-IslGraphRequest -Uri "$remediations/$summaryId" $policySettings = @{ - RunAsAccount = $policy.runAsAccount; RunAs32Bit = $policy.runAs32Bit - EnforceSignatureCheck = $policy.enforceSignatureCheck + RunAsAccount = Get-IslPropertyValue -InputObject $policy -Name 'runAsAccount' + RunAs32Bit = Get-IslPropertyValue -InputObject $policy -Name 'runAs32Bit' + EnforceSignatureCheck = Get-IslPropertyValue -InputObject $policy -Name 'enforceSignatureCheck' } $detectSplat = @{ - PolicyKind = 'Remediation'; Policy = $policy; Role = 'detection' - Content = $policy.detectionScriptContent + PolicyKind = 'Remediation' + Policy = $policy + Role = 'detection' + Content = Get-IslPropertyValue -InputObject $policy -Name 'detectionScriptContent' Candidates = Find-LocalFile -Policy $policy -Role 'detection' -Pattern '^(?i)detect' } Compare-Role @detectSplat @policySettings $remediateSplat = @{ - PolicyKind = 'Remediation'; Policy = $policy; Role = 'remediation' - Content = $policy.remediationScriptContent + PolicyKind = 'Remediation' + Policy = $policy + Role = 'remediation' + Content = Get-IslPropertyValue -InputObject $policy -Name 'remediationScriptContent' Candidates = Find-LocalFile -Policy $policy -Role 'remediation' -Pattern '^(?i)remediat' } Compare-Role @remediateSplat @policySettings @@ -364,11 +374,16 @@ function Compare-IntuneDeployedScript { if ('PlatformScript' -in $Kind) { $scripts = '/beta/deviceManagement/deviceManagementScripts' foreach ($summary in (Get-WantedPolicy -Uri "$scripts`?`$select=id,displayName")) { - $policy = Invoke-IslGraphRequest -Uri "$scripts/$($summary.id)" + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $policy = Invoke-IslGraphRequest -Uri "$scripts/$summaryId" $scriptSplat = @{ - PolicyKind = 'PlatformScript'; Policy = $policy; Role = 'script' - Content = $policy.scriptContent; RunAsAccount = $policy.runAsAccount - RunAs32Bit = $policy.runAs32Bit; EnforceSignatureCheck = $policy.enforceSignatureCheck + PolicyKind = 'PlatformScript' + Policy = $policy + Role = 'script' + Content = Get-IslPropertyValue -InputObject $policy -Name 'scriptContent' + RunAsAccount = Get-IslPropertyValue -InputObject $policy -Name 'runAsAccount' + RunAs32Bit = Get-IslPropertyValue -InputObject $policy -Name 'runAs32Bit' + EnforceSignatureCheck = Get-IslPropertyValue -InputObject $policy -Name 'enforceSignatureCheck' Candidates = Find-LocalFile -Policy $policy -Role 'script' } Compare-Role @scriptSplat @@ -379,9 +394,13 @@ function Compare-IntuneDeployedScript { $apps = '/beta/deviceAppManagement/mobileApps' $listUri = "$apps`?`$filter=isof('microsoft.graph.win32LobApp')&`$select=id,displayName" foreach ($summary in (Get-WantedPolicy -Uri $listUri)) { - $app = Invoke-IslGraphRequest -Uri "$apps/$($summary.id)" + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $app = Invoke-IslGraphRequest -Uri "$apps/$summaryId" $scriptType = '#microsoft.graph.win32LobAppPowerShellScriptDetection' - $detectionRules = @($app.detectionRules | Where-Object { "$($_.'@odata.type')" -eq $scriptType }) + $detectionRules = @( + Get-IslPropertyValue -InputObject $app -Name 'detectionRules' | Where-Object { + "$(Get-IslPropertyValue -InputObject $_ -Name '@odata.type')" -eq $scriptType + }) $detectionFiles = @(Find-LocalFile -Policy $app -Role 'detection' -Pattern '^(?i)detect') for ($index = 0; $index -lt $detectionRules.Count; $index++) { $candidateSplat = @{ @@ -389,10 +408,17 @@ function Compare-IntuneDeployedScript { } $candidates = Select-Candidate @candidateSplat $rule = $detectionRules[$index] + $signatureCheck = Get-IslPropertyValue -InputObject $rule -Name 'enforceSignatureCheck' $detectSplat = @{ - PolicyKind = 'Win32App'; Policy = $app; Role = 'detection'; Content = $rule.scriptContent - Candidates = $candidates; RunAsAccount = 'system'; RunAs32Bit = $rule.runAs32Bit - EnforceSignatureCheck = $rule.enforceSignatureCheck; HasContext = $false + PolicyKind = 'Win32App' + Policy = $app + Role = 'detection' + Content = Get-IslPropertyValue -InputObject $rule -Name 'scriptContent' + Candidates = $candidates + RunAsAccount = 'system' + RunAs32Bit = Get-IslPropertyValue -InputObject $rule -Name 'runAs32Bit' + EnforceSignatureCheck = $signatureCheck + HasContext = $false } Compare-Role @detectSplat } @@ -404,8 +430,10 @@ function Compare-IntuneDeployedScript { Compare-Role @noRuleSplat } $requirementType = '#microsoft.graph.win32LobAppPowerShellScriptRequirement' - $requirementRules = @($app.requirementRules | - Where-Object { "$($_.'@odata.type')" -eq $requirementType }) + $requirementRules = @( + Get-IslPropertyValue -InputObject $app -Name 'requirementRules' | Where-Object { + "$(Get-IslPropertyValue -InputObject $_ -Name '@odata.type')" -eq $requirementType + }) $requirementFiles = @(Find-LocalFile -Policy $app -Role 'requirement' -Pattern '^(?i)requirement') if ($requirementRules.Count -eq 0) { $noRuleSplat = @{ @@ -420,10 +448,16 @@ function Compare-IntuneDeployedScript { } $candidates = Select-Candidate @candidateSplat $rule = $requirementRules[$index] + $signatureCheck = Get-IslPropertyValue -InputObject $rule -Name 'enforceSignatureCheck' $requirementSplat = @{ - PolicyKind = 'Win32App'; Policy = $app; Role = 'requirement'; Content = $rule.scriptContent - Candidates = $candidates; RunAsAccount = $rule.runAsAccount; RunAs32Bit = $rule.runAs32Bit - EnforceSignatureCheck = $rule.enforceSignatureCheck + PolicyKind = 'Win32App' + Policy = $app + Role = 'requirement' + Content = Get-IslPropertyValue -InputObject $rule -Name 'scriptContent' + Candidates = $candidates + RunAsAccount = Get-IslPropertyValue -InputObject $rule -Name 'runAsAccount' + RunAs32Bit = Get-IslPropertyValue -InputObject $rule -Name 'runAs32Bit' + EnforceSignatureCheck = $signatureCheck } Compare-Role @requirementSplat } diff --git a/Public/Export-IntuneFindingSarif.ps1 b/Public/Export-IntuneFindingSarif.ps1 index 0cfad72..d5b149c 100644 --- a/Public/Export-IntuneFindingSarif.ps1 +++ b/Public/Export-IntuneFindingSarif.ps1 @@ -85,13 +85,17 @@ function Export-IntuneFindingSarif { if ($itemLevel -and $rank[$itemLevel] -gt $rank[$level]) { $level = $itemLevel } } if ($fixedRules.ContainsKey($name)) { - $summary = $fixedRules[$name].Summary - if ($fixedRules[$name].Level) { $level = $fixedRules[$name].Level } + $fixedRule = $fixedRules[$name] + $summary = $fixedRule['Summary'] + # A rule that reports at several severities has no level of its own + if ($fixedRule['Level']) { $level = $fixedRule['Level'] } } elseif (Get-Command -Name "Find-$name" -ErrorAction SilentlyContinue) { $help = Get-Help -Name "Find-$name" -ErrorAction SilentlyContinue $summary = "$($help.Synopsis)".Trim() - $description = (@($help.Description | ForEach-Object { $_.Text }) -join ' ') -replace '\s+', ' ' + # Help without a .DESCRIPTION has no description member + $paragraphs = @(Get-IslPropertyValue -InputObject $help -Name 'Description') + $description = (@($paragraphs | ForEach-Object { $_.Text }) -join ' ') -replace '\s+', ' ' } if (-not $summary) { $summary = $name } $rule = [ordered]@{ @@ -117,7 +121,8 @@ function Export-IntuneFindingSarif { } # A policy check from Test-IntuneDeployedScript has no script behind it; SARIF allows a # result without a location, and the policy's name goes into the message instead - $scriptPath = "$($item.PSObject.Properties['ScriptPath'].Value)" + $scriptPath = "$(Get-IslPropertyValue -InputObject $item -Name 'ScriptPath')" + $policyName = Get-IslPropertyValue -InputObject $item -Name 'PolicyName' if ($scriptPath) { $result.locations = @( [ordered]@{ @@ -128,14 +133,15 @@ function Export-IntuneFindingSarif { } ) } - elseif ($item.PSObject.Properties['PolicyName'] -and $item.PolicyName) { - $result.message.text = "$($item.Kind) '$($item.PolicyName)': $($item.Message)" + elseif ($policyName) { + $policyKind = Get-IslPropertyValue -InputObject $item -Name 'Kind' + $result.message.text = "$policyKind '$policyName': $($item.Message)" } $result.properties = [ordered]@{ scriptType = "$($item.ScriptType)" evidence = "$($item.Evidence)" } - if ($item.PSObject.Properties['Suppressed'] -and $item.Suppressed) { + if (Get-IslPropertyValue -InputObject $item -Name 'Suppressed') { $result.suppressions = @([ordered]@{ kind = 'inSource' }) } $result diff --git a/Public/Get-IntuneScriptHealth.ps1 b/Public/Get-IntuneScriptHealth.ps1 index e7a66cc..940c3c3 100644 --- a/Public/Get-IntuneScriptHealth.ps1 +++ b/Public/Get-IntuneScriptHealth.ps1 @@ -35,10 +35,11 @@ function Get-IntuneScriptHealth { function Test-Wanted { param($Policy) - $displayName = "$($Policy.displayName)" + $displayName = "$(Get-IslPropertyValue -InputObject $Policy -Name 'displayName')" + $policyId = "$(Get-IslPropertyValue -InputObject $Policy -Name 'id')" # -Id alone selects by id: -Name's default of '*' only counts when -Name was given or -Id was not $byName = ($nameGiven -or -not $Id) -and @($Name | Where-Object { $displayName -like $_ }).Count -gt 0 - $byId = $Id -and "$($Policy.id)" -in $Id + $byId = $Id -and $policyId -in $Id $byName -or $byId } @@ -85,7 +86,7 @@ function Get-IntuneScriptHealth { if (-not $SkipRunState -and 'Win32App' -in $Kind) { try { foreach ($row in @(Get-IslExportReport -ReportName 'AppInstallStatusAggregate')) { - $appInstall["$($row.ApplicationId)"] = $row + $appInstall["$(Get-IslPropertyValue -InputObject $row -Name 'ApplicationId')"] = $row } } catch { @@ -108,22 +109,26 @@ function Get-IntuneScriptHealth { function Get-AssignmentText { param($Policy) - $assignments = @($Policy.assignments | Where-Object { $_ }) + $assignments = @(Get-IslPropertyValue -InputObject $Policy -Name 'assignments' | Where-Object { $_ }) $includes = 0 $exclusions = 0 $filters = 0 $broad = [System.Collections.Generic.List[string]]::new() foreach ($assignment in $assignments) { - $target = $assignment.target - $type = "$($target.'@odata.type')" -replace '^#microsoft\.graph\.', '' + $target = Get-IslPropertyValue -InputObject $assignment -Name 'target' + $targetType = "$(Get-IslPropertyValue -InputObject $target -Name '@odata.type')" + $type = $targetType -replace '^#microsoft\.graph\.', '' if ($type -eq 'exclusionGroupAssignmentTarget') { $exclusions++ } else { $includes++ if ($type -eq 'allDevicesAssignmentTarget') { $broad.Add('all devices') } if ($type -eq 'allLicensedUsersAssignmentTarget') { $broad.Add('all users') } } - $filterType = "$($target.deviceAndAppManagementAssignmentFilterType)" - if ($target.deviceAndAppManagementAssignmentFilterId -and $filterType -ne 'none') { $filters++ } + # An assignment without a filter carries neither key, or a type of none + $filterId = Get-IslPropertyValue -InputObject $target -Name 'deviceAndAppManagementAssignmentFilterId' + $filterTypeName = 'deviceAndAppManagementAssignmentFilterType' + $filterType = Get-IslPropertyValue -InputObject $target -Name $filterTypeName + if ($filterId -and "$filterType" -ne 'none') { $filters++ } } $text = "$includes include" if ($broad.Count) { $text += " ($($broad -join ', '))" } @@ -137,7 +142,7 @@ function Get-IntuneScriptHealth { [string]$PolicyKind, $Policy, [string]$Context, [int]$Succeeded, [int]$Failed, [int]$Detected, [int]$Pending, $LastRun, [string[]]$DeviceNotes, [bool]$HasRunState ) - $key = "$($Policy.id)" + $key = "$(Get-IslPropertyValue -InputObject $Policy -Name 'id')" $findings = @(if ($findingsByPolicy.ContainsKey($key)) { $findingsByPolicy[$key] }) $errors = @($findings | Where-Object Severity -eq 'Error').Count $warnings = @($findings | Where-Object Severity -eq 'Warning').Count @@ -185,11 +190,11 @@ function Get-IntuneScriptHealth { [pscustomobject]@{ PSTypeName = 'IntuneScriptLab.HealthReport' Kind = $PolicyKind - PolicyName = "$($Policy.displayName)" + PolicyName = "$(Get-IslPropertyValue -InputObject $Policy -Name 'displayName')" PolicyId = $key Context = $Context Assigned = $assignment.Text - LastModified = $Policy.lastModifiedDateTime + LastModified = Get-IslPropertyValue -InputObject $Policy -Name 'lastModifiedDateTime' Errors = $errors Warnings = $warnings Findings = $findings @@ -210,20 +215,38 @@ function Get-IntuneScriptHealth { $remediations = '/beta/deviceManagement/deviceHealthScripts' $fields = 'id,displayName,runAsAccount,lastModifiedDateTime' foreach ($summary in (Get-WantedPolicy -Uri "$remediations`?`$select=id,displayName")) { - $policyUri = "$remediations/$($summary.id)?`$select=$fields&`$expand=assignments" + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $policyUri = "$remediations/$summaryId`?`$select=$fields&`$expand=assignments" $policy = Invoke-IslGraphRequest -Uri $policyUri - $run = Get-RunSummary -Uri "$remediations/$($summary.id)/runSummary" - $scriptErrors = [int]$run.detectionScriptErrorDeviceCount + [int]$run.remediationScriptErrorDeviceCount + $run = Get-RunSummary -Uri "$remediations/$summaryId/runSummary" + # The summary is absent under -SkipRunState and when it could not be read, and a + # counter that is not in it counts as zero + $runCount = @{} + $counters = @( + 'noIssueDetected' + 'issueRemediated' + 'issueDetected' + 'issueReoccurred' + 'detectionScriptError' + 'remediationScriptError' + 'detectionScriptPending' + 'detectionScriptNotApplicable' + ) + foreach ($counter in $counters) { + $runCount[$counter] = [int](Get-IslPropertyValue -InputObject $run -Name "${counter}DeviceCount") + } + $notApplicable = $runCount['detectionScriptNotApplicable'] $reportSplat = @{ - PolicyKind = 'Remediation'; Policy = $policy; Context = "$($policy.runAsAccount)" - Succeeded = [int]$run.noIssueDetectedDeviceCount + [int]$run.issueRemediatedDeviceCount - Failed = $scriptErrors - Detected = [int]$run.issueDetectedDeviceCount + [int]$run.issueReoccurredDeviceCount - Pending = [int]$run.detectionScriptPendingDeviceCount - LastRun = $run.lastScriptRunDateTime + PolicyKind = 'Remediation' + Policy = $policy + Context = "$(Get-IslPropertyValue -InputObject $policy -Name 'runAsAccount')" + Succeeded = $runCount['noIssueDetected'] + $runCount['issueRemediated'] + Failed = $runCount['detectionScriptError'] + $runCount['remediationScriptError'] + Detected = $runCount['issueDetected'] + $runCount['issueReoccurred'] + Pending = $runCount['detectionScriptPending'] + LastRun = Get-IslPropertyValue -InputObject $run -Name 'lastScriptRunDateTime' HasRunState = [bool]$run - DeviceNotes = @(if ([int]$run.detectionScriptNotApplicableDeviceCount) { - "$($run.detectionScriptNotApplicableDeviceCount) device(s) not applicable" }) + DeviceNotes = @(if ($notApplicable) { "$notApplicable device(s) not applicable" }) } $reports.Add((ConvertTo-Report @reportSplat)) } @@ -233,12 +256,20 @@ function Get-IntuneScriptHealth { $scripts = '/beta/deviceManagement/deviceManagementScripts' $fields = 'id,displayName,runAsAccount,lastModifiedDateTime' foreach ($summary in (Get-WantedPolicy -Uri "$scripts`?`$select=id,displayName")) { - $policy = Invoke-IslGraphRequest -Uri "$scripts/$($summary.id)?`$select=$fields&`$expand=assignments" - $run = Get-RunSummary -Uri "$scripts/$($summary.id)/runSummary" + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $policy = Invoke-IslGraphRequest -Uri "$scripts/$summaryId`?`$select=$fields&`$expand=assignments" + $run = Get-RunSummary -Uri "$scripts/$summaryId/runSummary" $reportSplat = @{ - PolicyKind = 'PlatformScript'; Policy = $policy; Context = "$($policy.runAsAccount)" - Succeeded = [int]$run.successDeviceCount; Failed = [int]$run.errorDeviceCount - Detected = 0; Pending = 0; LastRun = $null; HasRunState = [bool]$run; DeviceNotes = @() + PolicyKind = 'PlatformScript' + Policy = $policy + Context = "$(Get-IslPropertyValue -InputObject $policy -Name 'runAsAccount')" + Succeeded = [int](Get-IslPropertyValue -InputObject $run -Name 'successDeviceCount') + Failed = [int](Get-IslPropertyValue -InputObject $run -Name 'errorDeviceCount') + Detected = 0 + Pending = 0 + LastRun = $null + HasRunState = [bool]$run + DeviceNotes = @() } $reports.Add((ConvertTo-Report @reportSplat)) } @@ -249,15 +280,23 @@ function Get-IntuneScriptHealth { $listUri = "$apps`?`$filter=isof('microsoft.graph.win32LobApp')&`$select=id,displayName" foreach ($summary in (Get-WantedPolicy -Uri $listUri)) { # installExperience belongs to the derived type, and $select on the base entity refuses it - $app = Invoke-IslGraphRequest -Uri "$apps/$($summary.id)?`$expand=assignments" - $row = $appInstall["$($app.id)"] + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $app = Invoke-IslGraphRequest -Uri "$apps/$summaryId`?`$expand=assignments" + # An app that no device has reported on has no row in the export + $row = $appInstall["$(Get-IslPropertyValue -InputObject $app -Name 'id')"] + $installExperience = Get-IslPropertyValue -InputObject $app -Name 'installExperience' + $notApplicable = [int](Get-IslPropertyValue -InputObject $row -Name 'NotApplicableDeviceCount') $reportSplat = @{ - PolicyKind = 'Win32App'; Policy = $app; Context = "$($app.installExperience.runAsAccount)" - Succeeded = [int]$row.InstalledDeviceCount; Failed = [int]$row.FailedDeviceCount - Detected = 0; Pending = [int]$row.PendingInstallDeviceCount; LastRun = $null + PolicyKind = 'Win32App' + Policy = $app + Context = "$(Get-IslPropertyValue -InputObject $installExperience -Name 'runAsAccount')" + Succeeded = [int](Get-IslPropertyValue -InputObject $row -Name 'InstalledDeviceCount') + Failed = [int](Get-IslPropertyValue -InputObject $row -Name 'FailedDeviceCount') + Detected = 0 + Pending = [int](Get-IslPropertyValue -InputObject $row -Name 'PendingInstallDeviceCount') + LastRun = $null HasRunState = [bool]$row - DeviceNotes = @(if ([int]$row.NotApplicableDeviceCount) { - "$($row.NotApplicableDeviceCount) device(s) not applicable" }) + DeviceNotes = @(if ($notApplicable) { "$notApplicable device(s) not applicable" }) } $reports.Add((ConvertTo-Report @reportSplat)) } diff --git a/Public/Invoke-IntuneWin32AppTest.ps1 b/Public/Invoke-IntuneWin32AppTest.ps1 index 3e9afe9..2aee77b 100644 --- a/Public/Invoke-IntuneWin32AppTest.ps1 +++ b/Public/Invoke-IntuneWin32AppTest.ps1 @@ -77,11 +77,13 @@ function Invoke-IntuneWin32AppTest { $null = Resolve-Path -LiteralPath $ContentPath -ErrorAction Stop foreach ($related in @($DependsOn) + @($Supersedes)) { if (-not $related) { continue } - if (-not $related.Name) { throw 'Every -DependsOn and -Supersedes entry needs a Name' } - if (-not $related.DetectionPath -and -not $related.DetectionRule) { - throw "$($related.Name) needs a DetectionPath, DetectionRule entries, or both" + if (-not $related['Name']) { throw 'Every -DependsOn and -Supersedes entry needs a Name' } + if (-not $related['DetectionPath'] -and -not $related['DetectionRule']) { + throw "$($related['Name']) needs a DetectionPath, DetectionRule entries, or both" + } + if ($related['ContentPath']) { + $null = Resolve-Path -LiteralPath $related['ContentPath'] -ErrorAction Stop } - if ($related.ContentPath) { $null = Resolve-Path -LiteralPath $related.ContentPath -ErrorAction Stop } } $warnings = [System.Collections.Generic.List[string]]::new() @@ -241,10 +243,12 @@ function Invoke-IntuneWin32AppTest { # (W32-DEPD-PARENT) if (-not $status -and $Intent -eq 'Install') { foreach ($dependency in @($DependsOn | Where-Object { $_ })) { - $type = if ($dependency.Type) { "$($dependency.Type)" } else { 'autoInstall' } - $name = "$($dependency.Name)" + $type = if ($dependency['Type']) { "$($dependency['Type'])" } else { 'autoInstall' } + $name = "$($dependency['Name'])" $detect = @{ - Path = $dependency.DetectionPath; Rule = $dependency.DetectionRule; Label = " for dependency $name" + Path = $dependency['DetectionPath'] + Rule = $dependency['DetectionRule'] + Label = " for dependency $name" } $childPre = Invoke-DetectionPass -Phase 'Pre' @detect $childInstall = $null @@ -252,12 +256,14 @@ function Invoke-IntuneWin32AppTest { $childStatus = if ($childPre.TimedOut) { 'TimedOut' } elseif ($childPre.Detected) { 'Installed' } elseif ($type -ne 'autoInstall') { 'Not detected (detect-only dependency)' } - elseif (-not $dependency.InstallCommand -or -not $dependency.ContentPath) { + elseif (-not $dependency['InstallCommand'] -or -not $dependency['ContentPath']) { 'Not detected (no InstallCommand or ContentPath)' } else { $childRun = @{ - Phase = 'install'; Content = $dependency.ContentPath; CommandLine = $dependency.InstallCommand + Phase = 'install' + Content = $dependency['ContentPath'] + CommandLine = $dependency['InstallCommand'] } $childInstall = Invoke-ContentCommand @childRun switch (Get-Outcome -Run $childInstall) { @@ -291,10 +297,12 @@ function Invoke-IntuneWin32AppTest { # installed (W32-SUP-OLD-A) if (-not $status -and $Intent -eq 'Install') { foreach ($old in @($Supersedes | Where-Object { $_ })) { - $type = if ($old.Type) { "$($old.Type)" } else { 'update' } - $name = "$($old.Name)" + $type = if ($old['Type']) { "$($old['Type'])" } else { 'update' } + $name = "$($old['Name'])" $detect = @{ - Path = $old.DetectionPath; Rule = $old.DetectionRule; Label = " for superseded app $name" + Path = $old['DetectionPath'] + Rule = $old['DetectionRule'] + Label = " for superseded app $name" } $oldPre = Invoke-DetectionPass -Phase 'Pre' @detect $oldUninstall = $null @@ -302,11 +310,15 @@ function Invoke-IntuneWin32AppTest { $oldStatus = if ($oldPre.TimedOut) { 'TimedOut' } elseif (-not $oldPre.Detected) { 'Not installed' } elseif ($type -ne 'replace') { 'Installed (left in place by update)' } - elseif (-not $old.UninstallCommand -or -not $old.ContentPath) { + elseif (-not $old['UninstallCommand'] -or -not $old['ContentPath']) { 'Installed (no UninstallCommand or ContentPath)' } else { - $oldRun = @{ Phase = 'uninstall'; Content = $old.ContentPath; CommandLine = $old.UninstallCommand } + $oldRun = @{ + Phase = 'uninstall' + Content = $old['ContentPath'] + CommandLine = $old['UninstallCommand'] + } $oldUninstall = Invoke-ContentCommand @oldRun switch (Get-Outcome -Run $oldUninstall) { 'timedOut' { 'TimedOut' } diff --git a/Public/Test-IntuneDeployedScript.ps1 b/Public/Test-IntuneDeployedScript.ps1 index 5820eda..8e52c11 100644 --- a/Public/Test-IntuneDeployedScript.ps1 +++ b/Public/Test-IntuneDeployedScript.ps1 @@ -53,10 +53,11 @@ function Test-IntuneDeployedScript { function Test-Wanted { param($Policy) - $displayName = "$($Policy.displayName)" + $displayName = "$(Get-IslPropertyValue -InputObject $Policy -Name 'displayName')" + $policyId = "$(Get-IslPropertyValue -InputObject $Policy -Name 'id')" # -Id alone selects by id: -Name's default of '*' only counts when -Name was given or -Id was not $byName = ($nameGiven -or -not $Id) -and @($Name | Where-Object { $displayName -like $_ }).Count -gt 0 - $byId = $Id -and "$($Policy.id)" -in $Id + $byId = $Id -and $policyId -in $Id $byName -or $byId } @@ -65,8 +66,8 @@ function Test-IntuneDeployedScript { [pscustomobject]@{ PSTypeName = 'IntuneScriptLab.DeploymentFinding' Kind = $PolicyKind - PolicyName = "$($Policy.displayName)" - PolicyId = "$($Policy.id)" + PolicyName = "$(Get-IslPropertyValue -InputObject $Policy -Name 'displayName')" + PolicyId = "$(Get-IslPropertyValue -InputObject $Policy -Name 'id')" Role = $Role RuleName = $Finding.RuleName Severity = $Finding.Severity @@ -98,8 +99,10 @@ function Test-IntuneDeployedScript { $RunAsAccount, $RunAs32Bit, $EnforceSignatureCheck ) if (-not $Content) { return } - $safeName = [regex]::Replace("$($Policy.displayName)", '[^\w.-]', '_') - $folder = Join-Path -Path $workFolder -ChildPath "$PolicyKind\$safeName-$($Policy.id)" + $policyName = "$(Get-IslPropertyValue -InputObject $Policy -Name 'displayName')" + $policyId = "$(Get-IslPropertyValue -InputObject $Policy -Name 'id')" + $safeName = [regex]::Replace($policyName, '[^\w.-]', '_') + $folder = Join-Path -Path $workFolder -ChildPath "$PolicyKind\$safeName-$policyId" $null = New-Item -ItemType Directory -Path $folder -Force $file = Join-Path -Path $folder -ChildPath "$Role.ps1" # Byte for byte: the encoding rule needs to see the BOM, or its absence, as the tenant stores it @@ -117,7 +120,7 @@ function Test-IntuneDeployedScript { if ($settingsGiven) { $testSplat.Settings = $Settings } if ($IncludeRule) { $testSplat.IncludeRule = $IncludeRule } if ($ExcludeRule) { $testSplat.ExcludeRule = $ExcludeRule } - Write-Verbose "$PolicyKind '$($Policy.displayName)' $Role as $ScriptType, $context, $architecture" + Write-Verbose "$PolicyKind '$policyName' $Role as $ScriptType, $context, $architecture" foreach ($finding in (Test-IntuneScript @testSplat)) { ConvertTo-DeploymentFinding -PolicyKind $PolicyKind -Policy $Policy -Role $Role -Finding $finding } @@ -171,20 +174,22 @@ function Test-IntuneDeployedScript { # device can match is a warning (the assignment silently reaches nobody, or everybody) function Test-AssignmentFilter { param([string]$PolicyKind, $Policy) - foreach ($assignment in @($Policy.assignments)) { - $target = $assignment.target - $filterId = "$($target.deviceAndAppManagementAssignmentFilterId)" - $filterType = "$($target.deviceAndAppManagementAssignmentFilterType)" + foreach ($assignment in @(Get-IslPropertyValue -InputObject $Policy -Name 'assignments')) { + # An assignment without a filter carries neither key, or a type of none + $target = Get-IslPropertyValue -InputObject $assignment -Name 'target' + $filterId = Get-IslPropertyValue -InputObject $target -Name 'deviceAndAppManagementAssignmentFilterId' + $filterTypeName = 'deviceAndAppManagementAssignmentFilterType' + $filterType = "$(Get-IslPropertyValue -InputObject $target -Name $filterTypeName)" if (-not $filterId -or $filterType -eq 'none') { continue } $filter = Get-AssignmentFilter -FilterId $filterId if (-not $filter) { continue } - $label = "Filter '$($filter.displayName)' ($filterType)" - $parsed = ConvertFrom-IslFilterRule -Rule "$($filter.rule)" + $filterRule = "$(Get-IslPropertyValue -InputObject $filter -Name 'rule')" + $label = "Filter '$(Get-IslPropertyValue -InputObject $filter -Name 'displayName')' ($filterType)" + $parsed = ConvertFrom-IslFilterRule -Rule $filterRule if ($parsed.Error) { $unreadSplat = @{ PolicyKind = $PolicyKind; Policy = $Policy; Rule = 'IslFilterIssue'; Severity = 'Information' - Message = "$label uses syntax this evaluator does not read ($($parsed.Error)): " + - "$($filter.rule)" + Message = "$label uses syntax this evaluator does not read ($($parsed.Error)): $filterRule" Evidence = $filterEvidence } ConvertTo-PolicyFinding @unreadSplat @@ -196,7 +201,7 @@ function Test-IntuneDeployedScript { $message = Get-IslFilterWarningMessage -Warning $warning -Mode $mode $issueSplat = @{ PolicyKind = $PolicyKind; Policy = $Policy; Rule = 'IslFilterIssue'; Severity = $severity - Message = "${label}: $message. Rule: $($filter.rule)" + Message = "${label}: $message. Rule: $filterRule" Evidence = $filterEvidence } ConvertTo-PolicyFinding @issueSplat @@ -210,9 +215,11 @@ function Test-IntuneDeployedScript { # device group is skipped on Entra registered devices function Test-Assignment { param([string]$PolicyKind, $Policy, $RunAsAccount) - $assignments = @($Policy.assignments | Where-Object { $_ }) + $assignments = @(Get-IslPropertyValue -InputObject $Policy -Name 'assignments' | Where-Object { $_ }) + $exclusionType = '#microsoft.graph.exclusionGroupAssignmentTarget' $includes = @($assignments | Where-Object { - "$($_.target.'@odata.type')" -ne '#microsoft.graph.exclusionGroupAssignmentTarget' + $target = Get-IslPropertyValue -InputObject $_ -Name 'target' + "$(Get-IslPropertyValue -InputObject $target -Name '@odata.type')" -ne $exclusionType }) if ($includes.Count -eq 0) { $what = if ($assignments.Count -eq 0) { 'No assignment' } else { 'Only exclusion assignments' } @@ -226,14 +233,19 @@ function Test-IntuneDeployedScript { ConvertTo-PolicyFinding @noneSplat } foreach ($assignment in $includes) { - $schedule = $assignment.runSchedule - if ("$($schedule.'@odata.type')" -ne '#microsoft.graph.deviceHealthScriptRunOnceSchedule') { continue } - $stamp = "$($schedule.date) $($schedule.time)" + # Only a remediation's assignment has a schedule, and only a run-once one has a date + $schedule = Get-IslPropertyValue -InputObject $assignment -Name 'runSchedule' + $scheduleType = "$(Get-IslPropertyValue -InputObject $schedule -Name '@odata.type')" + if ($scheduleType -ne '#microsoft.graph.deviceHealthScriptRunOnceSchedule') { continue } + $scheduleDate = Get-IslPropertyValue -InputObject $schedule -Name 'date' + $scheduleTime = Get-IslPropertyValue -InputObject $schedule -Name 'time' + $useUtc = [bool](Get-IslPropertyValue -InputObject $schedule -Name 'useUtc') + $stamp = "$scheduleDate $scheduleTime" $at = [datetime]::MinValue if (-not [datetime]::TryParse($stamp, [cultureinfo]::InvariantCulture, 'None', [ref]$at)) { continue } - $now = if ([bool]$schedule.useUtc) { [datetime]::UtcNow } else { [datetime]::Now } + $now = if ($useUtc) { [datetime]::UtcNow } else { [datetime]::Now } if ($at -ge $now) { continue } - $zone = if ([bool]$schedule.useUtc) { 'UTC' } else { 'device local time' } + $zone = if ($useUtc) { 'UTC' } else { 'device local time' } $when = $at.ToString('yyyy-MM-dd HH:mm:ss') $pastSplat = @{ PolicyKind = $PolicyKind; Policy = $Policy; Rule = 'IslScheduleIssue'; Severity = 'Information' @@ -247,11 +259,12 @@ function Test-IntuneDeployedScript { } if ("$RunAsAccount" -ne 'user') { return } $deviceGroups = foreach ($assignment in $includes) { - $target = $assignment.target - $type = "$($target.'@odata.type')" + $target = Get-IslPropertyValue -InputObject $assignment -Name 'target' + $type = "$(Get-IslPropertyValue -InputObject $target -Name '@odata.type')" if ($type -eq '#microsoft.graph.allDevicesAssignmentTarget') { 'all devices'; continue } if ($type -ne '#microsoft.graph.groupAssignmentTarget') { continue } - if (Test-DeviceGroup -GroupId "$($target.groupId)") { "$($target.groupId)" } + $groupId = "$(Get-IslPropertyValue -InputObject $target -Name 'groupId')" + if (Test-DeviceGroup -GroupId $groupId) { $groupId } } if ($deviceGroups) { $userSplat = @{ @@ -276,20 +289,27 @@ function Test-IntuneDeployedScript { if ('Remediation' -in $Kind) { $remediations = '/beta/deviceManagement/deviceHealthScripts' foreach ($summary in (Get-WantedPolicy -Uri "$remediations`?`$select=id,displayName")) { - $policy = Invoke-IslGraphRequest -Uri "$remediations/$($summary.id)?`$expand=assignments" + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $policy = Invoke-IslGraphRequest -Uri "$remediations/$summaryId`?`$expand=assignments" + $runAsAccount = Get-IslPropertyValue -InputObject $policy -Name 'runAsAccount' $policySettings = @{ - RunAsAccount = $policy.runAsAccount; RunAs32Bit = $policy.runAs32Bit - EnforceSignatureCheck = $policy.enforceSignatureCheck + RunAsAccount = $runAsAccount + RunAs32Bit = Get-IslPropertyValue -InputObject $policy -Name 'runAs32Bit' + EnforceSignatureCheck = Get-IslPropertyValue -InputObject $policy -Name 'enforceSignatureCheck' } $detectSplat = @{ - PolicyKind = 'Remediation'; Policy = $policy; Role = 'detection'; ScriptType = 'Detection' - Content = $policy.detectionScriptContent + PolicyKind = 'Remediation' + Policy = $policy + Role = 'detection' + ScriptType = 'Detection' + Content = Get-IslPropertyValue -InputObject $policy -Name 'detectionScriptContent' } Test-PolicyScript @detectSplat @policySettings - if ($policy.remediationScriptContent) { + $remediationContent = Get-IslPropertyValue -InputObject $policy -Name 'remediationScriptContent' + if ($remediationContent) { $remediateSplat = @{ PolicyKind = 'Remediation'; Policy = $policy; Role = 'remediation' - ScriptType = 'Remediation'; Content = $policy.remediationScriptContent + ScriptType = 'Remediation'; Content = $remediationContent } Test-PolicyScript @remediateSplat @policySettings } @@ -304,7 +324,7 @@ function Test-IntuneDeployedScript { } ConvertTo-PolicyFinding @noteSplat } - Test-Assignment -PolicyKind 'Remediation' -Policy $policy -RunAsAccount $policy.runAsAccount + Test-Assignment -PolicyKind 'Remediation' -Policy $policy -RunAsAccount $runAsAccount Test-AssignmentFilter -PolicyKind 'Remediation' -Policy $policy } } @@ -312,14 +332,21 @@ function Test-IntuneDeployedScript { if ('PlatformScript' -in $Kind) { $scripts = '/beta/deviceManagement/deviceManagementScripts' foreach ($summary in (Get-WantedPolicy -Uri "$scripts`?`$select=id,displayName")) { - $policy = Invoke-IslGraphRequest -Uri "$scripts/$($summary.id)?`$expand=assignments" + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $policy = Invoke-IslGraphRequest -Uri "$scripts/$summaryId`?`$expand=assignments" + $runAsAccount = Get-IslPropertyValue -InputObject $policy -Name 'runAsAccount' $scriptSplat = @{ - PolicyKind = 'PlatformScript'; Policy = $policy; Role = 'script'; ScriptType = 'PlatformScript' - Content = $policy.scriptContent; RunAsAccount = $policy.runAsAccount - RunAs32Bit = $policy.runAs32Bit; EnforceSignatureCheck = $policy.enforceSignatureCheck + PolicyKind = 'PlatformScript' + Policy = $policy + Role = 'script' + ScriptType = 'PlatformScript' + Content = Get-IslPropertyValue -InputObject $policy -Name 'scriptContent' + RunAsAccount = $runAsAccount + RunAs32Bit = Get-IslPropertyValue -InputObject $policy -Name 'runAs32Bit' + EnforceSignatureCheck = Get-IslPropertyValue -InputObject $policy -Name 'enforceSignatureCheck' } Test-PolicyScript @scriptSplat - Test-Assignment -PolicyKind 'PlatformScript' -Policy $policy -RunAsAccount $policy.runAsAccount + Test-Assignment -PolicyKind 'PlatformScript' -Policy $policy -RunAsAccount $runAsAccount Test-AssignmentFilter -PolicyKind 'PlatformScript' -Policy $policy } } @@ -328,27 +355,38 @@ function Test-IntuneDeployedScript { $apps = '/beta/deviceAppManagement/mobileApps' $listUri = "$apps`?`$filter=isof('microsoft.graph.win32LobApp')&`$select=id,displayName" foreach ($summary in (Get-WantedPolicy -Uri $listUri)) { - $app = Invoke-IslGraphRequest -Uri "$apps/$($summary.id)?`$expand=assignments" + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $app = Invoke-IslGraphRequest -Uri "$apps/$summaryId`?`$expand=assignments" $ruleIndex = 0 - foreach ($rule in @($app.detectionRules)) { + foreach ($rule in @(Get-IslPropertyValue -InputObject $app -Name 'detectionRules')) { $ruleIndex++ - $ruleType = "$($rule.'@odata.type')" + # Each kind of rule has its own members: a script rule has no detectionType, + # a file rule no scriptContent + $ruleType = "$(Get-IslPropertyValue -InputObject $rule -Name '@odata.type')" + $detectionType = "$(Get-IslPropertyValue -InputObject $rule -Name 'detectionType')" if ($ruleType -eq '#microsoft.graph.win32LobAppPowerShellScriptDetection') { + $signatureCheck = Get-IslPropertyValue -InputObject $rule -Name 'enforceSignatureCheck' $detectSplat = @{ - PolicyKind = 'Win32App'; Policy = $app; Role = 'detection' - ScriptType = 'Win32Detection'; Content = $rule.scriptContent - RunAsAccount = 'system'; RunAs32Bit = $rule.runAs32Bit - EnforceSignatureCheck = $rule.enforceSignatureCheck + PolicyKind = 'Win32App' + Policy = $app + Role = 'detection' + ScriptType = 'Win32Detection' + Content = Get-IslPropertyValue -InputObject $rule -Name 'scriptContent' + RunAsAccount = 'system' + RunAs32Bit = Get-IslPropertyValue -InputObject $rule -Name 'runAs32Bit' + EnforceSignatureCheck = $signatureCheck } Test-PolicyScript @detectSplat } elseif ($ruleType -eq '#microsoft.graph.win32LobAppFileSystemDetection' -and - "$($rule.detectionType)" -eq 'doesNotExist') { + $detectionType -eq 'doesNotExist') { + $rulePath = Get-IslPropertyValue -InputObject $rule -Name 'path' + $ruleFile = Get-IslPropertyValue -InputObject $rule -Name 'fileOrFolderName' $ruleSplat = @{ PolicyKind = 'Win32App'; Policy = $app; Rule = 'IslDetectionRuleIssue' Severity = 'Error' Message = "Detection rule $ruleIndex is a file rule with detectionType " + - "doesNotExist ($($rule.path)\$($rule.fileOrFolderName)): the agent does " + + "doesNotExist ($rulePath\$ruleFile): the agent does " + 'not evaluate it. Use a registry doesNotExist rule or a script' Evidence = 'File doesNotExist: on a missing file the app was not detected ' + 'and the install ran; on a present file the detection ended "Invalid ' + @@ -358,25 +396,35 @@ function Test-IntuneDeployedScript { ConvertTo-PolicyFinding @ruleSplat } } - foreach ($rule in @($app.requirementRules)) { - if ("$($rule.'@odata.type')" -ne '#microsoft.graph.win32LobAppPowerShellScriptRequirement') { + foreach ($rule in @(Get-IslPropertyValue -InputObject $app -Name 'requirementRules')) { + $ruleType = "$(Get-IslPropertyValue -InputObject $rule -Name '@odata.type')" + if ($ruleType -ne '#microsoft.graph.win32LobAppPowerShellScriptRequirement') { continue } + $signatureCheck = Get-IslPropertyValue -InputObject $rule -Name 'enforceSignatureCheck' $requirementSplat = @{ - PolicyKind = 'Win32App'; Policy = $app; Role = 'requirement' - ScriptType = 'Win32Requirement'; Content = $rule.scriptContent - RunAsAccount = $rule.runAsAccount; RunAs32Bit = $rule.runAs32Bit - EnforceSignatureCheck = $rule.enforceSignatureCheck + PolicyKind = 'Win32App' + Policy = $app + Role = 'requirement' + ScriptType = 'Win32Requirement' + Content = Get-IslPropertyValue -InputObject $rule -Name 'scriptContent' + RunAsAccount = Get-IslPropertyValue -InputObject $rule -Name 'runAsAccount' + RunAs32Bit = Get-IslPropertyValue -InputObject $rule -Name 'runAs32Bit' + EnforceSignatureCheck = $signatureCheck } Test-PolicyScript @requirementSplat } - if ("$($app.installExperience.runAsAccount)" -eq 'user') { - $deviceGroups = foreach ($assignment in @($app.assignments)) { - $target = $assignment.target - $type = "$($target.'@odata.type')" + $installExperience = Get-IslPropertyValue -InputObject $app -Name 'installExperience' + $installContext = "$(Get-IslPropertyValue -InputObject $installExperience -Name 'runAsAccount')" + if ($installContext -eq 'user') { + $appAssignments = @(Get-IslPropertyValue -InputObject $app -Name 'assignments') + $deviceGroups = foreach ($assignment in $appAssignments) { + $target = Get-IslPropertyValue -InputObject $assignment -Name 'target' + $type = "$(Get-IslPropertyValue -InputObject $target -Name '@odata.type')" if ($type -eq '#microsoft.graph.allDevicesAssignmentTarget') { 'all devices'; continue } if ($type -ne '#microsoft.graph.groupAssignmentTarget') { continue } - if (Test-DeviceGroup -GroupId "$($target.groupId)") { "$($target.groupId)" } + $groupId = "$(Get-IslPropertyValue -InputObject $target -Name 'groupId')" + if (Test-DeviceGroup -GroupId $groupId) { $groupId } } if ($deviceGroups) { $assignmentSplat = @{ diff --git a/Tests/Invoke-Tests.ps1 b/Tests/Invoke-Tests.ps1 index 9fb5739..421d2de 100644 --- a/Tests/Invoke-Tests.ps1 +++ b/Tests/Invoke-Tests.ps1 @@ -181,9 +181,9 @@ if ($CodeCoverage) { } # Pester runs the test files in scopes below this one, so they would inherit this script's strict -# mode, and when the script is started with -File this scope is the global one, which the -# module's functions see as well. The suites, the validation kit and the module are not yet -# written for strict mode (#63, #70, #71), so it is off for the run and on again after it. +# mode. The module sets its own in its root module and does not depend on this one, but the +# suites and the validation kit are not yet written for strict mode (#70, #71), so it is off for +# the run and on again after it. Set-StrictMode -Off try { $result = Invoke-Pester -Configuration $configuration diff --git a/Tests/TestHelpers/TestHelpers.ps1 b/Tests/TestHelpers/TestHelpers.ps1 index 6fa479e..aa89505 100644 --- a/Tests/TestHelpers/TestHelpers.ps1 +++ b/Tests/TestHelpers/TestHelpers.ps1 @@ -130,3 +130,55 @@ function Set-Win32FixtureScript { [System.IO.File]::WriteAllText($Fixture.Detection, $DetectBody, $utf8Bom) } } + + +function ConvertTo-FakeRunResult { + <# + .SYNOPSIS + Completes a partial run result with every member the real one has. + + .DESCRIPTION + A mock of Invoke-IslScriptRun or Invoke-IslProcess names only the members its test is about. + The commands read the others too, and under strict mode a read of a member that is not there + is an error, so the fake gets the rest with the values of an uneventful run as SYSTEM. + + .PARAMETER Member + The members the test sets, by name. Each replaces the default of that name. + + .EXAMPLE + ConvertTo-FakeRunResult @{ ExitCode = 1; StdOut = 'missing' } + + A run that exited 1 after writing one line, with every other member at its default. + + .INPUTS + None. + + .OUTPUTS + System.Management.Automation.PSCustomObject. The fake run result. + #> + [CmdletBinding()] + [OutputType([System.Management.Automation.PSCustomObject])] + param( + [Parameter(Mandatory, Position = 0)] + [hashtable]$Member + ) + $result = [ordered]@{ + Phase = 'detection' + ScriptPath = '' + Host = 'powershell.exe' + Architecture = 'x64' + Context = 'System' + RunAs = 'NT AUTHORITY\SYSTEM (Service)' + UserName = 'NT AUTHORITY\SYSTEM' + LogonType = 'Service' + ExitCode = 0 + TimedOut = $false + StdOut = '' + StdErr = '' + Duration = [timespan]::Zero + } + foreach ($key in $Member.Keys) { + $result[$key] = $Member[$key] + } + [pscustomobject]$result +} diff --git a/Tests/Unit/Module.Contract.Tests.ps1 b/Tests/Unit/Module.Contract.Tests.ps1 index 908ad25..9a67e4b 100644 --- a/Tests/Unit/Module.Contract.Tests.ps1 +++ b/Tests/Unit/Module.Contract.Tests.ps1 @@ -172,6 +172,114 @@ Describe 'IntuneScriptLab module contract' -Tag 'Unit', 'Contract' { Get-Command @commandSplat | Should-BeNull } + It 'runs its functions under strict mode' { + # Set once at the top of the root module: a read of a variable that was never assigned is + # an error in every function, where it used to be a silent $null + { InModuleScope IntuneScriptLab { $null = $neverAssignedAnywhere } } | + Should-Throw -ExceptionMessage '*neverAssignedAnywhere*' + } + + Context 'When a part of the module cannot be loaded' { + BeforeAll { + # Each copy is imported in a new process: a second module of this name imported here + # would stand beside the one under test for the rest of the run + $script:Shell = (Get-Process -Id $PID).Path + function script:Import-ModuleCopy { + <# + .SYNOPSIS + Copies the module under TestDrive, changes the copy and imports it in a new process. + + .DESCRIPTION + The import is a plain one, as a user types it. Returns the exit code of that process + and what it wrote: 'imported' when the module is loaded afterwards, and otherwise + the message of the error that ended the import, followed by 'not imported'. + + .PARAMETER Name + The folder under TestDrive that holds this copy. + + .PARAMETER Change + Changes the copy before it is imported. It receives the folder of the copy. + + .EXAMPLE + Import-ModuleCopy -Name 'Intact' -Change { } + + Imports an unchanged copy. + + .INPUTS + None. + + .OUTPUTS + System.Management.Automation.PSCustomObject. ExitCode and Output of the process. + #> + [CmdletBinding()] + [OutputType([System.Management.Automation.PSCustomObject])] + param( + [Parameter(Mandatory)] + [string]$Name, + + [Parameter(Mandatory)] + [scriptblock]$Change + ) + $copy = Join-Path (Join-Path $TestDrive $Name) 'IntuneScriptLab' + $null = New-Item -ItemType Directory -Path $copy -Force + $parts = @( + 'IntuneScriptLab.psd1' + 'IntuneScriptLab.psm1' + 'IntuneScriptLab.Format.ps1xml' + 'Private' + 'Public' + ) + foreach ($part in $parts) { + Copy-Item -LiteralPath (Join-Path $script:ModuleRoot $part) -Destination $copy -Recurse + } + & $Change $copy + # The child reports the failure on its output: a native error stream read under an + # error preference of Stop, which a CI step sets, would end the test instead + $manifest = Join-Path $copy 'IntuneScriptLab.psd1' + $import = "try { Import-Module '$manifest' } catch { 'error: ' + `$_.Exception.Message }" + $report = "if (Get-Module -Name IntuneScriptLab) { 'imported' } else { 'not imported'; exit 1 }" + $command = "$import; $report" + $arguments = @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', $command) + $output = & $script:Shell @arguments + [pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = "$output" } + } + } + + It 'imports an intact copy, so that the failures below come from what was broken' { + $result = Import-ModuleCopy -Name 'Intact' -Change { } + $result.Output | Should-Be 'imported' + $result.ExitCode | Should-Be 0 + } + + It 'fails the import when a function file ' -ForEach @( + @{ Problem = 'throws while it loads'; Body = "throw 'this file cannot load'" } + @{ Problem = 'does not parse'; Body = 'function Get-IslBrokenFile {' } + ) { + # The file that does not parse is the case the loader's rethrow exists for: dot-sourcing + # it is an error that ends only that statement, and the import used to carry on and + # leave the module loaded without the commands of that file + $result = Import-ModuleCopy -Name ($Problem -replace '\W', '-') -Change { + param($copy) + $broken = Join-Path $copy 'Private\Get-IslBrokenFile.ps1' + Set-Content -LiteralPath $broken -Value $Body -Encoding ascii + } + $result.ExitCode | Should-Be 1 + $result.Output | Should-BeLikeString 'error: *not imported' + } + + It 'fails the import when the folder is missing' -ForEach @( + @{ Folder = 'Private\Rules' } + @{ Folder = 'Public' } + ) { + $result = Import-ModuleCopy -Name ($Folder -replace '\W', '-') -Change { + param($copy) + Remove-Item -LiteralPath (Join-Path $copy $Folder) -Recurse -Force + } + $result.ExitCode | Should-Be 1 + $result.Output | Should-BeLikeString "error: *$($Folder -replace '^.*\\')*is missing*not imported" + } + } + It 'loads on Windows PowerShell 5.1 as well as PowerShell 7' { # The rules reference PowerShell 7 AST types by name only; a hard type reference would # break import on 5.1, which is where many admins will run this. diff --git a/Tests/Unit/Private/Get-IslPropertyValue.Tests.ps1 b/Tests/Unit/Private/Get-IslPropertyValue.Tests.ps1 new file mode 100644 index 0000000..d5c8486 --- /dev/null +++ b/Tests/Unit/Private/Get-IslPropertyValue.Tests.ps1 @@ -0,0 +1,134 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The accessor for data with optional members. A Graph reply is a dictionary or an object + depending on how it was read, and under the module's strict mode a plain read of a member that + is not there is an error, so the same reads are checked against both shapes. +#> + +BeforeDiscovery { + $script:Shapes = @( + @{ + Shape = 'a hashtable' + Data = @{ id = 'rem-a'; runAs32Bit = $false; deviceCount = 0; '@odata.type' = '#policy' } + } + @{ + Shape = 'an ordered dictionary' + Data = [ordered]@{ id = 'rem-a'; runAs32Bit = $false; deviceCount = 0; '@odata.type' = '#policy' } + } + @{ + Shape = 'an object' + Data = [pscustomobject]@{ + id = 'rem-a'; runAs32Bit = $false; deviceCount = 0; '@odata.type' = '#policy' + } + } + ) +} + +BeforeAll { + if (-not (Get-Module -Name IntuneScriptLab)) { + $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + Import-Module (Join-Path $moduleRoot 'IntuneScriptLab.psd1') + } +} + +Describe 'Get-IslPropertyValue' -Tag 'Unit', 'Private' { + + Context 'Parameter Validation' { + It 'declares Name as mandatory and lets InputObject be omitted or null' { + InModuleScope IntuneScriptLab { + $command = Get-Command -Name Get-IslPropertyValue + $command | Should-HaveParameter -ParameterName 'Name' -Type ([string]) -Mandatory + $declared = @($command.Parameters['InputObject'].Attributes | + Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] }) + $declared.Count | Should-Be 1 + $declared[0].Mandatory | Should-BeFalse + @(Get-IslPropertyValue -InputObject $null -Name 'id').Count | Should-Be 0 + @(Get-IslPropertyValue -Name 'id').Count | Should-Be 0 + } + } + } + + Context 'Core Functionality' { + It 'reads a value from ' -ForEach $script:Shapes { + InModuleScope IntuneScriptLab -Parameters @{ Data = $Data } { + Get-IslPropertyValue -InputObject $Data -Name 'id' | Should-Be 'rem-a' + Get-IslPropertyValue -InputObject $Data -Name '@odata.type' | Should-Be '#policy' + Get-IslPropertyValue -InputObject $Data -Name 'ID' | Should-Be 'rem-a' + } + } + + It 'returns a value that is false or zero from , not nothing' -ForEach $script:Shapes { + InModuleScope IntuneScriptLab -Parameters @{ Data = $Data } { + $flag = @(Get-IslPropertyValue -InputObject $Data -Name 'runAs32Bit') + $flag.Count | Should-Be 1 + $flag[0] | Should-BeFalse + $count = @(Get-IslPropertyValue -InputObject $Data -Name 'deviceCount') + $count.Count | Should-Be 1 + $count[0] | Should-Be 0 + } + } + + It 'returns nothing for a member that does not have' -ForEach $script:Shapes { + InModuleScope IntuneScriptLab -Parameters @{ Data = $Data } { + @(Get-IslPropertyValue -InputObject $Data -Name 'remediationScriptContent').Count | Should-Be 0 + $value = Get-IslPropertyValue -InputObject $Data -Name 'remediationScriptContent' + $value | Should-BeNull + } + } + + It 'reads the entry of a dictionary, never the dictionary''s own property of that name' { + InModuleScope IntuneScriptLab { + # Member syntax reads Count and Keys from the hashtable itself when it has no such entry + @(Get-IslPropertyValue -InputObject @{ id = 'rem-a' } -Name 'Count').Count | Should-Be 0 + @(Get-IslPropertyValue -InputObject @{ id = 'rem-a' } -Name 'Keys').Count | Should-Be 0 + Get-IslPropertyValue -InputObject @{ id = 'rem-a'; Count = 5 } -Name 'Count' | Should-Be 5 + } + } + + It 'hands a list back as its elements, and an empty or missing list as nothing' { + InModuleScope IntuneScriptLab { + $page = @{ value = @(@{ id = 'a' }, @{ id = 'b' }); empty = @() } + $items = @(Get-IslPropertyValue -InputObject $page -Name 'value') + $items.Count | Should-Be 2 + $items[1]['id'] | Should-Be 'b' + @(Get-IslPropertyValue -InputObject $page -Name 'empty').Count | Should-Be 0 + @(Get-IslPropertyValue -InputObject $page -Name '@odata.nextLink').Count | Should-Be 0 + } + } + + It 'reads a property of a .NET object' { + InModuleScope IntuneScriptLab { + Get-IslPropertyValue -InputObject ([version]'5.1.2') -Name 'Minor' | Should-Be 1 + @(Get-IslPropertyValue -InputObject ([version]'5.1.2') -Name 'Patch').Count | Should-Be 0 + } + } + } + + Context 'Error Handling' { + It 'does not fail on a missing member under the module''s strict mode, where a plain read does' { + InModuleScope IntuneScriptLab { + $reply = @{ id = 'rem-a' } + { $null = $reply.runSchedule } | Should-Throw -ExceptionMessage '*runSchedule*' + $schedule = Get-IslPropertyValue -InputObject $reply -Name 'runSchedule' -ErrorAction Stop + $schedule | Should-BeNull + # Reading on from a member that was not there gives nothing as well + @(Get-IslPropertyValue -InputObject $schedule -Name 'date' -ErrorAction Stop).Count | Should-Be 0 + } + } + } + + Context 'Performance Requirements' { + It 'makes 5,000 reads in less than five seconds' { + { + InModuleScope IntuneScriptLab { + $reply = @{ id = 'rem-a'; displayName = 'Fix-Widget' } + foreach ($index in 1..2500) { + $null = Get-IslPropertyValue -InputObject $reply -Name 'displayName' + $null = Get-IslPropertyValue -InputObject $reply -Name 'runSchedule' + } + } + } | Should-BeFasterThan '5s' + } + } +} diff --git a/Tests/Unit/Private/Get-IslSetting.Tests.ps1 b/Tests/Unit/Private/Get-IslSetting.Tests.ps1 index 9cd2c2f..a1fe363 100644 --- a/Tests/Unit/Private/Get-IslSetting.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslSetting.Tests.ps1 @@ -32,8 +32,9 @@ BeforeAll { function script:Get-Setting { param([string]$Relative, $Settings, [hashtable]$Cache = @{}) - $parameters = @{ Path = (Join-Path $script:Tree $Relative); Cache = $Cache } - if ($null -ne $Settings) { $parameters.Settings = $Settings } + # Settings is always passed, as $null when the test gives none: the block below runs under + # the module's strict mode, where a variable that was never set cannot be read + $parameters = @{ Path = (Join-Path $script:Tree $Relative); Cache = $Cache; Settings = $Settings } InModuleScope IntuneScriptLab -Parameters $parameters { $splat = @{ Path = $Path; Cache = $Cache } if ($null -ne $Settings) { $splat.Settings = $Settings } diff --git a/Tests/Unit/Private/Invoke-IslScriptRun.Tests.ps1 b/Tests/Unit/Private/Invoke-IslScriptRun.Tests.ps1 index fa86e71..f58d716 100644 --- a/Tests/Unit/Private/Invoke-IslScriptRun.Tests.ps1 +++ b/Tests/Unit/Private/Invoke-IslScriptRun.Tests.ps1 @@ -27,7 +27,7 @@ Describe 'Invoke-IslScriptRun' -Tag 'Unit', 'Private' { BeforeEach { # Echo the launch back so the test can read it, and record the cache folder Mock Invoke-IslProcess -ModuleName IntuneScriptLab { - [pscustomobject]@{ + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdErr = ''; Duration = [timespan]::FromSeconds(1) StdOut = "$FilePath|$Arguments|$WorkingDirectory|$WorkFolder|$Context|$TimeoutSeconds" } @@ -85,7 +85,7 @@ Describe 'Invoke-IslScriptRun' -Tag 'Unit', 'Private' { It 'copies the run result through unchanged' { Mock Invoke-IslProcess -ModuleName IntuneScriptLab { - [pscustomobject]@{ + ConvertTo-FakeRunResult @{ ExitCode = 4; TimedOut = $true; StdOut = 'o'; StdErr = 'e'; Duration = [timespan]::Zero } } @@ -101,7 +101,7 @@ Describe 'Invoke-IslScriptRun' -Tag 'Unit', 'Private' { It 'runs from a ProgramData cache the account is granted, and passes the credential through' { Mock Grant-IslFolderAccess -ModuleName IntuneScriptLab { } Mock Invoke-IslProcess -ModuleName IntuneScriptLab { - [pscustomobject]@{ + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdErr = ''; Duration = [timespan]::Zero StdOut = "$WorkFolder|$($Credential.UserName)|$LogonType" UserName = $Credential.UserName; LogonType = 'Interactive' diff --git a/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 b/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 index 7847460..c31a4cb 100644 --- a/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 +++ b/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 @@ -90,14 +90,14 @@ Describe 'Get-IntuneScriptHealth' -Tag 'Unit', 'Public' { '^/beta/deviceManagement/deviceHealthScripts/([^?/]+)/runSummary' { $tenant.runSummaries[$Matches[1]] } - '^/beta/deviceManagement/deviceHealthScripts/([^?/]+)' { + '^/beta/deviceManagement/deviceHealthScripts/([^?/]+)(\?|$)' { $tenant.remediations | Where-Object id -eq $Matches[1] } '^/beta/deviceManagement/deviceManagementScripts\?' { & $summary $tenant.platformScripts } '^/beta/deviceManagement/deviceManagementScripts/([^?/]+)/runSummary' { $tenant.runSummaries[$Matches[1]] } - '^/beta/deviceManagement/deviceManagementScripts/([^?/]+)' { + '^/beta/deviceManagement/deviceManagementScripts/([^?/]+)(\?|$)' { $tenant.platformScripts | Where-Object id -eq $Matches[1] } '^/beta/deviceAppManagement/mobileApps\?' { & $summary $tenant.apps } diff --git a/Tests/Unit/Public/Invoke-IntuneDetectionTest.Tests.ps1 b/Tests/Unit/Public/Invoke-IntuneDetectionTest.Tests.ps1 index 28c01f4..13d8d1e 100644 --- a/Tests/Unit/Public/Invoke-IntuneDetectionTest.Tests.ps1 +++ b/Tests/Unit/Public/Invoke-IntuneDetectionTest.Tests.ps1 @@ -33,7 +33,7 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { It 'takes script paths from the pipeline, as Get-ChildItem gives them' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { # The result's ScriptPath comes from the launch, which is mocked here - [pscustomobject]@{ + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'ok'; StdErr = ''; ScriptPath = $Path } } @@ -53,7 +53,7 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { Context 'Core Functionality' { It 'is detected with exit 0, stdout and no stderr' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = "installed`r`n"; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = "installed`r`n"; StdErr = '' } } $result = Invoke-IntuneDetectionTest -Path $script:Detect $result.Detected | Should-BeTrue @@ -63,7 +63,7 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { It 'is not detected with exit 0 and nothing on stdout' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = ''; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = ''; StdErr = '' } } $result = Invoke-IntuneDetectionTest -Path $script:Detect $result.Detected | Should-BeFalse @@ -72,7 +72,7 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { It 'is not detected when anything reaches stderr, even with stdout and exit 0' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'installed'; StdErr = 'oops' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'installed'; StdErr = 'oops' } } $result = Invoke-IntuneDetectionTest -Path $script:Detect $result.Detected | Should-BeFalse @@ -81,7 +81,7 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { It 'is not detected on a non-zero exit and names the code' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 1; TimedOut = $false; StdOut = 'installed'; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 1; TimedOut = $false; StdOut = 'installed'; StdErr = '' } } $result = Invoke-IntuneDetectionTest -Path $script:Detect $result.Detected | Should-BeFalse @@ -90,7 +90,7 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { It 'passes the architecture, context, phase and timeout through to the launch' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'x'; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'x'; StdErr = '' } } $result = Invoke-IntuneDetectionTest -Path $script:Detect -Architecture x86 -TimeoutSeconds 7 Should-Invoke Invoke-IslScriptRun -ModuleName IntuneScriptLab -Exactly -Times 1 -ParameterFilter { @@ -103,7 +103,7 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { It 'defaults to the 64-bit host this device has, the one the agent uses for Win32 detection' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'x'; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'x'; StdErr = '' } } $result = Invoke-IntuneDetectionTest -Path $script:Detect Should-Invoke Invoke-IslScriptRun -ModuleName IntuneScriptLab -Exactly -Times 1 -ParameterFilter { @@ -116,7 +116,7 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { Context 'Enforced signature check (W32-DET-SIGCHECK)' { BeforeEach { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'installed'; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'installed'; StdErr = '' } } $script:Unsigned = New-TestScript 'Detect-Unsigned.ps1' 'Write-Output installed; exit 0' } @@ -148,7 +148,7 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { Context 'Error Handling' { It 'reports a timeout as not detected with the 60-minute rule as the reason' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = $null; TimedOut = $true; StdOut = ''; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = $null; TimedOut = $true; StdOut = ''; StdErr = '' } } $result = Invoke-IntuneDetectionTest -Path $script:Detect -TimeoutSeconds 3 $result.Detected | Should-BeFalse @@ -158,7 +158,7 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { It 'combines every reason when several apply' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 2; TimedOut = $false; StdOut = ''; StdErr = 'err' } + ConvertTo-FakeRunResult @{ ExitCode = 2; TimedOut = $false; StdOut = ''; StdErr = 'err' } } $reason = (Invoke-IntuneDetectionTest -Path $script:Detect).Reason $reason | Should-BeLikeString '*Exit code 2*Nothing on stdout*stderr*' @@ -168,7 +168,7 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' { Context 'Another account' { It 'passes -Credential to the launcher and refuses it with Context System' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = "installed`r`n"; StdErr = '' RunAs = 'LAB\isl-user (Password)' } diff --git a/Tests/Unit/Public/Invoke-IntunePlatformScriptTest.Tests.ps1 b/Tests/Unit/Public/Invoke-IntunePlatformScriptTest.Tests.ps1 index 26f5130..50c338e 100644 --- a/Tests/Unit/Public/Invoke-IntunePlatformScriptTest.Tests.ps1 +++ b/Tests/Unit/Public/Invoke-IntunePlatformScriptTest.Tests.ps1 @@ -21,7 +21,7 @@ Describe 'Invoke-IntunePlatformScriptTest' -Tag 'Unit', 'Public' { Context 'Parameter Validation' { It 'takes script paths from the pipeline, one result each' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'ok'; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'ok'; StdErr = '' } } $results = @('C:\lab\a.ps1', 'C:\lab\b.ps1' | Invoke-IntunePlatformScriptTest) $results.Count | Should-Be 2 @@ -30,7 +30,7 @@ Describe 'Invoke-IntunePlatformScriptTest' -Tag 'Unit', 'Public' { It 'defaults to the 32-bit host and the current user, as the portal does' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = ''; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = ''; StdErr = '' } } $result = Invoke-IntunePlatformScriptTest -Path $script:Script $result.Architecture | Should-Be 'x86' @@ -44,7 +44,7 @@ Describe 'Invoke-IntunePlatformScriptTest' -Tag 'Unit', 'Public' { Context 'Core Functionality' { It 'reports Success on exit 0 with stdout and stderr joined as the result message' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = "out-1`r`nhost-2`r`n"; StdErr = "warn`r`n" } } @@ -56,7 +56,7 @@ Describe 'Invoke-IntunePlatformScriptTest' -Tag 'Unit', 'Public' { It 'reports Failed on any non-zero exit' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 5; TimedOut = $false; StdOut = ''; StdErr = 'deliberate' } + ConvertTo-FakeRunResult @{ ExitCode = 5; TimedOut = $false; StdOut = ''; StdErr = 'deliberate' } } $result = Invoke-IntunePlatformScriptTest -Path $script:Script $result.RunState | Should-Be 'Failed' @@ -66,7 +66,7 @@ Describe 'Invoke-IntunePlatformScriptTest' -Tag 'Unit', 'Public' { It 'warns what Intune does with a failure: three runs in total, at policy fetches (PS-FAIL)' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 1; TimedOut = $false; StdOut = ''; StdErr = 'deliberate' } + ConvertTo-FakeRunResult @{ ExitCode = 1; TimedOut = $false; StdOut = ''; StdErr = 'deliberate' } } $result = Invoke-IntunePlatformScriptTest -Path $script:Script @($result.Warnings).Count | Should-Be 1 @@ -76,7 +76,7 @@ Describe 'Invoke-IntunePlatformScriptTest' -Tag 'Unit', 'Public' { It 'carries no warning on success' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'ok'; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'ok'; StdErr = '' } } @((Invoke-IntunePlatformScriptTest -Path $script:Script).Warnings).Count | Should-Be 0 } @@ -85,7 +85,7 @@ Describe 'Invoke-IntunePlatformScriptTest' -Tag 'Unit', 'Public' { Context 'Error Handling' { It 'reports TimedOut when the script is killed' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = $null; TimedOut = $true; StdOut = ''; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = $null; TimedOut = $true; StdOut = ''; StdErr = '' } } $result = Invoke-IntunePlatformScriptTest -Path $script:Script -TimeoutSeconds 1 $result.RunState | Should-Be 'TimedOut' @@ -97,7 +97,7 @@ Describe 'Invoke-IntunePlatformScriptTest' -Tag 'Unit', 'Public' { Context 'Another account' { It 'passes -Credential to the launcher, reports RunAs, and refuses it with Context System' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = ''; StdErr = ''; RunAs = 'LAB\isl-user (Interactive)' } } diff --git a/Tests/Unit/Public/Invoke-IntuneRemediationTest.Tests.ps1 b/Tests/Unit/Public/Invoke-IntuneRemediationTest.Tests.ps1 index b3f74ec..d623efc 100644 --- a/Tests/Unit/Public/Invoke-IntuneRemediationTest.Tests.ps1 +++ b/Tests/Unit/Public/Invoke-IntuneRemediationTest.Tests.ps1 @@ -28,15 +28,15 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { # Detection passes only once the remediation has left its marker Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'detect' } { if (Test-Path (Join-Path (Split-Path $Path -Parent) 'fixed.marker')) { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'present'; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'present'; StdErr = '' } } else { - [pscustomobject]@{ ExitCode = 1; TimedOut = $false; StdOut = 'missing'; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 1; TimedOut = $false; StdOut = 'missing'; StdErr = '' } } } Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'remediate' } { $null = New-Item -ItemType File -Path (Join-Path (Split-Path $Path -Parent) 'fixed.marker') -Force - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'created'; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'created'; StdErr = '' } } } @@ -99,7 +99,7 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { It 'reports Recurred when the remediation exits 0 but detection still fails' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'remediate' } { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'did nothing'; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'did nothing'; StdErr = '' } } $result = Invoke-IntuneRemediationTest -DetectionPath $script:Detect -RemediationPath $script:Remediate $result.Status | Should-Be 'Recurred' @@ -111,7 +111,7 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { # exit code: RemediationStatus 3, Graph scriptError, no post-detection (REM-STDERR-EXIT0) Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'remediate' } { $null = New-Item -ItemType File -Path (Join-Path (Split-Path $Path -Parent) 'fixed.marker') -Force - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'turned off' + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'turned off' StdErr = "Set-ItemProperty : Cannot find path 'HKCU:\x' because it does not exist." } } $result = Invoke-IntuneRemediationTest -DetectionPath $script:Detect -RemediationPath $script:Remediate @@ -124,7 +124,7 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { It 'does not take whitespace on the remediation stderr for an error' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'remediate' } { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'did nothing'; StdErr = "`r`n" } + ConvertTo-FakeRunResult @{ ExitCode = 0; StdOut = 'did nothing'; StdErr = "`r`n" } } $result = Invoke-IntuneRemediationTest -DetectionPath $script:Detect -RemediationPath $script:Remediate $result.Status | Should-Be 'Recurred' @@ -133,7 +133,7 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { It 'reports Failed and skips the post-detection when the remediation exits non-zero' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'remediate' } { - [pscustomobject]@{ ExitCode = 1; TimedOut = $false; StdOut = ''; StdErr = 'nope' } + ConvertTo-FakeRunResult @{ ExitCode = 1; TimedOut = $false; StdOut = ''; StdErr = 'nope' } } $result = Invoke-IntuneRemediationTest -DetectionPath $script:Detect -RemediationPath $script:Remediate $result.Status | Should-Be 'Failed' @@ -142,7 +142,7 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { It 'treats any non-zero detection exit as an issue, and warns when it is not 1' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'detect' } { - [pscustomobject]@{ ExitCode = 2; TimedOut = $false; StdOut = 'still broken'; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 2; TimedOut = $false; StdOut = 'still broken'; StdErr = '' } } $result = Invoke-IntuneRemediationTest -DetectionPath $script:Detect -RemediationPath $script:Remediate $result.Status | Should-Be 'Recurred' @@ -153,7 +153,7 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { Context 'Output warnings' { It 'keeps the last stdout line and the last 2,048 characters, and warns about both' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'detect' } { - [pscustomobject]@{ + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = "one`r`ntwo`r`n" + ('x' * 3000); StdErr = '' } } @@ -165,7 +165,7 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { It 'warns when stderr is written but the detection still exits 0' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'detect' } { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'fine'; StdErr = 'careful' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'fine'; StdErr = 'careful' } } $result = Invoke-IntuneRemediationTest -DetectionPath $script:Detect $result.Status | Should-Be 'Without issues' @@ -175,8 +175,7 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { It 'warns about non-ASCII output, which Intune reports through the OEM code page' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'detect' } { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'Gr' + [char]0xFC + [char]0xDF + 'e' - StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; StdOut = 'Gr' + [char]0xFC + [char]0xDF + 'e' } } $result = Invoke-IntuneRemediationTest -DetectionPath $script:Detect $result.Warnings -join ' ' | Should-BeLikeString '*Non-ASCII*OEM code page*' @@ -186,7 +185,7 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { Context 'Error Handling' { It 'reports TimedOut when the detection is killed' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'detect' } { - [pscustomobject]@{ ExitCode = $null; TimedOut = $true; StdOut = ''; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = $null; TimedOut = $true; StdOut = ''; StdErr = '' } } $result = Invoke-IntuneRemediationTest -DetectionPath $script:Detect -RemediationPath $script:Remediate $result.Status | Should-Be 'TimedOut' @@ -195,7 +194,7 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' { It 'reports TimedOut when the remediation is killed' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'remediate' } { - [pscustomobject]@{ ExitCode = $null; TimedOut = $true; StdOut = ''; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = $null; TimedOut = $true; StdOut = ''; StdErr = '' } } $result = Invoke-IntuneRemediationTest -DetectionPath $script:Detect -RemediationPath $script:Remediate $result.Status | Should-Be 'TimedOut' diff --git a/Tests/Unit/Public/Invoke-IntuneRequirementTest.Tests.ps1 b/Tests/Unit/Public/Invoke-IntuneRequirementTest.Tests.ps1 index 3fe953d..cc12f98 100644 --- a/Tests/Unit/Public/Invoke-IntuneRequirementTest.Tests.ps1 +++ b/Tests/Unit/Public/Invoke-IntuneRequirementTest.Tests.ps1 @@ -34,7 +34,7 @@ Describe 'Invoke-IntuneRequirementTest' -Tag 'Unit', 'Public' { It 'takes script paths from the pipeline, with the rule given once' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'ok'; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'ok'; StdErr = '' } } $results = @('C:\lab\a.ps1', 'C:\lab\b.ps1' | Invoke-IntuneRequirementTest -OutputType String -Operator Equal -Value ok) @@ -44,7 +44,7 @@ Describe 'Invoke-IntuneRequirementTest' -Tag 'Unit', 'Public' { It 'defaults to the 64-bit host this device has, as the portal does for requirement rules' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = "ok`r`n"; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = "ok`r`n"; StdErr = '' } } $result = Invoke-IntuneRequirementTest -Path $script:Script -OutputType String -Value 'ok' $result.Architecture | Should-Be $script:Native @@ -59,7 +59,7 @@ Describe 'Invoke-IntuneRequirementTest' -Tag 'Unit', 'Public' { Context 'Core Functionality' { It 'reports Applicable with the compared output when the rule is met' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = "2.10.0`r`n"; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = "2.10.0`r`n"; StdErr = '' } } $intuneRequirementTestSplat = @{ Path = $script:Script @@ -76,7 +76,7 @@ Describe 'Invoke-IntuneRequirementTest' -Tag 'Unit', 'Public' { It 'reports not applicable with the reason when the rule fails' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = "first`r`nok`r`n"; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = 0; StdOut = "first`r`nok`r`n" } } $result = Invoke-IntuneRequirementTest -Path $script:Script -OutputType String -Value 'ok' $result.Applicable | Should-BeFalse @@ -86,7 +86,7 @@ Describe 'Invoke-IntuneRequirementTest' -Tag 'Unit', 'Public' { It 'carries the rule and the run details on the result' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ + ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = "5`r`n"; StdErr = ''; Host = 'h'; ScriptPath = 's' Duration = [timespan]::FromSeconds(2) } @@ -113,7 +113,7 @@ Describe 'Invoke-IntuneRequirementTest' -Tag 'Unit', 'Public' { Context 'Error Handling' { It 'reports a timeout as not applicable' { Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab { - [pscustomobject]@{ ExitCode = $null; TimedOut = $true; StdOut = ''; StdErr = '' } + ConvertTo-FakeRunResult @{ ExitCode = $null; TimedOut = $true; StdOut = ''; StdErr = '' } } $result = Invoke-IntuneRequirementTest -Path $script:Script -OutputType String -Value 'ok' $result.Applicable | Should-BeFalse From 35fd3e7bdf93630d5cf04c6f5f4f5172db00aaa5 Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:58:57 -0800 Subject: [PATCH 2/2] fix(module): read a generic dictionary through the accessor Get-IslPropertyValue called Contains on the dictionary itself. A generic Dictionary[string, object] implements that method of IDictionary explicitly, so PowerShell does not find it there and the call failed with "Cannot find an overload for Contains" for a key that is present and for one that is not. Nothing passes such a dictionary today, but the help says the function takes any dictionary. The method is now called through the interface, and a test covers the type. The catch in the root module's loader gets a comment that says why it only rethrows, so that it is not removed as dead code. Refs #63 --- IntuneScriptLab.psm1 | 2 ++ Private/Get-IslPropertyValue.ps1 | 4 +++- Tests/Unit/Private/Get-IslPropertyValue.Tests.ps1 | 14 ++++++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/IntuneScriptLab.psm1 b/IntuneScriptLab.psm1 index 3193c07..73af996 100644 --- a/IntuneScriptLab.psm1 +++ b/IntuneScriptLab.psm1 @@ -26,6 +26,8 @@ foreach ($functionFolder in $functionFolders) { Write-Verbose "Loading $($functionFile.FullName)" . $functionFile.FullName } catch { + # Not dead code: an error in a dot-sourced file, such as one that does not parse, ends + # only that statement. Rethrown here it ends the root module, and so the import. throw } } diff --git a/Private/Get-IslPropertyValue.ps1 b/Private/Get-IslPropertyValue.ps1 index ef6f591..b311d07 100644 --- a/Private/Get-IslPropertyValue.ps1 +++ b/Private/Get-IslPropertyValue.ps1 @@ -52,7 +52,9 @@ function Get-IslPropertyValue { } if ($InputObject -is [System.Collections.IDictionary]) { - if ($InputObject.Contains($Name)) { + # Called through the interface: a generic dictionary implements this method explicitly, + # and PowerShell does not find it on the object itself + if (([System.Collections.IDictionary]$InputObject).Contains($Name)) { return $InputObject[$Name] } return diff --git a/Tests/Unit/Private/Get-IslPropertyValue.Tests.ps1 b/Tests/Unit/Private/Get-IslPropertyValue.Tests.ps1 index d5c8486..862cc69 100644 --- a/Tests/Unit/Private/Get-IslPropertyValue.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslPropertyValue.Tests.ps1 @@ -86,6 +86,20 @@ Describe 'Get-IslPropertyValue' -Tag 'Unit', 'Private' { } } + It 'reads a generic dictionary, whose Contains method PowerShell does not find by name' { + InModuleScope IntuneScriptLab { + # Dictionary[string, object] implements IDictionary.Contains explicitly, so a plain + # call of that method on it fails with "Cannot find an overload" + $generic = [System.Collections.Generic.Dictionary[string, object]]::new() + $generic['id'] = 'rem-a' + $generic['deviceCount'] = 0 + Get-IslPropertyValue -InputObject $generic -Name 'id' -ErrorAction Stop | Should-Be 'rem-a' + Get-IslPropertyValue -InputObject $generic -Name 'deviceCount' -ErrorAction Stop | Should-Be 0 + @(Get-IslPropertyValue -InputObject $generic -Name 'runSchedule' -ErrorAction Stop).Count | + Should-Be 0 + } + } + It 'hands a list back as its elements, and an empty or missing list as nothing' { InModuleScope IntuneScriptLab { $page = @{ value = @(@{ id = 'a' }, @{ id = 'b' }); empty = @() }