From 18cc40b95fa553ea484f3311028be1f2d74be48d Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:07:28 -0800 Subject: [PATCH] fix(tenant)!: end the tenant commands with terminating errors Test-IntuneDeployedScript, Compare-IntuneDeployedScript, Get-IntuneScriptHealth and Test-IntuneAssignmentFilter, and the Graph seam and the export reader below them, ended on a failure with throw (ERR-10, ERR-11, ERR-14). Each failure the module detects is now an error record with an ID and a category, raised with ThrowTerminatingError, and every call of a function that can end that way is inside a try with a catch. Invoke-IslGraphRequest ends with the error Graph gave, unchanged, so a caller still reads the status code and the response from it. The tenant commands end with it in turn. The two commands that write one result after another read each policy inside a try and write what it gave after that try (ERR-15), so the output is still a stream and an error of a command further down the pipeline is not caught as theirs. Get-IslExportReport is one try from the job to the rows, and its download has -ErrorAction Stop. Get-IntuneScriptHealth returned its reports when only the file of -MarkdownPath could not be written, because a .NET exception ends just the statement. It still does, now on purpose: the failed write is reported with WriteError and -ErrorAction Stop ends the command. The contract test's list of calls that still rely on a throw loses the twenty of this area; thirteen remain, all in the analysis and rule commands. Refs #64. BREAKING CHANGE: a script that calls one of the four tenant commands without try and without $ErrorActionPreference = 'Stop' goes on at its next statement after a failure, where it used to end. Set the preference, or make the call inside try. --- CHANGELOG.md | 11 + CLAUDE.md | 5 +- Private/Get-IslExportReport.ps1 | 65 ++-- Private/Get-IslFilterDeviceFact.ps1 | 10 +- Private/Invoke-IslGraphRequest.ps1 | 39 ++- Public/Compare-IntuneDeployedScript.ps1 | 248 +++++++++------ Public/Get-IntuneScriptHealth.ps1 | 232 +++++++------- Public/Test-IntuneAssignmentFilter.ps1 | 9 +- Public/Test-IntuneDeployedScript.ps1 | 297 ++++++++++-------- README.md | 2 +- Tests/Unit/Module.ErrorFlow.Tests.ps1 | 20 -- .../Private/Get-IslExportReport.Tests.ps1 | 36 ++- .../Private/Invoke-IslGraphRequest.Tests.ps1 | 3 +- .../Compare-IntuneDeployedScript.Tests.ps1 | 38 ++- .../Public/Get-IntuneScriptHealth.Tests.ps1 | 44 +++ .../Test-IntuneAssignmentFilter.Tests.ps1 | 9 + .../Test-IntuneDeployedScript.Tests.ps1 | 22 ++ .../Compare-IntuneDeployedScript.md | 5 + .../IntuneScriptLab/Get-IntuneScriptHealth.md | 9 + .../Test-IntuneDeployedScript.md | 5 + en-US/IntuneScriptLab-Help.xml | 25 +- 21 files changed, 731 insertions(+), 403 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f0ddd15..ce1b556 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -100,6 +100,17 @@ entries are carried over from the manifest's release notes. that error. `Invoke-IntuneRemediationTest` and `Invoke-IntuneWin32AppTest` run one flow, and a step of it that cannot be run ends the command: no result is returned, and the steps that would have followed do not run. +- `Test-IntuneDeployedScript`, `Compare-IntuneDeployedScript`, `Get-IntuneScriptHealth` and + `Test-IntuneAssignmentFilter` end on a failure with a terminating error raised the way a compiled + cmdlet raises one, where they used `throw`. A request that Microsoft Graph refused ends the + command with Graph's own error, unchanged, and the failures the module detects have IDs of their + own: `GraphModuleNotLoaded`, `LocalPathNotFolder`, `DeviceFactsNeedWindows`, and for the app + install export `ExportJobTimedOut`, `ExportJobFailed` and `ExportHasNoCsv`. **A script that calls + one of them without `try` and without `$ErrorActionPreference = 'Stop'` now goes on at its next + statement after the failure, where it used to end.** What these commands return for a tenant + they can read is unchanged. `Get-IntuneScriptHealth` still returns its reports when only the + file of `-MarkdownPath` could not be written, and reports that as an error which + `-ErrorAction Stop` turns into the end of the command. - The module's functions run under strict mode, set once in the root module. A read of a variable that was never assigned, or of a member that is not there, is an error where it was a silent `$null`. Graph replies, export rows and the other data with optional members are read through one diff --git a/CLAUDE.md b/CLAUDE.md index 6e64c90..102af20 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -144,7 +144,10 @@ way out, so a `[object[]]` parameter splatted from that result binds `$null` and ### Graph goes through `Invoke-IslGraphRequest`, and the endpoints are the ones that still exist Every Graph call goes through the private `Invoke-IslGraphRequest` seam so the suites can mock it -and never touch a tenant. `mobileApps/{id}/installSummary`, `deviceStatuses` and `userStatuses` +and never touch a tenant. A request that fails for good ends the seam with Graph's own error +record, unchanged, so a caller still reads the status code from it; the tenant commands end with +it in turn, and write what each policy gave after the `try` that read the policy, so that the +output stays a stream. `mobileApps/{id}/installSummary`, `deviceStatuses` and `userStatuses` are gone and `reports/getAppsInstallSummaryReport` returns 400; app install counts come from the `AppInstallStatusAggregate` export job through `Get-IslExportReport`. `$select=installExperience` on `mobileApps/{id}` is refused (derived-type property) - fetch the app without `$select`. diff --git a/Private/Get-IslExportReport.ps1 b/Private/Get-IslExportReport.ps1 index 92cd345..d1c3ea1 100644 --- a/Private/Get-IslExportReport.ps1 +++ b/Private/Get-IslExportReport.ps1 @@ -45,40 +45,59 @@ function Get-IslExportReport { if ($Filter) { $body.filter = $Filter } 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 ($jobStatus -in 'notStarted', 'inProgress') { - if ((Get-Date) -gt $deadline) { - throw "The $ReportName export job did not complete within $TimeoutSeconds seconds" - } - Start-Sleep -Seconds 5 - $jobId = Get-IslPropertyValue -InputObject $job -Name 'id' - $job = Invoke-IslGraphRequest -Uri "$jobs/$jobId" - $jobStatus = "$(Get-IslPropertyValue -InputObject $job -Name '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 + $invalidResult = [System.Management.Automation.ErrorCategory]::InvalidResult + # The job, the wait for it, the download and the read are one transaction: a step that fails + # ends the function, and the records raised in here pass through the catch unchanged try { - Invoke-WebRequest -Uri $jobUrl -OutFile $zip -UseBasicParsing + $job = Invoke-IslGraphRequest -Uri $jobs -Method POST -Body $body + $jobStatus = "$(Get-IslPropertyValue -InputObject $job -Name 'status')" + $deadline = (Get-Date).AddSeconds($TimeoutSeconds) + while ($jobStatus -in 'notStarted', 'inProgress') { + if ((Get-Date) -gt $deadline) { + $recordSplat = @{ + Message = "The $ReportName export job did not complete within $TimeoutSeconds seconds" + ErrorId = 'ExportJobTimedOut' + Category = [System.Management.Automation.ErrorCategory]::OperationTimeout + TargetObject = $ReportName + ExceptionType = [System.TimeoutException] + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) + } + Start-Sleep -Seconds 5 + $jobId = Get-IslPropertyValue -InputObject $job -Name 'id' + $job = Invoke-IslGraphRequest -Uri "$jobs/$jobId" + $jobStatus = "$(Get-IslPropertyValue -InputObject $job -Name '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) { + $message = "The $ReportName export job ended with status '$jobStatus'" + $recordSplat = @{ Message = $message; ErrorId = 'ExportJobFailed'; Category = $invalidResult } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat -TargetObject $ReportName)) + } + + Invoke-WebRequest -Uri $jobUrl -OutFile $zip -UseBasicParsing -ErrorAction Stop Add-Type -AssemblyName System.IO.Compression.FileSystem $archive = [System.IO.Compression.ZipFile]::OpenRead($zip) try { $entry = $archive.Entries | Where-Object Name -like '*.csv' | Select-Object -First 1 - if (-not $entry) { throw "The $ReportName export contains no CSV file" } + if (-not $entry) { + $message = "The $ReportName export contains no CSV file" + $recordSplat = @{ Message = $message; ErrorId = 'ExportHasNoCsv'; Category = $invalidResult } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat -TargetObject $ReportName)) + } $reader = [System.IO.StreamReader]::new($entry.Open()) try { $csv = $reader.ReadToEnd() } finally { $reader.Dispose() } } finally { $archive.Dispose() } - @($csv | ConvertFrom-Csv) - } - finally { + $rows = @($csv | ConvertFrom-Csv) + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } finally { Remove-Item -LiteralPath $zip -Force -ErrorAction SilentlyContinue @script:IslInternal } + + $rows } diff --git a/Private/Get-IslFilterDeviceFact.ps1 b/Private/Get-IslFilterDeviceFact.ps1 index 0e7dc01..f61a0b3 100644 --- a/Private/Get-IslFilterDeviceFact.ps1 +++ b/Private/Get-IslFilterDeviceFact.ps1 @@ -29,7 +29,15 @@ function Get-IslFilterDeviceFact { $onWindows = $PSVersionTable.PSVersion.Major -lt 6 -or $IsWindows if (-not $onWindows) { - throw 'The local device facts come from Windows (CIM, the registry, dsregcmd); pass -Device elsewhere' + $message = ('The local device facts come from Windows (CIM, the registry, dsregcmd); pass ' + + '-Device elsewhere') + $recordSplat = @{ + Message = $message + ErrorId = 'DeviceFactsNeedWindows' + Category = [System.Management.Automation.ErrorCategory]::NotImplemented + ExceptionType = [System.PlatformNotSupportedException] + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } $computer = Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction SilentlyContinue diff --git a/Private/Invoke-IslGraphRequest.ps1 b/Private/Invoke-IslGraphRequest.ps1 index 66b9076..bc24db0 100644 --- a/Private/Invoke-IslGraphRequest.ps1 +++ b/Private/Invoke-IslGraphRequest.ps1 @@ -62,10 +62,17 @@ function Invoke-IslGraphRequest { ) if (-not (Get-Command -Name Invoke-MgGraphRequest -ErrorAction SilentlyContinue)) { - throw ('Microsoft.Graph.Authentication is not loaded. Install-PSResource ' + + $message = ('Microsoft.Graph.Authentication is not loaded. Install-PSResource ' + 'Microsoft.Graph.Authentication, then Connect-MgGraph -Scopes ' + 'DeviceManagementConfiguration.Read.All, DeviceManagementApps.Read.All, ' + 'DeviceManagementScripts.Read.All, GroupMember.Read.All') + $recordSplat = @{ + Message = $message + ErrorId = 'GraphModuleNotLoaded' + Category = [System.Management.Automation.ErrorCategory]::NotInstalled + TargetObject = 'Microsoft.Graph.Authentication' + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } $requestSplat = @{ Method = $Method; Uri = $Uri; ErrorAction = 'Stop' } if ($Body) { $requestSplat.Body = $Body } @@ -115,17 +122,27 @@ function Invoke-IslGraphRequest { } } - if (-not $All) { return Invoke-Once -Splat $requestSplat } - + # The request that failed for good ends this function with Graph's own error, unchanged, so + # that a caller reads the status code and the response from it as before $items = [System.Collections.Generic.List[object]]::new() - $next = $Uri - while ($next) { - $requestSplat.Uri = $next - $page = Invoke-Once -Splat $requestSplat - # 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' + try { + if (-not $All) { + $reply = Invoke-Once -Splat $requestSplat + } else { + $next = $Uri + while ($next) { + $requestSplat.Uri = $next + $page = Invoke-Once -Splat $requestSplat + # 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' + } + } + } catch { + $PSCmdlet.ThrowTerminatingError($_) } + + if (-not $All) { return $reply } $items.ToArray() } diff --git a/Public/Compare-IntuneDeployedScript.ps1 b/Public/Compare-IntuneDeployedScript.ps1 index 00f7bb7..8c943bf 100644 --- a/Public/Compare-IntuneDeployedScript.ps1 +++ b/Public/Compare-IntuneDeployedScript.ps1 @@ -25,9 +25,20 @@ function Compare-IntuneDeployedScript { Write-Verbose ("Starting $($MyInvocation.MyCommand.Name) against $Path for $($Kind -join ', ') named " + "$($Name -join ', ')$(if ($Id) { " or with id $($Id -join ', ')" })") - $root = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath + try { + $root = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } if (-not (Test-Path -LiteralPath $root -PathType Container)) { - throw "Path must be a folder holding the local scripts: $Path" + $recordSplat = @{ + Message = "Path must be a folder holding the local scripts: $Path" + ErrorId = 'LocalPathNotFolder' + Category = [System.Management.Automation.ErrorCategory]::InvalidArgument + TargetObject = $Path + ExceptionType = [System.ArgumentException] + } + $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } $files = @(Get-ChildItem -LiteralPath $root -Recurse -File -Filter '*.ps1') $folders = @(Get-Item -LiteralPath $root) + @(Get-ChildItem -LiteralPath $root -Recurse -Directory) @@ -344,123 +355,158 @@ function Compare-IntuneDeployedScript { try { if ('Remediation' -in $Kind) { $remediations = '/beta/deviceManagement/deviceHealthScripts' - foreach ($summary in (Get-WantedPolicy -Uri "$remediations`?`$select=id,displayName")) { - $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' - $policy = Invoke-IslGraphRequest -Uri "$remediations/$summaryId" - $policySettings = @{ - 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 = 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 = Get-IslPropertyValue -InputObject $policy -Name 'remediationScriptContent' - Candidates = Find-LocalFile -Policy $policy -Role 'remediation' -Pattern '^(?i)remediat' + try { + $summaries = @(Get-WantedPolicy -Uri "$remediations`?`$select=id,displayName") + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } + foreach ($summary in $summaries) { + # A read that fails ends the command. What one policy gives is written after its try, so + # that an error of a command further down the pipeline is not caught here + $policyOutput = try { + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $policy = Invoke-IslGraphRequest -Uri "$remediations/$summaryId" + $enforceSignature = Get-IslPropertyValue -InputObject $policy -Name 'enforceSignatureCheck' + $policySettings = @{ + RunAsAccount = Get-IslPropertyValue -InputObject $policy -Name 'runAsAccount' + RunAs32Bit = Get-IslPropertyValue -InputObject $policy -Name 'runAs32Bit' + EnforceSignatureCheck = $enforceSignature + } + $detectSplat = @{ + 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 = Get-IslPropertyValue -InputObject $policy -Name 'remediationScriptContent' + Candidates = Find-LocalFile -Policy $policy -Role 'remediation' -Pattern '^(?i)remediat' + } + Compare-Role @remediateSplat @policySettings + } catch { + $PSCmdlet.ThrowTerminatingError($_) } - Compare-Role @remediateSplat @policySettings + $policyOutput } } if ('PlatformScript' -in $Kind) { $scripts = '/beta/deviceManagement/deviceManagementScripts' - foreach ($summary in (Get-WantedPolicy -Uri "$scripts`?`$select=id,displayName")) { - $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' - $policy = Invoke-IslGraphRequest -Uri "$scripts/$summaryId" - $scriptSplat = @{ - 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' + try { + $summaries = @(Get-WantedPolicy -Uri "$scripts`?`$select=id,displayName") + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } + foreach ($summary in $summaries) { + $policyOutput = try { + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $policy = Invoke-IslGraphRequest -Uri "$scripts/$summaryId" + $enforceSignature = Get-IslPropertyValue -InputObject $policy -Name 'enforceSignatureCheck' + $scriptSplat = @{ + 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 = $enforceSignature + Candidates = Find-LocalFile -Policy $policy -Role 'script' + } + Compare-Role @scriptSplat + } catch { + $PSCmdlet.ThrowTerminatingError($_) } - Compare-Role @scriptSplat + $policyOutput } } if ('Win32App' -in $Kind) { $apps = '/beta/deviceAppManagement/mobileApps' $listUri = "$apps`?`$filter=isof('microsoft.graph.win32LobApp')&`$select=id,displayName" - foreach ($summary in (Get-WantedPolicy -Uri $listUri)) { - $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' - $app = Invoke-IslGraphRequest -Uri "$apps/$summaryId" - $scriptType = '#microsoft.graph.win32LobAppPowerShellScriptDetection' - $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 = @{ - Files = $detectionFiles; RuleCount = $detectionRules.Count; Index = $index - } - $candidates = Select-Candidate @candidateSplat - $rule = $detectionRules[$index] - $signatureCheck = Get-IslPropertyValue -InputObject $rule -Name 'enforceSignatureCheck' - $detectSplat = @{ - 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 + try { + $summaries = @(Get-WantedPolicy -Uri $listUri) + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } + foreach ($summary in $summaries) { + $policyOutput = try { + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $app = Invoke-IslGraphRequest -Uri "$apps/$summaryId" + $scriptType = '#microsoft.graph.win32LobAppPowerShellScriptDetection' + $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 = @{ + Files = $detectionFiles; RuleCount = $detectionRules.Count; Index = $index + } + $candidates = Select-Candidate @candidateSplat + $rule = $detectionRules[$index] + $signatureCheck = Get-IslPropertyValue -InputObject $rule -Name 'enforceSignatureCheck' + $detectSplat = @{ + 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 } - Compare-Role @detectSplat - } - if ($detectionRules.Count -eq 0 -and $detectionFiles.Count -gt 0) { - $noRuleSplat = @{ - PolicyKind = 'Win32App'; Policy = $app; Role = 'detection'; Content = '' - Candidates = $detectionFiles + if ($detectionRules.Count -eq 0 -and $detectionFiles.Count -gt 0) { + $noRuleSplat = @{ + PolicyKind = 'Win32App'; Policy = $app; Role = 'detection'; Content = '' + Candidates = $detectionFiles + } + Compare-Role @noRuleSplat } - Compare-Role @noRuleSplat - } - $requirementType = '#microsoft.graph.win32LobAppPowerShellScriptRequirement' - $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 = @{ - PolicyKind = 'Win32App'; Policy = $app; Role = 'requirement'; Content = '' - Candidates = $requirementFiles - } - Compare-Role @noRuleSplat - } - for ($index = 0; $index -lt $requirementRules.Count; $index++) { - $candidateSplat = @{ - Files = $requirementFiles; RuleCount = $requirementRules.Count; Index = $index + $requirementType = '#microsoft.graph.win32LobAppPowerShellScriptRequirement' + $requirementRules = @( + Get-IslPropertyValue -InputObject $app -Name 'requirementRules' | Where-Object { + "$(Get-IslPropertyValue -InputObject $_ -Name '@odata.type')" -eq $requirementType + }) + $requirementFind = @{ Policy = $app; Role = 'requirement'; Pattern = '^(?i)requirement' } + $requirementFiles = @(Find-LocalFile @requirementFind) + if ($requirementRules.Count -eq 0) { + $noRuleSplat = @{ + PolicyKind = 'Win32App'; Policy = $app; Role = 'requirement'; Content = '' + Candidates = $requirementFiles + } + Compare-Role @noRuleSplat } - $candidates = Select-Candidate @candidateSplat - $rule = $requirementRules[$index] - $signatureCheck = Get-IslPropertyValue -InputObject $rule -Name 'enforceSignatureCheck' - $requirementSplat = @{ - 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 + for ($index = 0; $index -lt $requirementRules.Count; $index++) { + $candidateSplat = @{ + Files = $requirementFiles; RuleCount = $requirementRules.Count; Index = $index + } + $candidates = Select-Candidate @candidateSplat + $rule = $requirementRules[$index] + $signatureCheck = Get-IslPropertyValue -InputObject $rule -Name 'enforceSignatureCheck' + $requirementSplat = @{ + 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 } - Compare-Role @requirementSplat + } catch { + $PSCmdlet.ThrowTerminatingError($_) } + $policyOutput } } diff --git a/Public/Get-IntuneScriptHealth.ps1 b/Public/Get-IntuneScriptHealth.ps1 index c8ee140..b06a106 100644 --- a/Public/Get-IntuneScriptHealth.ps1 +++ b/Public/Get-IntuneScriptHealth.ps1 @@ -52,34 +52,40 @@ function Get-IntuneScriptHealth { $selection = @{ Kind = $Kind; Name = $Name } if ($Id) { $selection.Id = $Id } - $findingsByPolicy = @{} - if (-not $SkipAnalysis) { - $analysisSplat = $selection.Clone() - if ($PSBoundParameters.ContainsKey('Settings')) { $analysisSplat.Settings = $Settings } - if ($SkipGroupLookup) { $analysisSplat.SkipGroupLookup = $true } - foreach ($finding in @(Test-IntuneDeployedScript @analysisSplat)) { - $key = "$($finding.PolicyId)" - if (-not $findingsByPolicy.ContainsKey($key)) { - $findingsByPolicy[$key] = [System.Collections.Generic.List[object]]::new() + # The analysis and the drift comparison each read the tenant; a read that fails ends this + # command as it ends them + try { + $findingsByPolicy = @{} + if (-not $SkipAnalysis) { + $analysisSplat = $selection.Clone() + if ($PSBoundParameters.ContainsKey('Settings')) { $analysisSplat.Settings = $Settings } + if ($SkipGroupLookup) { $analysisSplat.SkipGroupLookup = $true } + foreach ($finding in @(Test-IntuneDeployedScript @analysisSplat)) { + $key = "$($finding.PolicyId)" + if (-not $findingsByPolicy.ContainsKey($key)) { + $findingsByPolicy[$key] = [System.Collections.Generic.List[object]]::new() + } + $findingsByPolicy[$key].Add($finding) } - $findingsByPolicy[$key].Add($finding) } - } - $driftByPolicy = @{} - if ($Path) { - $driftSplat = $selection.Clone() - $driftSplat.Path = $Path - if ($Map) { $driftSplat.Map = $Map } - if ($PSBoundParameters.ContainsKey('Settings')) { $driftSplat.Settings = $Settings } - foreach ($result in @(Compare-IntuneDeployedScript @driftSplat)) { - $key = "$($result.PolicyId)" - if (-not $key) { continue } - if (-not $driftByPolicy.ContainsKey($key)) { - $driftByPolicy[$key] = [System.Collections.Generic.List[object]]::new() + $driftByPolicy = @{} + if ($Path) { + $driftSplat = $selection.Clone() + $driftSplat.Path = $Path + if ($Map) { $driftSplat.Map = $Map } + if ($PSBoundParameters.ContainsKey('Settings')) { $driftSplat.Settings = $Settings } + foreach ($result in @(Compare-IntuneDeployedScript @driftSplat)) { + $key = "$($result.PolicyId)" + if (-not $key) { continue } + if (-not $driftByPolicy.ContainsKey($key)) { + $driftByPolicy[$key] = [System.Collections.Generic.List[object]]::new() + } + $driftByPolicy[$key].Add($result) } - $driftByPolicy[$key].Add($result) } + } catch { + $PSCmdlet.ThrowTerminatingError($_) } # The install counts come from an export job, and creating one is a write to the tenant: @@ -214,96 +220,102 @@ function Get-IntuneScriptHealth { } } - $reports = [System.Collections.Generic.List[object]]::new() - if ('Remediation' -in $Kind) { - $remediations = '/beta/deviceManagement/deviceHealthScripts' - $fields = 'id,displayName,runAsAccount,lastModifiedDateTime' - foreach ($summary in (Get-WantedPolicy -Uri "$remediations`?`$select=id,displayName")) { - $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' - $policyUri = "$remediations/$summaryId`?`$select=$fields&`$expand=assignments" - $policy = Invoke-IslGraphRequest -Uri $policyUri - $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") + # A policy that cannot be read ends the command: a report with gaps would read as health + try { + $reports = [System.Collections.Generic.List[object]]::new() + if ('Remediation' -in $Kind) { + $remediations = '/beta/deviceManagement/deviceHealthScripts' + $fields = 'id,displayName,runAsAccount,lastModifiedDateTime' + foreach ($summary in (Get-WantedPolicy -Uri "$remediations`?`$select=id,displayName")) { + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $policyUri = "$remediations/$summaryId`?`$select=$fields&`$expand=assignments" + $policy = Invoke-IslGraphRequest -Uri $policyUri + $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) { + $counterValue = Get-IslPropertyValue -InputObject $run -Name "${counter}DeviceCount" + $runCount[$counter] = [int]$counterValue + } + $notApplicable = $runCount['detectionScriptNotApplicable'] + $reportSplat = @{ + 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 ($notApplicable) { "$notApplicable device(s) not applicable" }) + } + $reports.Add((ConvertTo-Report @reportSplat)) } - $notApplicable = $runCount['detectionScriptNotApplicable'] - $reportSplat = @{ - 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 ($notApplicable) { "$notApplicable device(s) not applicable" }) - } - $reports.Add((ConvertTo-Report @reportSplat)) } - } - if ('PlatformScript' -in $Kind) { - $scripts = '/beta/deviceManagement/deviceManagementScripts' - $fields = 'id,displayName,runAsAccount,lastModifiedDateTime' - foreach ($summary in (Get-WantedPolicy -Uri "$scripts`?`$select=id,displayName")) { - $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 = "$(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 = @() + if ('PlatformScript' -in $Kind) { + $scripts = '/beta/deviceManagement/deviceManagementScripts' + $fields = 'id,displayName,runAsAccount,lastModifiedDateTime' + foreach ($summary in (Get-WantedPolicy -Uri "$scripts`?`$select=id,displayName")) { + $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 = "$(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)) } - $reports.Add((ConvertTo-Report @reportSplat)) } - } - if ('Win32App' -in $Kind) { - $apps = '/beta/deviceAppManagement/mobileApps' - $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 - $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 = "$(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 ($notApplicable) { "$notApplicable device(s) not applicable" }) + if ('Win32App' -in $Kind) { + $apps = '/beta/deviceAppManagement/mobileApps' + $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 + $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 = "$(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 ($notApplicable) { "$notApplicable device(s) not applicable" }) + } + $reports.Add((ConvertTo-Report @reportSplat)) } - $reports.Add((ConvertTo-Report @reportSplat)) } + } catch { + $PSCmdlet.ThrowTerminatingError($_) } # The reports are read from the tenant and are returned in any case. The file is the one @@ -335,8 +347,14 @@ function Get-IntuneScriptHealth { } $lines.Add('') } - [System.IO.File]::WriteAllLines($markdownFile, $lines, [System.Text.UTF8Encoding]::new($false)) - Write-Verbose "Markdown report written to $MarkdownPath" + try { + [System.IO.File]::WriteAllLines($markdownFile, $lines, [System.Text.UTF8Encoding]::new($false)) + Write-Verbose "Markdown report written to $MarkdownPath" + } catch { + # The reports were read and are returned below. A file that could not be written is + # reported, and the caller decides with -ErrorAction whether that ends the command + $PSCmdlet.WriteError($_) + } } $reports diff --git a/Public/Test-IntuneAssignmentFilter.ps1 b/Public/Test-IntuneAssignmentFilter.ps1 index fd5e252..5d1d6c2 100644 --- a/Public/Test-IntuneAssignmentFilter.ps1 +++ b/Public/Test-IntuneAssignmentFilter.ps1 @@ -26,7 +26,14 @@ function Test-IntuneAssignmentFilter { [System.StringComparer]::OrdinalIgnoreCase) $source = $null if ($null -ne $Device) { $source = $Device } - elseif (-not $SyntaxOnly) { $source = Get-IslFilterDeviceFact } + elseif (-not $SyntaxOnly) { + # No facts, no verdict: the command ends here and process does not run + try { + $source = Get-IslFilterDeviceFact + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } + } if ($source -is [System.Collections.IDictionary]) { foreach ($key in $source.Keys) { $facts["$key"] = $source[$key] } } diff --git a/Public/Test-IntuneDeployedScript.ps1 b/Public/Test-IntuneDeployedScript.ps1 index 7476699..3cf5a24 100644 --- a/Public/Test-IntuneDeployedScript.ps1 +++ b/Public/Test-IntuneDeployedScript.ps1 @@ -290,161 +290,202 @@ function Test-IntuneDeployedScript { try { if ('Remediation' -in $Kind) { $remediations = '/beta/deviceManagement/deviceHealthScripts' - foreach ($summary in (Get-WantedPolicy -Uri "$remediations`?`$select=id,displayName")) { - $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' - $policy = Invoke-IslGraphRequest -Uri "$remediations/$summaryId`?`$expand=assignments" - $runAsAccount = Get-IslPropertyValue -InputObject $policy -Name 'runAsAccount' - $policySettings = @{ - 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 = Get-IslPropertyValue -InputObject $policy -Name 'detectionScriptContent' - } - Test-PolicyScript @detectSplat @policySettings - $remediationContent = Get-IslPropertyValue -InputObject $policy -Name 'remediationScriptContent' - if ($remediationContent) { - $remediateSplat = @{ - PolicyKind = 'Remediation'; Policy = $policy; Role = 'remediation' - ScriptType = 'Remediation'; Content = $remediationContent + try { + $summaries = @(Get-WantedPolicy -Uri "$remediations`?`$select=id,displayName") + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } + foreach ($summary in $summaries) { + # A read that fails ends the command. What one policy gives is written after its try, so + # that an error of a command further down the pipeline is not caught here + $policyOutput = try { + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $policy = Invoke-IslGraphRequest -Uri "$remediations/$summaryId`?`$expand=assignments" + $runAsAccount = Get-IslPropertyValue -InputObject $policy -Name 'runAsAccount' + $enforceSignature = Get-IslPropertyValue -InputObject $policy -Name 'enforceSignatureCheck' + $policySettings = @{ + RunAsAccount = $runAsAccount + RunAs32Bit = Get-IslPropertyValue -InputObject $policy -Name 'runAs32Bit' + EnforceSignatureCheck = $enforceSignature } - Test-PolicyScript @remediateSplat @policySettings - } - else { - $noteSplat = @{ - PolicyKind = 'Remediation'; Policy = $policy; Rule = 'IslDetectOnly' - Severity = 'Information' - Message = 'No remediation script: the detection runs alone on its schedule and the ' + - 'portal shows the issue without fixing it' - Evidence = 'A remediation created without remediationScriptContent ran its detection ' + - 'alone every cycle; Graph reports remediationState skipped (REM-DETECTONLY)' + $detectSplat = @{ + PolicyKind = 'Remediation' + Policy = $policy + Role = 'detection' + ScriptType = 'Detection' + Content = Get-IslPropertyValue -InputObject $policy -Name 'detectionScriptContent' + } + Test-PolicyScript @detectSplat @policySettings + $contentName = 'remediationScriptContent' + $remediationContent = Get-IslPropertyValue -InputObject $policy -Name $contentName + if ($remediationContent) { + $remediateSplat = @{ + PolicyKind = 'Remediation'; Policy = $policy; Role = 'remediation' + ScriptType = 'Remediation'; Content = $remediationContent + } + Test-PolicyScript @remediateSplat @policySettings + } + else { + $detectOnlyEvidence = ('A remediation created without remediationScriptContent ran ' + + 'its detection alone every cycle; Graph reports remediationState skipped ' + + '(REM-DETECTONLY)') + $noteSplat = @{ + PolicyKind = 'Remediation'; Policy = $policy; Rule = 'IslDetectOnly' + Severity = 'Information' + Message = 'No remediation script: the detection runs alone on its schedule and ' + + 'the portal shows the issue without fixing it' + Evidence = $detectOnlyEvidence + } + ConvertTo-PolicyFinding @noteSplat } - ConvertTo-PolicyFinding @noteSplat + Test-Assignment -PolicyKind 'Remediation' -Policy $policy -RunAsAccount $runAsAccount + Test-AssignmentFilter -PolicyKind 'Remediation' -Policy $policy + } catch { + $PSCmdlet.ThrowTerminatingError($_) } - Test-Assignment -PolicyKind 'Remediation' -Policy $policy -RunAsAccount $runAsAccount - Test-AssignmentFilter -PolicyKind 'Remediation' -Policy $policy + $policyOutput } } if ('PlatformScript' -in $Kind) { $scripts = '/beta/deviceManagement/deviceManagementScripts' - foreach ($summary in (Get-WantedPolicy -Uri "$scripts`?`$select=id,displayName")) { - $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 = Get-IslPropertyValue -InputObject $policy -Name 'scriptContent' - RunAsAccount = $runAsAccount - RunAs32Bit = Get-IslPropertyValue -InputObject $policy -Name 'runAs32Bit' - EnforceSignatureCheck = Get-IslPropertyValue -InputObject $policy -Name 'enforceSignatureCheck' + try { + $summaries = @(Get-WantedPolicy -Uri "$scripts`?`$select=id,displayName") + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } + foreach ($summary in $summaries) { + $policyOutput = try { + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $policy = Invoke-IslGraphRequest -Uri "$scripts/$summaryId`?`$expand=assignments" + $runAsAccount = Get-IslPropertyValue -InputObject $policy -Name 'runAsAccount' + $enforceSignature = Get-IslPropertyValue -InputObject $policy -Name 'enforceSignatureCheck' + $scriptSplat = @{ + 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 = $enforceSignature + } + Test-PolicyScript @scriptSplat + Test-Assignment -PolicyKind 'PlatformScript' -Policy $policy -RunAsAccount $runAsAccount + Test-AssignmentFilter -PolicyKind 'PlatformScript' -Policy $policy + } catch { + $PSCmdlet.ThrowTerminatingError($_) } - Test-PolicyScript @scriptSplat - Test-Assignment -PolicyKind 'PlatformScript' -Policy $policy -RunAsAccount $runAsAccount - Test-AssignmentFilter -PolicyKind 'PlatformScript' -Policy $policy + $policyOutput } } if ('Win32App' -in $Kind) { $apps = '/beta/deviceAppManagement/mobileApps' $listUri = "$apps`?`$filter=isof('microsoft.graph.win32LobApp')&`$select=id,displayName" - foreach ($summary in (Get-WantedPolicy -Uri $listUri)) { - $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' - $app = Invoke-IslGraphRequest -Uri "$apps/$summaryId`?`$expand=assignments" - $ruleIndex = 0 - foreach ($rule in @(Get-IslPropertyValue -InputObject $app -Name 'detectionRules')) { - $ruleIndex++ - # 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') { + try { + $summaries = @(Get-WantedPolicy -Uri $listUri) + } catch { + $PSCmdlet.ThrowTerminatingError($_) + } + foreach ($summary in $summaries) { + $policyOutput = try { + $summaryId = Get-IslPropertyValue -InputObject $summary -Name 'id' + $app = Invoke-IslGraphRequest -Uri "$apps/$summaryId`?`$expand=assignments" + $ruleIndex = 0 + foreach ($rule in @(Get-IslPropertyValue -InputObject $app -Name 'detectionRules')) { + $ruleIndex++ + # 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 = 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 + $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 ($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 ' + + 'detection rule or unable to parse detection rule" 0x87D30004 ' + + '(W32-FILE-NOTEXIST, W32-FILE-NOTEXIST-FALSE)' + } + ConvertTo-PolicyFinding @ruleSplat + } + } + 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' - $detectSplat = @{ + $requirementSplat = @{ PolicyKind = 'Win32App' Policy = $app - Role = 'detection' - ScriptType = 'Win32Detection' + Role = 'requirement' + ScriptType = 'Win32Requirement' Content = Get-IslPropertyValue -InputObject $rule -Name 'scriptContent' - RunAsAccount = 'system' + RunAsAccount = Get-IslPropertyValue -InputObject $rule -Name 'runAsAccount' RunAs32Bit = Get-IslPropertyValue -InputObject $rule -Name 'runAs32Bit' EnforceSignatureCheck = $signatureCheck } - Test-PolicyScript @detectSplat + Test-PolicyScript @requirementSplat } - elseif ($ruleType -eq '#microsoft.graph.win32LobAppFileSystemDetection' -and - $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 ($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 ' + - 'detection rule or unable to parse detection rule" 0x87D30004 ' + - '(W32-FILE-NOTEXIST, W32-FILE-NOTEXIST-FALSE)' + $installExperience = Get-IslPropertyValue -InputObject $app -Name 'installExperience' + $installAccount = Get-IslPropertyValue -InputObject $installExperience -Name 'runAsAccount' + $installContext = "$installAccount" + 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 } + $groupId = "$(Get-IslPropertyValue -InputObject $target -Name 'groupId')" + if (Test-DeviceGroup -GroupId $groupId) { $groupId } } - ConvertTo-PolicyFinding @ruleSplat - } - } - 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 = 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 - } - $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 } - $groupId = "$(Get-IslPropertyValue -InputObject $target -Name 'groupId')" - if (Test-DeviceGroup -GroupId $groupId) { $groupId } - } - if ($deviceGroups) { - $assignmentSplat = @{ - PolicyKind = 'Win32App'; Policy = $app; Rule = 'IslAssignmentIssue' - Severity = 'Warning' - Message = 'Install behavior User, assigned to devices ' + - "($($deviceGroups -join ', ')): the app is never installed there. Assign " + - 'it to users' - Evidence = 'A user-context app assigned to a device group was never installed ' + - 'on either join type: "user install context and this is a userless ' + - 'check-in", Not applicable, Applicability 1011 (W32-USER-INSTALL)' + if ($deviceGroups) { + $assignmentSplat = @{ + PolicyKind = 'Win32App'; Policy = $app; Rule = 'IslAssignmentIssue' + Severity = 'Warning' + Message = 'Install behavior User, assigned to devices ' + + "($($deviceGroups -join ', ')): the app is never installed there. Assign " + + 'it to users' + Evidence = 'A user-context app assigned to a device group was never installed ' + + 'on either join type: "user install context and this is a userless ' + + 'check-in", Not applicable, Applicability 1011 (W32-USER-INSTALL)' + } + ConvertTo-PolicyFinding @assignmentSplat } - ConvertTo-PolicyFinding @assignmentSplat } + # Install context is not a script context: the user-context note does not apply to apps + Test-Assignment -PolicyKind 'Win32App' -Policy $app -RunAsAccount 'system' + Test-AssignmentFilter -PolicyKind 'Win32App' -Policy $app + } catch { + $PSCmdlet.ThrowTerminatingError($_) } - # Install context is not a script context: the user-context note does not apply to apps - Test-Assignment -PolicyKind 'Win32App' -Policy $app -RunAsAccount 'system' - Test-AssignmentFilter -PolicyKind 'Win32App' -Policy $app + $policyOutput } } } diff --git a/README.md b/README.md index bfaf577..a36d966 100644 --- a/README.md +++ b/README.md @@ -744,7 +744,7 @@ Install-PSResource Microsoft.PowerShell.PlatyPS # 1.0.3 or later, once | `-Context System` says "run elevated" | `Register-ScheduledTask` needs an administrator session. Restart PowerShell as administrator; the current-user runs need no elevation. | | `-Architecture x64` refused on an ARM64 PC | ARM64 Windows has no x64 `powershell.exe`; only x86 (emulated) and arm64 (native) exist there, which is what Intune's agent uses too. Test x64 on an x64 machine. | | Runtime result differs from what Intune showed | Compare what the result carries as Intune reports it: `IntuneOutput` and `IntuneError` on a remediation result, `StdOut`, `StdErr` and `ExitCode` on a detection, platform script or requirement result (OEM code page; the 2,048-character tail where the portal caps it). The `-Verbose` switch prints each step. | -| A script goes on after a command failed | `Get-IntuneAgentLog`, `Get-IntuneAgentTimeline`, `Export-IntuneAgentDiagnostic` and the five `Invoke-Intune*Test` commands end on a failure with a terminating error, as a compiled cmdlet does: the command ends, and the script decides whether it stops too. Start the script with `$ErrorActionPreference = 'Stop'`, or make the call inside `try`. The error's `FullyQualifiedErrorId` says what failed, for example `UnknownAgentLogEvent`, `DiagnosticPackageExists`, `HostArchitectureUnavailable` or `ScheduledTaskNotRegistered`. One item among several is reported for that item and the others are still processed: a path that does not exist and a log that cannot be parsed (`CmTraceTimestampInvalid`) for the log commands, a script that cannot be run for `Invoke-IntuneDetectionTest`, `Invoke-IntuneRequirementTest` and `Invoke-IntunePlatformScriptTest`. `-ErrorAction Stop` ends the command there. | +| A script goes on after a command failed | The log commands (`Get-IntuneAgentLog`, `Get-IntuneAgentTimeline`, `Export-IntuneAgentDiagnostic`), the five `Invoke-Intune*Test` commands and the tenant commands (`Test-IntuneDeployedScript`, `Compare-IntuneDeployedScript`, `Get-IntuneScriptHealth`, `Test-IntuneAssignmentFilter`) end on a failure with a terminating error, as a compiled cmdlet does: the command ends, and the script decides whether it stops too. Start the script with `$ErrorActionPreference = 'Stop'`, or make the call inside `try`. The error's `FullyQualifiedErrorId` says what failed, for example `UnknownAgentLogEvent`, `DiagnosticPackageExists`, `HostArchitectureUnavailable`, `ScheduledTaskNotRegistered` or `GraphModuleNotLoaded`; a request that Graph refused ends the command with Graph's own error. One item among several is reported for that item and the others are still processed: a path that does not exist and a log that cannot be parsed (`CmTraceTimestampInvalid`) for the log commands, a script that cannot be run for `Invoke-IntuneDetectionTest`, `Invoke-IntuneRequirementTest` and `Invoke-IntunePlatformScriptTest`. `-ErrorAction Stop` ends the command there. | | Pester says `Should-HaveIntuneStatus` is not recognised | The aliases come from this module, not Pester: `Import-Module IntuneScriptLab` in `BeforeAll`, and use Pester 6.2 or later (`New-ShouldAssertion`). | ## Blog posts diff --git a/Tests/Unit/Module.ErrorFlow.Tests.ps1 b/Tests/Unit/Module.ErrorFlow.Tests.ps1 index 19f2e5b..eb64dbd 100644 --- a/Tests/Unit/Module.ErrorFlow.Tests.ps1 +++ b/Tests/Unit/Module.ErrorFlow.Tests.ps1 @@ -220,28 +220,8 @@ Describe 'How a failure travels through the module' -Tag 'Unit', 'Contract' { 'Assert-NotBeIntuneDetected -> Test-IslPesterAssertionSupport' 'Assert-PassIntuneAnalysis -> Test-IntuneScript' 'Assert-PassIntuneAnalysis -> Test-IslPesterAssertionSupport' - 'Compare-IntuneDeployedScript -> Compare-IntuneDeployedScript::Compare-Role' - 'Compare-IntuneDeployedScript -> Compare-IntuneDeployedScript::Get-WantedPolicy' - 'Compare-IntuneDeployedScript -> Invoke-IslGraphRequest' - 'Compare-IntuneDeployedScript::Compare-Role -> Compare-IntuneDeployedScript::Compare-Setting' - 'Compare-IntuneDeployedScript::Compare-Setting -> Compare-IntuneDeployedScript::Get-LocalSetting' - 'Compare-IntuneDeployedScript::Get-LocalSetting -> Get-IslSetting' - 'Compare-IntuneDeployedScript::Get-WantedPolicy -> Invoke-IslGraphRequest' - 'Get-IntuneScriptHealth -> Compare-IntuneDeployedScript' - 'Get-IntuneScriptHealth -> Get-IntuneScriptHealth::Get-WantedPolicy' - 'Get-IntuneScriptHealth -> Invoke-IslGraphRequest' - 'Get-IntuneScriptHealth -> Test-IntuneDeployedScript' - 'Get-IntuneScriptHealth::Get-WantedPolicy -> Invoke-IslGraphRequest' - 'Get-IslExportReport -> Invoke-IslGraphRequest' 'Get-IslSetting -> Get-IslSetting::ConvertTo-SettingsObject' - 'Invoke-IslGraphRequest -> Invoke-IslGraphRequest::Invoke-Once' 'Repair-IntuneScript -> Test-IntuneScript' - 'Test-IntuneAssignmentFilter -> Get-IslFilterDeviceFact' - 'Test-IntuneDeployedScript -> Invoke-IslGraphRequest' - 'Test-IntuneDeployedScript -> Test-IntuneDeployedScript::Get-WantedPolicy' - 'Test-IntuneDeployedScript -> Test-IntuneDeployedScript::Test-PolicyScript' - 'Test-IntuneDeployedScript::Get-WantedPolicy -> Invoke-IslGraphRequest' - 'Test-IntuneDeployedScript::Test-PolicyScript -> Test-IntuneScript' 'Test-IntuneScript -> Get-IslSetting' 'Test-IntuneWin32Requirement -> Get-IslWindowsReleaseBuild' 'Test-IntuneWin32Rule -> ConvertFrom-IslRuleSpec' diff --git a/Tests/Unit/Private/Get-IslExportReport.Tests.ps1 b/Tests/Unit/Private/Get-IslExportReport.Tests.ps1 index 68e82f1..63e80ff 100644 --- a/Tests/Unit/Private/Get-IslExportReport.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslExportReport.Tests.ps1 @@ -77,13 +77,43 @@ Describe 'Get-IslExportReport' -Tag 'Unit', 'Private' { It 'fails when the job ends in failure' { Mock Invoke-IslGraphRequest -ModuleName IntuneScriptLab { @{ id = 'job-3'; status = 'failed' } } - { InModuleScope IntuneScriptLab { Get-IslExportReport -ReportName 'AppInstallStatusAggregate' } } | - Should-Throw -ExceptionMessage "*ended with status 'failed'*" + $export = { InModuleScope IntuneScriptLab { Get-IslExportReport -ReportName 'AppInstallStatusAggregate' } } + $failure = $export | Should-Throw -ExceptionMessage "*ended with status 'failed'*" + $failure.FullyQualifiedErrorId | Should-BeLikeString 'ExportJobFailed,*' + Should-Invoke Invoke-WebRequest -ModuleName IntuneScriptLab -Times 0 -Exactly } It 'fails when the job does not complete in time' { Mock Invoke-IslGraphRequest -ModuleName IntuneScriptLab { @{ id = 'job-4'; status = 'inProgress' } } - { InModuleScope IntuneScriptLab { Get-IslExportReport -ReportName 'X' -TimeoutSeconds -1 } } | + $failure = { InModuleScope IntuneScriptLab { Get-IslExportReport -ReportName 'X' -TimeoutSeconds -1 } } | Should-Throw -ExceptionMessage '*did not complete within*' + $failure.FullyQualifiedErrorId | Should-BeLikeString 'ExportJobTimedOut,*' + } + + It 'fails when the download holds no CSV file, and removes the download' { + Mock Invoke-IslGraphRequest -ModuleName IntuneScriptLab { + @{ id = 'job-5'; status = 'completed'; url = 'https://download.example/job-5.zip' } + } + $script:Downloaded = $null + Mock Invoke-WebRequest -ModuleName IntuneScriptLab { + $script:Downloaded = $OutFile + $archive = [System.IO.Compression.ZipFile]::Open($OutFile, 'Create') + try { $null = $archive.CreateEntry('readme.txt') } finally { $archive.Dispose() } + } + + $failure = { InModuleScope IntuneScriptLab { Get-IslExportReport -ReportName 'X' } } | Should-Throw + $failure.FullyQualifiedErrorId | Should-BeLikeString 'ExportHasNoCsv,*' + $script:Downloaded | Should-NotBeNull + Test-Path -LiteralPath $script:Downloaded | Should-BeFalse + } + + It 'ends with the error of a download that fails' { + Mock Invoke-IslGraphRequest -ModuleName IntuneScriptLab { + @{ id = 'job-6'; status = 'completed'; url = 'https://download.example/job-6.zip' } + } + Mock Invoke-WebRequest -ModuleName IntuneScriptLab { throw 'The download was refused.' } + + { InModuleScope IntuneScriptLab { Get-IslExportReport -ReportName 'X' } } | + Should-Throw -ExceptionMessage '*download was refused*' } } diff --git a/Tests/Unit/Private/Invoke-IslGraphRequest.Tests.ps1 b/Tests/Unit/Private/Invoke-IslGraphRequest.Tests.ps1 index e66d283..fc4edf1 100644 --- a/Tests/Unit/Private/Invoke-IslGraphRequest.Tests.ps1 +++ b/Tests/Unit/Private/Invoke-IslGraphRequest.Tests.ps1 @@ -52,8 +52,9 @@ Describe 'Invoke-IslGraphRequest' -Tag 'Unit', 'Private' { It 'explains what to install and connect when the Graph module is not loaded' { $graphCommand = { $Name -eq 'Invoke-MgGraphRequest' } Mock Get-Command -ModuleName IntuneScriptLab { $null } -ParameterFilter $graphCommand - { InModuleScope IntuneScriptLab { Invoke-IslGraphRequest -Uri '/v1.0/me' } } | + $failure = { InModuleScope IntuneScriptLab { Invoke-IslGraphRequest -Uri '/v1.0/me' } } | Should-Throw -ExceptionMessage '*Microsoft.Graph.Authentication*Connect-MgGraph*' + $failure.FullyQualifiedErrorId | Should-BeLikeString 'GraphModuleNotLoaded,*' } It 'passes the method, URI and body through and returns the reply as is' { diff --git a/Tests/Unit/Public/Compare-IntuneDeployedScript.Tests.ps1 b/Tests/Unit/Public/Compare-IntuneDeployedScript.Tests.ps1 index 9df5dd5..651fb60 100644 --- a/Tests/Unit/Public/Compare-IntuneDeployedScript.Tests.ps1 +++ b/Tests/Unit/Public/Compare-IntuneDeployedScript.Tests.ps1 @@ -11,6 +11,10 @@ BeforeAll { $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force + . (Join-Path $script:ModuleRoot 'Tests\TestHelpers\TestHelpers.ps1') + # Stands in for the Graph module in a calling script: every request fails + $script:GraphDown = 'function global:Invoke-MgGraphRequest { ' + + "throw [System.InvalidOperationException]::new('Graph is down') }" function script:Get-ByteArray { param([string]$Text, [switch]$Bom) @@ -274,11 +278,41 @@ Describe 'Compare-IntuneDeployedScript' -Tag 'Unit', 'Public' { Context 'Error Handling' { It 'refuses a -Path that is not a folder' { $file = Join-Path $script:Root 'Scripts\Dup.ps1' - { Compare-IntuneDeployedScript -Path $file } | Should-Throw -ExceptionMessage '*must be a folder*' + $failure = { Compare-IntuneDeployedScript -Path $file } | + Should-Throw -ExceptionMessage '*must be a folder*' + $failure.FullyQualifiedErrorId | Should-BeLikeString 'LocalPathNotFolder,*' } It 'refuses a -Path that does not exist' { - { Compare-IntuneDeployedScript -Path (Join-Path $TestDrive 'nope') } | Should-Throw + { Compare-IntuneDeployedScript -Path (Join-Path $TestDrive 'nope') } | + Should-Throw -FullyQualifiedErrorId 'PathNotFound,*' + } + + It 'ends at the read of a policy that fails, with what the policies before it gave' { + Mock Invoke-IslGraphRequest -ModuleName IntuneScriptLab -ParameterFilter { + $Uri -like '*/deviceManagementScripts/*' + } { throw 'Graph answered 503.' } + + $output = [System.Collections.Generic.List[object]]::new() + + { Compare-IntuneDeployedScript -Path $script:Root | ForEach-Object { $output.Add($_) } } | + Should-Throw -ExceptionMessage '*Graph answered 503*' + # The remediations are compared first and were written before the failure; nothing of + # the platform scripts or the apps follows + $output.Count | Should-BeGreaterThan 0 + @($output | Where-Object { $_.Kind -ne 'Remediation' }) | Should-BeCollection @() + } + + It 'leaves a calling script one error and no result when Graph cannot be reached' { + $run = Invoke-CallerScript -Statement @( + $script:GraphDown + "`$drift = @(Compare-IntuneDeployedScript -Path '$($script:Root)' -Kind Remediation)" + "'results: ' + `$drift.Count" + ) + + $run.ReachedEnd | Should-BeTrue + $run.Output | Should-BeCollection @('results: 0') + $run.ErrorId | Should-BeCollection @('Graph is down') } } } diff --git a/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 b/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 index 9e4e1cf..5666ccc 100644 --- a/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 +++ b/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 @@ -9,6 +9,10 @@ BeforeAll { $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force + . (Join-Path $script:ModuleRoot 'Tests\TestHelpers\TestHelpers.ps1') + # Stands in for the Graph module in a calling script: every request fails + $script:GraphDown = 'function global:Invoke-MgGraphRequest { ' + + "throw [System.InvalidOperationException]::new('Graph is down') }" $group = @{ '@odata.type' = '#microsoft.graph.groupAssignmentTarget'; groupId = 'grp-devices' } $allDevices = @{ '@odata.type' = '#microsoft.graph.allDevicesAssignmentTarget' } @@ -259,4 +263,44 @@ Describe 'Get-IntuneScriptHealth' -Tag 'Unit', 'Public' { Test-Path -LiteralPath (Join-Path $folder 'health.md') | Should-BeTrue } } + + Context 'Error Handling' { + It 'ends with the error of the analysis when it fails, and returns no report' { + Mock Test-IntuneDeployedScript -ModuleName IntuneScriptLab { + throw 'The analysis could not read Graph.' + } + + { Get-IntuneScriptHealth -SkipRunState } | + Should-Throw -ExceptionMessage '*analysis could not read Graph*' + } + + It 'returns its reports when only the Markdown file cannot be written, and reports that' { + $missingFolder = Join-Path $TestDrive "no-such-folder-$([guid]::NewGuid().ToString('N'))" + $healthSplat = @{ + SkipAnalysis = $true; SkipRunState = $true; MarkdownPath = Join-Path $missingFolder 'health.md' + } + + $output = Get-IntuneScriptHealth @healthSplat -ErrorAction Continue 2>&1 + $errors = @($output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }) + $reports = @($output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }) + + $errors | Should-BeCollection -Count 1 + $errors[0].Exception.GetBaseException() | + Should-HaveType ([System.IO.DirectoryNotFoundException]) + $reports.Count | Should-BeGreaterThan 0 + { Get-IntuneScriptHealth @healthSplat -ErrorAction Stop } | Should-Throw + } + + It 'leaves a calling script one error and no report when Graph cannot be reached' { + $run = Invoke-CallerScript -Statement @( + $script:GraphDown + "`$reports = @(Get-IntuneScriptHealth -Kind Remediation -SkipRunState)" + "'reports: ' + `$reports.Count" + ) + + $run.ReachedEnd | Should-BeTrue + $run.Output | Should-BeCollection @('reports: 0') + $run.ErrorId | Should-BeCollection @('Graph is down') + } + } } diff --git a/Tests/Unit/Public/Test-IntuneAssignmentFilter.Tests.ps1 b/Tests/Unit/Public/Test-IntuneAssignmentFilter.Tests.ps1 index 1be9c29..0aeb3dc 100644 --- a/Tests/Unit/Public/Test-IntuneAssignmentFilter.Tests.ps1 +++ b/Tests/Unit/Public/Test-IntuneAssignmentFilter.Tests.ps1 @@ -279,5 +279,14 @@ Describe 'Test-IntuneAssignmentFilter' -Tag 'Unit', 'Public' { { Test-IntuneAssignmentFilter -Rule '(device.deviceName -like "X")' -Device @{} -ErrorAction Stop } | Should-Throw -ExceptionMessage '*unknown operator*' } + + It 'ends before any rule is judged when the facts of this device cannot be read' { + Mock Get-IslFilterDeviceFact -ModuleName IntuneScriptLab { throw 'The device facts need Windows.' } + Mock ConvertFrom-IslFilterRule -ModuleName IntuneScriptLab { } + + { '(device.deviceName -eq "X")' | Test-IntuneAssignmentFilter } | + Should-Throw -ExceptionMessage '*device facts need Windows*' + Should-Invoke ConvertFrom-IslFilterRule -ModuleName IntuneScriptLab -Times 0 -Exactly + } } } diff --git a/Tests/Unit/Public/Test-IntuneDeployedScript.Tests.ps1 b/Tests/Unit/Public/Test-IntuneDeployedScript.Tests.ps1 index 30d4746..7e76423 100644 --- a/Tests/Unit/Public/Test-IntuneDeployedScript.Tests.ps1 +++ b/Tests/Unit/Public/Test-IntuneDeployedScript.Tests.ps1 @@ -10,6 +10,10 @@ BeforeAll { $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force + . (Join-Path $script:ModuleRoot 'Tests\TestHelpers\TestHelpers.ps1') + # Stands in for the Graph module in a calling script: every request fails + $script:GraphDown = 'function global:Invoke-MgGraphRequest { ' + + "throw [System.InvalidOperationException]::new('Graph is down') }" function script:ConvertTo-Base64 { param([string]$Text, [switch]$Bom) @@ -420,5 +424,23 @@ Describe 'Test-IntuneDeployedScript' -Tag 'Unit', 'Public' { { Test-IntuneDeployedScript -Kind PlatformScript } | Should-Throw -ExceptionMessage '*analysis broke*' @(Get-ChildItem @listSplat).Count | Should-Be $before } + + It 'leaves a calling script one error and no finding when Graph cannot be reached' { + $run = Invoke-CallerScript -Statement @( + $script:GraphDown + "`$findings = @(Test-IntuneDeployedScript -Kind Remediation)" + "'findings: ' + `$findings.Count" + ) + + $run.ReachedEnd | Should-BeTrue + $run.Output | Should-BeCollection @('findings: 0') + $run.ErrorId | Should-BeCollection @('Graph is down') + } + + It 'does not take the error of a command further down the pipeline for its own' { + $downstream = { Test-IntuneDeployedScript | ForEach-Object { throw 'the caller''s own failure' } } + + $downstream | Should-Throw -ExceptionMessage 'the caller''s own failure' + } } } diff --git a/docs/IntuneScriptLab/Compare-IntuneDeployedScript.md b/docs/IntuneScriptLab/Compare-IntuneDeployedScript.md index 894cd8e..5f62684 100644 --- a/docs/IntuneScriptLab/Compare-IntuneDeployedScript.md +++ b/docs/IntuneScriptLab/Compare-IntuneDeployedScript.md @@ -65,6 +65,11 @@ LineEndings, Whitespace, Bom, Settings) and Detail says where. Nothing in the tenant is changed. +A request to Microsoft Graph that fails for good ends the command with a terminating error +that is Graph's own, with its status code. What was written before the failure stays written. +A script that calls the command goes on after that error unless the call is inside try or the +script sets $ErrorActionPreference to Stop. + ## EXAMPLES ### EXAMPLE 1 diff --git a/docs/IntuneScriptLab/Get-IntuneScriptHealth.md b/docs/IntuneScriptLab/Get-IntuneScriptHealth.md index 17fc44f..2b9cbed 100644 --- a/docs/IntuneScriptLab/Get-IntuneScriptHealth.md +++ b/docs/IntuneScriptLab/Get-IntuneScriptHealth.md @@ -59,6 +59,15 @@ A policy changed minutes ago is best read with -SkipRunState. -MarkdownPath writes the same report as a Markdown table per kind, for a wiki or a pull request. Nothing in the tenant is changed. +A request to Microsoft Graph that fails for good ends the command with a terminating error +that is Graph's own, with its status code, and no report is returned. +The run summaries and the app install export are the exception: when one of them cannot be +read, a warning says so and the device columns stay empty. +A file of -MarkdownPath that cannot be written is reported as an error, and the reports are +still returned. +A script that calls the command goes on after a terminating error unless the call is inside +try or the script sets $ErrorActionPreference to Stop. + ## EXAMPLES ### EXAMPLE 1 diff --git a/docs/IntuneScriptLab/Test-IntuneDeployedScript.md b/docs/IntuneScriptLab/Test-IntuneDeployedScript.md index 9d023c3..177ad67 100644 --- a/docs/IntuneScriptLab/Test-IntuneDeployedScript.md +++ b/docs/IntuneScriptLab/Test-IntuneDeployedScript.md @@ -84,6 +84,11 @@ Script content is written to a temporary folder for the analysis, byte for byte tenant stores it, and removed afterwards. Nothing in the tenant is changed. +A request to Microsoft Graph that fails for good ends the command with a terminating error +that is Graph's own, with its status code. What was written before the failure stays written. +A script that calls the command goes on after that error unless the call is inside try or the +script sets $ErrorActionPreference to Stop. + ## EXAMPLES ### EXAMPLE 1 diff --git a/en-US/IntuneScriptLab-Help.xml b/en-US/IntuneScriptLab-Help.xml index 4d861b8..e76bba1 100644 --- a/en-US/IntuneScriptLab-Help.xml +++ b/en-US/IntuneScriptLab-Help.xml @@ -1114,7 +1114,12 @@ carry, or a -Map entry naming a policy the selection did not include; a local fo policy the tenant does not have is not reported); Differences lists what differs (Content, LineEndings, Whitespace, Bom, Settings) and Detail says where. -Nothing in the tenant is changed. +Nothing in the tenant is changed. + +A request to Microsoft Graph that fails for good ends the command with a terminating error +that is Graph's own, with its status code. What was written before the failure stays written. +A script that calls the command goes on after that error unless the call is inside try or the +script sets $ErrorActionPreference to Stop. @@ -2449,7 +2454,16 @@ not re-reported at all, so lastStateUpdateDateTime is the last change, not the l count that is days old is not stale. A policy changed minutes ago is best read with -SkipRunState. -MarkdownPath writes the same report as a Markdown table per kind, for a wiki or a pull request. -Nothing in the tenant is changed. +Nothing in the tenant is changed. + +A request to Microsoft Graph that fails for good ends the command with a terminating error +that is Graph's own, with its status code, and no report is returned. +The run summaries and the app install export are the exception: when one of them cannot be +read, a warning says so and the device columns stay empty. +A file of -MarkdownPath that cannot be written is reported as an error, and the reports are +still returned. +A script that calls the command goes on after a terminating error unless the call is inside +try or the script sets $ErrorActionPreference to Stop. @@ -5097,7 +5111,12 @@ once, and the rest of the run does without them. Script content is written to a temporary folder for the analysis, byte for byte as the tenant stores it, and removed afterwards. -Nothing in the tenant is changed. +Nothing in the tenant is changed. + +A request to Microsoft Graph that fails for good ends the command with a terminating error +that is Graph's own, with its status code. What was written before the failure stays written. +A script that calls the command goes on after that error unless the call is inside try or the +script sets $ErrorActionPreference to Stop.