Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
65 changes: 42 additions & 23 deletions Private/Get-IslExportReport.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

-ErrorAction Stop is new (ERR-12). Without it a download that failed was reported and the function went on to open a zip that was not there. The request carries no credential, the address is a signed one from the job, so SEC-09's -MaximumRedirection 0 does not apply.

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
}
10 changes: 9 additions & 1 deletion Private/Get-IslFilterDeviceFact.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 28 additions & 11 deletions Private/Invoke-IslGraphRequest.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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 }

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

The reply is held in a variable for the length of the try and returned here. For a reply that is one object, a hashtable or the text of a $count, that is what return Invoke-Once ... gave. The comparison against the lab tenant is the check that nothing changed for real replies.

$items.ToArray()
}
Loading