Development snapshot 2026-10-25 (4.0.0-beta1 + fixes)

This commit is contained in:
Mikael Karlsson
2026-10-25 20:04:55 +11:00
parent 7869619510
commit 325e3a6b12
88 changed files with 21308 additions and 1081 deletions
+30
View File
@@ -0,0 +1,30 @@
# Facts about this application, read from its own module manifest.
#
# The About dialog used to carry them as literal text in the XAML - in BOTH backends,
# separately - so the copyright line said "(c) 2022" in a 2026 build, and disagreed
# with the manifest's own Copyright field ("(c) 2019-2026 ..."), which had been kept
# current. Two hardcoded copies that nothing compares will always drift.
#
# IntuneManagement.psd1 is the single source of truth: it is the file the module is
# loaded from, PowerShell exposes its metadata on the module object, and it is already
# the thing maintained at release time.
# Copyright line for the About dialog, from the manifest.
#
# $ExecutionContext.SessionState.Module is this module, so no name lookup and nothing
# to keep in step if the module is ever renamed. The fallback is deliberately vague
# about the year rather than inventing one: a wrong year is worse than no year.
function Get-AppCopyright {
[OutputType([string])]
param()
$text = $null
try { $text = [string]$ExecutionContext.SessionState.Module.Copyright } catch { }
if (-not [string]::IsNullOrWhiteSpace($text)) { return $text.Trim() }
$author = $null
try { $author = [string]$ExecutionContext.SessionState.Module.Author } catch { }
if (-not [string]::IsNullOrWhiteSpace($author)) { return "(c) $author. Software released under MIT License." }
return 'Software released under MIT License.'
}
+196 -6
View File
@@ -18,6 +18,134 @@ $script:AppUpdateRepo = 'Micke-K/IntuneManagement'
# Tried in order. $null means "no ref", i.e. whatever the default branch is.
$script:AppUpdateRefs = @('v4', $null)
# raw.githubusercontent.com fallback refs. Unlike the contents API there is no
# "omit the ref" form, so the default branch has to be named - hence master AND
# main, tried after v4. The list keeps the self-healing property described above:
# when v4 becomes the default branch its own ref stops resolving and the next
# entry serves exactly the content v4 used to.
$script:AppUpdateRawRefs = @('v4', 'master', 'main')
# Why a raw fallback exists at all: api.github.com allows 60 requests per hour per
# IP for unauthenticated callers, and that quota is counted per EGRESS ip - so every
# client behind one corporate proxy shares a single pool of 60 and a busy office
# never gets above it. raw.githubusercontent.com serves file content from a CDN and
# is not under that quota (verified live while the API was returning 403), so the
# two file lookups this module makes keep working when the API is exhausted.
# /releases has no raw equivalent and stays API-only.
# Human-readable reason the last GitHub lookup failed, or $null. Read by the UI so
# the dialog can say what actually happened instead of "not reachable" - the
# failures used to go only to Write-LogDebug, which is silent unless the Debug
# setting is on, so a rate-limited check looked exactly like a broken proxy.
$script:AppUpdateLastError = $null
function Get-AppUpdateLastError {
return $script:AppUpdateLastError
}
function Clear-AppUpdateLastError {
$script:AppUpdateLastError = $null
}
# Record (and log) why a lookup failed. First failure wins: it is the one that
# describes the primary cause, later refs usually fail the same way.
#
# A 403 from this API is almost always the rate limit rather than a permission
# problem, so it is named as such and the reset time is looked up from
# /rate_limit - that endpoint is explicitly exempt from the quota, so asking costs
# nothing even while everything else is being refused.
function Set-AppUpdateError {
param([string]$Context, $ErrorRecord)
$message = if ($ErrorRecord) { [string]$ErrorRecord.Exception.Message } else { 'unknown error' }
$detail = $message
if ($message -match '(?i)rate limit') {
$detail = 'GitHub API rate limit exceeded (60 requests per hour per IP for anonymous callers, shared by everyone behind the same proxy)'
$reset = Get-AppUpdateRateLimitReset
if ($reset) {
$detail += ". Resets at $($reset.ToString('HH:mm'))"
}
}
# Debug, not warning: a single lookup failing is not the outcome. The raw fallback
# below often rescues it, and four warnings for a check that then succeeded is its
# own kind of misleading. The entry points warn ONCE, with this reason, only when
# the whole lookup ends up empty.
Write-LogDebug "Update check: $Context failed. $detail"
if (-not $script:AppUpdateLastError) { $script:AppUpdateLastError = $detail }
}
# Local time the anonymous quota resets, or $null. /rate_limit does not count
# against the quota, so this is safe to call from the failure path.
function Get-AppUpdateRateLimitReset {
try {
$params = Get-AppUpdateRestParams
$limit = Invoke-RestMethod "https://api.github.com/rate_limit" @params
$epoch = [long]$limit.resources.core.reset
if ($epoch -gt 0) { return [DateTimeOffset]::FromUnixTimeSeconds($epoch).ToLocalTime() }
}
catch {
Write-LogDebug "Update check: rate limit lookup failed: $($_.Exception.Message)"
}
return $null
}
# The git blob sha of some text, the same value the contents API reports in .sha.
#
# git hashes a blob as sha1("blob <bytecount>\0<bytes>") over LF-normalised content.
# Computing it here is what lets the raw fallback return a Sha at all - raw serves
# bytes with no metadata - so a caller comparing published against local keeps
# working whichever path the text arrived by.
#
# The length prefix counts BYTES, not characters, and the payload is hashed as UTF-8
# bytes. Those differ the moment the file contains one non-ASCII character ("cafe"
# with an e-acute is 5 characters but 6 bytes), which would silently yield a sha that
# matches nothing GitHub ever reports - so a published file identical to the local
# one would be reported as differing. Verified against git hash-object for both an
# ASCII and a non-ASCII payload (Tests/AppUpdateFallback.Tests.ps1).
function Get-AppGitBlobSha {
param([string]$Text)
if ($null -eq $Text) { return $null }
$payload = [System.Text.Encoding]::UTF8.GetBytes($Text.Replace("`r`n", "`n"))
$header = [System.Text.Encoding]::ASCII.GetBytes("blob $($payload.Length)`0")
$stream = $null
try {
$stream = [IO.MemoryStream]::new()
$stream.Write($header, 0, $header.Length)
$stream.Write($payload, 0, $payload.Length)
[void]$stream.Seek(0, [IO.SeekOrigin]::Begin)
return (Get-FileHash -InputStream $stream -Algorithm SHA1).Hash
}
finally {
if ($stream) { $stream.Dispose() }
}
}
# A file's text from raw.githubusercontent.com, or $null. Tried refs in order.
function Get-AppRawFileText {
param([Parameter(Mandatory)][string]$Path)
$params = Get-AppUpdateRestParams
foreach ($ref in $script:AppUpdateRawRefs) {
$url = "https://raw.githubusercontent.com/$($script:AppUpdateRepo)/$ref/$Path"
try {
$text = Invoke-RestMethod $url @params
if ($text) {
Write-LogDebug "Update check: '$Path' served by raw.githubusercontent.com at ref '$ref'"
return [string]$text
}
}
catch {
Write-LogDebug "Update check: raw lookup of '$Path' at ref '$ref' failed: $($_.Exception.Message)"
}
}
return $null
}
# Invoke-RestMethod splat honouring the configured proxy, if any.
function Get-AppUpdateRestParams {
$params = @{}
@@ -114,14 +242,33 @@ function Get-AppRemoteManifestVersion {
$url = "https://api.github.com/repos/$($script:AppUpdateRepo)/contents/IntuneManagement.psd1"
if ($Ref) { $url = $url + '?ref=' + $Ref }
$tempManifest = $null
try {
$content = Invoke-RestMethod $url @params
if (-not $content.content) { return $null }
$text = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($content.content))
return (ConvertTo-AppVersionFromManifestText $text)
}
catch {
Set-AppUpdateError "manifest lookup at ref '$Ref'" $_
return $null
}
}
# A manifest's ModuleVersion (plus pre-release label) from its TEXT.
#
# Written to a temp file and read with Import-PowerShellDataFile: the manifest is
# PowerShell data, not JSON, and this avoids hand-rolling a parser or invoking the
# text as code. Split out from the API path so the raw fallback parses identically.
function ConvertTo-AppVersionFromManifestText {
param([string]$Text)
if ([string]::IsNullOrWhiteSpace($Text)) { return $null }
$tempManifest = $null
try {
$tempManifest = [IO.Path]::Combine([IO.Path]::GetTempPath(), "IM-update-$([Guid]::NewGuid().ToString('N')).psd1")
[IO.File]::WriteAllText($tempManifest, $text, (New-Object System.Text.UTF8Encoding($false)))
[IO.File]::WriteAllText($tempManifest, $Text, (New-Object System.Text.UTF8Encoding($false)))
$data = Import-PowerShellDataFile -Path $tempManifest -ErrorAction Stop
if (-not $data.ModuleVersion) { return $null }
@@ -132,7 +279,7 @@ function Get-AppRemoteManifestVersion {
return (ConvertTo-AppVersion $full)
}
catch {
Write-LogDebug "Update check: manifest lookup at ref '$Ref' failed: $($_.Exception.Message)"
Write-LogDebug "Update check: manifest parse failed: $($_.Exception.Message)"
return $null
}
finally {
@@ -165,7 +312,7 @@ function Get-AppRemoteReleaseVersion {
return $best
}
catch {
Write-LogDebug "Update check: releases lookup failed: $($_.Exception.Message)"
Set-AppUpdateError 'releases lookup' $_
return $null
}
}
@@ -179,6 +326,20 @@ function Get-AppRemoteVersion {
if ($fromManifest -and ($Major -le 0 -or $fromManifest.Release.Major -eq $Major)) { return $fromManifest }
}
# Contents API gave nothing at any ref. Before falling back to /releases, try the
# same manifest from raw: when the failure was the shared anonymous rate limit,
# raw is not subject to it and answers normally.
$rawText = Get-AppRawFileText -Path 'IntuneManagement.psd1'
if ($rawText) {
$fromRaw = ConvertTo-AppVersionFromManifestText $rawText
if ($fromRaw -and ($Major -le 0 -or $fromRaw.Release.Major -eq $Major)) {
$reason = Get-AppUpdateLastError
if ($reason) { Write-Log "Version read from raw.githubusercontent.com instead of the API: $reason" }
Clear-AppUpdateLastError
return $fromRaw
}
}
# No manifest at any ref matched. The 3.x line has no IntuneManagement.psd1
# at all - its manifest is named differently - so ask the releases instead.
return (Get-AppRemoteReleaseVersion -Major $Major)
@@ -217,12 +378,21 @@ function Get-AppUpdateInfo {
[CmdletBinding()]
param()
Clear-AppUpdateLastError
$local = Get-AppLocalVersion
$major = if ($local) { $local.Release.Major } else { 0 }
$remote = Get-AppRemoteVersion -Major $major
if (-not $local) { Write-Log 'Failed to get version info from local file' 2 }
if (-not $remote) { Write-Log 'Failed to get version info in GitHub' 2 }
if (-not $remote) {
# Name the cause. 'Failed to get version info in GitHub' on its own reads as a
# connectivity problem, which sent one report chasing a proxy setting for a
# check that was simply rate limited.
$reason = Get-AppUpdateLastError
if ($reason) { Write-Log "Failed to get version info in GitHub: $reason" 2 }
else { Write-Log 'Failed to get version info in GitHub' 2 }
}
$outdated = ($local -and $remote -and (Compare-AppVersion $local $remote) -lt 0)
@@ -256,6 +426,8 @@ function Get-AppRemoteReleaseNotes {
[CmdletBinding()]
param()
Clear-AppUpdateLastError
$params = Get-AppUpdateRestParams
foreach ($ref in $script:AppUpdateRefs) {
$url = "https://api.github.com/repos/$($script:AppUpdateRepo)/contents/ReleaseNotes.md"
@@ -270,8 +442,26 @@ function Get-AppRemoteReleaseNotes {
}
}
catch {
Write-LogDebug "Update check: release notes lookup at ref '$ref' failed: $($_.Exception.Message)"
Set-AppUpdateError "release notes lookup at ref '$ref'" $_
}
}
# Raw fallback: same file, CDN instead of the rate-limited API. Sha is computed
# locally (Get-AppGitBlobSha) so the caller's published-vs-local comparison
# behaves exactly as it does on the API path.
$rawText = Get-AppRawFileText -Path 'ReleaseNotes.md'
if ($rawText) {
$reason = Get-AppUpdateLastError
if ($reason) { Write-Log "Release notes read from raw.githubusercontent.com instead of the API: $reason" }
Clear-AppUpdateLastError
return [PSCustomObject]@{
Text = $rawText
Sha = Get-AppGitBlobSha $rawText
}
}
$reason = Get-AppUpdateLastError
if ($reason) { Write-Log "Failed to get release notes from GitHub: $reason" 2 }
else { Write-Log 'Failed to get release notes from GitHub' 2 }
return $null
}
+107
View File
@@ -0,0 +1,107 @@
# The console window the application was started from - show, hide, toggle.
#
# Version 3 hid that console at startup unless -ShowConsoleWindow was passed
# to the launcher. Version 4 leaves it alone at startup and offers two things
# instead: File > Hide console / Show console for the session, and the
# HideConsoleWindow setting (UI/Classes/UICommonSettings.ps1) to hide it once
# the main window is up. The UI decides when; this file only knows how, and
# reads no setting itself.
#
# Where it works: Windows, and only when the process owns a real console
# window - the classic console host that Start.cmd and Start-PS7.cmd get.
# Under Windows Terminal the process owns a hidden pseudo-console and the
# visible window belongs to Terminal, so ShowWindow changes nothing the user
# can see; that case reports "not supported" and the UI hides the menu item.
# macOS and Linux have no console window of the process at all - the terminal
# emulator is another application and cannot be hidden from here - so the
# feature does not exist there and the menu item is never shown.
# Support is decided once, on first use, and BEFORE anything is hidden: a
# console that is not visible when we first look is either Windows Terminal's
# hidden pseudo-console or a -WindowStyle Hidden start, and neither is a window
# the user expects this menu to control.
$script:ConsoleWindowSupported = $null
function Initialize-ConsoleWindowApi
{
if(-not $script:IsWindowsOS) { return $false }
if("IMConsoleWindow" -as [type]) { return $true }
try
{
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public static class IMConsoleWindow
{
[DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);
}
'@ -ErrorAction Stop
return $true
}
catch
{
Write-LogError "Console window API could not be loaded" $_.Exception
return $false
}
}
function Get-ConsoleWindowHandle
{
if(-not (Initialize-ConsoleWindowApi)) { return [IntPtr]::Zero }
return [IMConsoleWindow]::GetConsoleWindow()
}
# $true when Show/Hide-ConsoleWindow can do something the user will see.
function Test-ConsoleWindowSupported
{
if($null -ne $script:ConsoleWindowSupported) { return $script:ConsoleWindowSupported }
$supported = $false
if($script:IsWindowsOS)
{
$handle = Get-ConsoleWindowHandle
if($handle -ne [IntPtr]::Zero)
{
$supported = [bool][IMConsoleWindow]::IsWindowVisible($handle)
if(-not $supported) { Write-LogDebug "Console window exists but is not visible (Windows Terminal or a hidden start) - hide/show console is off" }
}
else { Write-LogDebug "No console window - hide/show console is off" }
}
$script:ConsoleWindowSupported = $supported
return $supported
}
function Get-ConsoleWindowVisible
{
if(-not (Test-ConsoleWindowSupported)) { return $false }
return [bool][IMConsoleWindow]::IsWindowVisible((Get-ConsoleWindowHandle))
}
# SW_SHOW (5): the user asked for the console, so it comes to the front.
function Show-ConsoleWindow
{
if(-not (Test-ConsoleWindowSupported)) { return $false }
[void][IMConsoleWindow]::ShowWindow((Get-ConsoleWindowHandle), 5)
Write-Log "Console window shown"
return $true
}
# SW_HIDE (0).
function Hide-ConsoleWindow
{
if(-not (Test-ConsoleWindowSupported)) { return $false }
[void][IMConsoleWindow]::ShowWindow((Get-ConsoleWindowHandle), 0)
Write-Log "Console window hidden"
return $true
}
# Toggles and returns the new state: $true visible, $false hidden.
function Switch-ConsoleWindow
{
if(-not (Test-ConsoleWindowSupported)) { return $false }
if(Get-ConsoleWindowVisible) { [void](Hide-ConsoleWindow); return $false }
[void](Show-ConsoleWindow)
return $true
}
@@ -26,6 +26,26 @@ function Get-SettingsCatalogPolicyBuffer {
return $script:_curSettingsCatologPolicy
}
# The @odata.type of a setting instance, inferred from the value it carries
# when the payload has none (a GET made with odata.metadata=none, and the
# exports hydrated that way).
function Get-SettingInstanceODataType {
param($SettingInstance)
$type = [string]$SettingInstance.'@odata.type'
if ($type) { return $type }
foreach ($pair in @(
@('groupSettingCollectionValue', '#microsoft.graph.deviceManagementConfigurationGroupSettingCollectionInstance'),
@('groupSettingValue', '#microsoft.graph.deviceManagementConfigurationGroupSettingInstance'),
@('choiceSettingCollectionValue', '#microsoft.graph.deviceManagementConfigurationChoiceSettingCollectionInstance'),
@('choiceSettingValue', '#microsoft.graph.deviceManagementConfigurationChoiceSettingInstance'),
@('simpleSettingCollectionValue', '#microsoft.graph.deviceManagementConfigurationSimpleSettingCollectionInstance'),
@('simpleSettingValue', '#microsoft.graph.deviceManagementConfigurationSimpleSettingInstance'))) {
if ($SettingInstance.PSObject.Properties[$pair[0]] -and $null -ne $SettingInstance.($pair[0])) { return $pair[1] }
}
return ''
}
function Add-SettingsSetting {
param(
$SettingInstance,
@@ -37,6 +57,7 @@ function Add-SettingsSetting {
if (-not $SettingInstance) { return }
$ctx = Get-CurrentDocumentationContext
$instanceType = Get-SettingInstanceODataType $SettingInstance
$defaultValue = $null
$tableValue = $null
@@ -97,8 +118,12 @@ function Add-SettingsSetting {
$settingDescription = $settingsDef.description.Trim([Environment]::NewLine).Trim("`n")
}
# The id comes from the schema when it resolved, else from the instance: a
# row without a schema still needs its identity (EntityKey, fallback names).
$settingId = if ($settingsDef) { $settingsDef.Id } else { $SettingInstance.settingDefinitionId }
$settingInfo = [PSCustomObject]@{
SettingId = $settingsDef.Id
SettingId = $settingId
SettingKey = ''
SettingName = $settingsDef.Name
Name = $settingName
@@ -116,7 +141,7 @@ function Add-SettingsSetting {
Level = $ItemLevel
Parent = $null
Show = $show
Type = $SettingInstance.'@odata.type'
Type = $instanceType
PropertyIndex = 0
RowIndex = 0
ChildSettings = @()
@@ -126,7 +151,7 @@ function Add-SettingsSetting {
$script:_curSettingsCatologPolicy += $settingInfo
}
switch ($SettingInstance.'@odata.type') {
switch ($instanceType) {
'#microsoft.graph.deviceManagementConfigurationChoiceSettingInstance' {
# Single dropdown
@@ -183,8 +208,12 @@ function Add-SettingsSetting {
# Catalog uses $settingsDef.childIds. Old code at L1347-1354.
$childIds = if ($ctx.CurrentObject.templateReference.templateId -and $SettingsDefs) {
$SettingsDefs.id
} else {
} elseif ($settingsDef.childIds) {
$settingsDef.childIds
} else {
# No schema for this group (offline, or an id the generic
# endpoint does not serve): walk the children the item has.
@($groupSettingCollection.children | ForEach-Object { $_.settingDefinitionId })
}
foreach ($childId in $childIds) {
$childSetting = $groupSettingCollection.children | Where-Object settingDefinitionId -EQ $childId | Select-Object -First 1
@@ -242,7 +271,7 @@ function Add-SettingsSetting {
}
default {
Write-Log "Unhandled settings catalog instance type: $($SettingInstance.'@odata.type')" 2
Write-Log "Unhandled settings catalog instance type: $instanceType" 2
return
}
}
@@ -274,15 +303,13 @@ function Add-SettingsSetting {
#
# Rows are returned rather than pushed onto the context, so the caller decides
# whether they belong in the main settings table or in a table of their own.
function Get-SettingsCatalogDocumentationRows
# Bind the context to the session-wide schema caches and make sure the
# configuration categories are loaded. Shared by Get-SettingsCatalogDocumentationRows
# and the handlers that walk a single settings instance themselves (reusable
# settings), which need the same category resolution.
function Initialize-SettingsCatalogSchemaCache
{
param(
$Settings,
[DocumentationContext]$Context
)
$cfgSettings = @($Settings)
if ($cfgSettings.Count -eq 0) { return @() }
param([DocumentationContext]$Context)
# Generic schema caches (session-persistent, shared by reference so later
# writes by the walker warm the cache automatically). Definitions are generic
@@ -306,6 +333,19 @@ function Get-SettingsCatalogDocumentationRows
Write-LogError 'Failed to fetch configuration categories' $_.Exception
}
}
}
function Get-SettingsCatalogDocumentationRows
{
param(
$Settings,
[DocumentationContext]$Context
)
$cfgSettings = @($Settings)
if ($cfgSettings.Count -eq 0) { return @() }
Initialize-SettingsCatalogSchemaCache $Context
# Seed the definition cache from inline settingDefinitions on each setting
foreach ($cfgSetting in $cfgSettings) {
@@ -491,6 +491,126 @@ function Add-DocumentationDefenderFirewallSettings {
}
}
function Get-DocumentationFirewallRuleHeader {
param([hashtable]$Meta, [string]$EntityKey)
$text = if ($Meta[$EntityKey].nameResourceKey) { Get-LanguageString "SettingDetails.$($Meta[$EntityKey].nameResourceKey)" }
if ($text) { $text } else { $EntityKey }
}
# Option label(s) for a firewall rule value. Flag enums ('private,public') map
# each part and join them with the property separator.
function Get-DocumentationFirewallRuleOption {
param([hashtable]$Meta, [string]$EntityKey, $Value, [string]$Separator)
$labels = foreach ($part in ("$Value" -split ',')) {
$part = $part.Trim()
if (-not $part) { continue }
$option = @($Meta[$EntityKey].options) | Where-Object { "$($_.value)" -eq $part } | Select-Object -First 1
$text = if ($option.nameResourceKey) { Get-LanguageString "SettingDetails.$($option.nameResourceKey)" }
if ($text) { $text } else { $part }
}
return (@($labels) -join $Separator)
}
# Endpoint Protection firewall rules. The portal metadata marks the rules table and
# every column enabled=false (rules are edited in a separate pane), so SkipDisabled
# dropped the row, and the generic table walk left the synthetic columns
# (application, protocol, ports, addresses) empty. Emit one enabled row whose
# FullValueTable has a line per rule, keeping only the columns some rule sets.
function Add-DocumentationFirewallRules {
param($Obj, $Prop, [DocumentationContext]$Context)
$rowProp = [PSCustomObject]@{
nameResourceKey = 'firewallRules'
descriptionResourceKey = 'firewallCreateRules'
entityKey = $Prop.entityKey
dataType = $Prop.dataType
category = $Prop.category
enabled = $true
}
$rules = @($Obj."$($Prop.entityKey)" | Where-Object { $null -ne $_ })
if ($rules.Count -eq 0) {
Add-PropertyInfo $rowProp $null
return
}
# Column metadata by entityKey, including the port settings nested under the
# protocol options' children.
$meta = @{}
$pending = [System.Collections.Generic.Queue[object]]::new()
foreach ($column in @($Prop.columns)) { if ($column.metadata) { $pending.Enqueue($column.metadata) } }
while ($pending.Count -gt 0) {
$setting = $pending.Dequeue()
if ($setting.entityKey -and -not $meta.ContainsKey($setting.entityKey)) { $meta[$setting.entityKey] = $setting }
foreach ($option in @($setting.options)) {
foreach ($child in @($option.children)) { if ($child) { $pending.Enqueue($child) } }
}
}
$sep = $Context.PropertySeparator
$notConfigured = Get-LanguageString 'SettingDetails.notConfigured'
$appKey = 'firewallRuleSyntheticApplicationKey'
$protocolKey = 'firewallRuleSyntheticProtocolKey'
$columnKeys = @('displayName', 'description', 'trafficDirection', 'action', 'profileTypes', $appKey, $protocolKey,
'firewallRuleSyntheticLocalPortsKey', 'firewallRuleSyntheticRemotePortsKey',
'firewallRuleSyntheticLocalAddressesKey', 'firewallRuleSyntheticRemoteAddressesKey',
'interfaceTypes', 'localUserAuthorizations')
$usedKeys = @{ displayName = $true }
$ruleCells = @(foreach ($rule in $rules) {
$cells = @{ displayName = $rule.displayName; description = $rule.description; localUserAuthorizations = $rule.localUserAuthorizations }
if ($rule.description) { $usedKeys.description = $true }
if ($rule.localUserAuthorizations) { $usedKeys.localUserAuthorizations = $true }
foreach ($key in 'trafficDirection', 'action', 'profileTypes', 'interfaceTypes') {
if ($null -ne $rule.$key -and "$($rule.$key)" -notin @('', 'notConfigured')) {
$cells[$key] = Get-DocumentationFirewallRuleOption $meta $key $rule.$key $sep
$usedKeys[$key] = $true
}
else { $cells[$key] = $notConfigured }
}
# The application option values are the rule property names.
$apps = foreach ($appProp in 'packageFamilyName', 'filePath', 'serviceName') {
if ($rule.$appProp) { '{0}: {1}' -f (Get-DocumentationFirewallRuleOption $meta $appKey $appProp $sep), $rule.$appProp }
}
if (@($apps).Count -gt 0) { $cells[$appKey] = @($apps) -join $sep; $usedKeys[$appKey] = $true }
else { $cells[$appKey] = Get-DocumentationFirewallRuleOption $meta $appKey 'all' $sep }
# Graph stores the IANA protocol number; the portal offers Any / TCP (6) / UDP (17) / Custom.
$protocol = $rule.protocol
if ($null -eq $protocol) { $cells[$protocolKey] = Get-DocumentationFirewallRuleOption $meta $protocolKey 'any' $sep }
else {
$usedKeys[$protocolKey] = $true
$cells[$protocolKey] = if ($protocol -eq 6) { Get-DocumentationFirewallRuleOption $meta $protocolKey 'TCP' $sep }
elseif ($protocol -eq 17) { Get-DocumentationFirewallRuleOption $meta $protocolKey 'UDP' $sep }
else { '{0}: {1}' -f (Get-DocumentationFirewallRuleOption $meta $protocolKey 'customProtocol' $sep), $protocol }
}
# Ports only apply to TCP/UDP; addresses always default to "Any address".
foreach ($pair in @(@('firewallRuleSyntheticLocalPortsKey', 'localPortRanges', ($protocol -in 6, 17)),
@('firewallRuleSyntheticRemotePortsKey', 'remotePortRanges', ($protocol -in 6, 17)),
@('firewallRuleSyntheticLocalAddressesKey', 'localAddressRanges', $true),
@('firewallRuleSyntheticRemoteAddressesKey', 'remoteAddressRanges', $true))) {
$ranges = @($rule."$($pair[1])" | Where-Object { $_ })
if ($ranges.Count -gt 0) { $cells[$pair[0]] = $ranges -join $sep; $usedKeys[$pair[0]] = $true }
elseif ($pair[2]) { $cells[$pair[0]] = Get-DocumentationFirewallRuleOption $meta $pair[0] 'all' $sep }
else { $cells[$pair[0]] = '' }
}
$cells
})
$keys = @($columnKeys | Where-Object { $usedKeys[$_] })
$headers = @{}
foreach ($key in $keys) { $headers[$key] = Get-DocumentationFirewallRuleHeader $meta $key }
$table = foreach ($cells in $ruleCells) {
$row = [ordered]@{}
foreach ($key in $keys) { $row[$headers[$key]] = $cells[$key] }
[PSCustomObject]$row
}
$value = @(foreach ($cells in $ruleCells) { @(foreach ($key in $keys) { $cells[$key] }) -join $sep }) -join $Context.ObjectSeparator
Add-PropertyInfo $rowProp $value $rules -TableValue @($table)
}
function Initialize-FeatureUpdateSyntheticProperties {
param($Obj, [DocumentationContext]$Context)
@@ -1257,6 +1377,10 @@ function Get-DocumentationCustomProfileValue {
Invoke-TranslateOption $TopObj $Prop | Out-Null
return $false
}
if ($Prop.entityKey -eq 'firewallRules') {
Add-DocumentationFirewallRules $Obj $Prop $Context
return $false
}
}
if ($type -eq '#microsoft.graph.windowsHealthMonitoringConfiguration' -and $Prop.entityKey -eq 'configDeviceHealthMonitoringScope' -and ($Prop.options | Where-Object value -EQ 'healthMonitoring')) { return $false }
if ($type -eq '#microsoft.graph.windows10VpnConfiguration') {
@@ -1274,13 +1398,23 @@ function Get-DocumentationCustomProfileValue {
function Finalize-DocumentationCustomObject {
param($Obj, [DocumentationContext]$Context)
if ($Obj.'@odata.type' -ne '#microsoft.graph.windows10EndpointProtectionConfiguration') { return }
foreach ($categoryId in @('bitLocker','xboxServices')) {
# Drop a whole category when none of its rows differs from its default. Graph
# returns enum defaults for settings nobody touched (e.g. Xbox services 'manual',
# lanManagerAuthenticationLevel 'lmAndNltm') and the portal hides them. Done per
# category rather than per row: a default value is still shown when something
# else in its category is configured.
foreach ($categoryId in @('bitLocker','xboxServices','defenderLocalSecurityOptions')) {
$category = Get-LanguageString "Category.$categoryId"
if (-not $category) { continue }
$rows = @($Context.SettingsData | Where-Object Category -EQ $category)
$configured = $rows | Where-Object {
if ($categoryId -eq 'bitLocker' -and $_.EntityKey -like 'startupAuthenticationTpm*') { return $false }
return $null -ne $_.RawValue -and $_.RawValue -ne $_.DefaultValue
$raw = $_.RawValue
if ($null -eq $raw -or "$raw" -in @('', 'notConfigured')) { return $false }
if ($raw -is [array]) { return $raw.Count -gt 0 }
# String compare: -ne coerces to the left operand's type, so a boolean
# RawValue against a string default would compare as booleans.
return "$raw" -ne "$($_.DefaultValue)"
} | Select-Object -First 1
if ($configured) { continue }
foreach ($row in $rows) { [void]$Context.SettingsData.Remove($row) }
@@ -2,11 +2,331 @@
# handler.
#
# Claims @odata.type='#microsoft.graph.deviceManagementReusablePolicySetting'.
# Covers the reusable settings surfaced as policy types (currently the Linux
# custom-compliance discovery script). The object is a name + description +
# settingDefinitionId wrapper around a single settings-catalog setting
# instance whose simpleSettingValue carries the payload (base64 script for
# the discovery-script definition). No old-project documenter existed.
# A reusable setting is a name + description around ONE settings-catalog
# setting instance (settingInstance). The portal wizard
# (ReusableSettingsWizard.ReactView.js) reads that instance against the schema
# from deviceManagement/reusableSettings, which is where the display names of
# every child ("Keyword", "Auto Resolve", "Match type", "Device properties", ...)
# and of every choice option ("True", "Match all") live. The generic
# configurationSettings/{id} endpoint answers nothing for these ids (they carry
# {id} / {groupid} placeholders), so the schema is loaded from that list once
# per session and handed to the settings-catalog walker inline.
#
# Rendering: a list of items (GroupSettingCollection whose items hold only
# simple / choice values - firewall dynamic keyword addresses, Device Control
# device properties, printer devices) becomes one row with a table value
# (FullValueTable: one column per named child) plus a flat Value for the
# outputs that cannot show a table. Groups that nest further lists (the Device
# Control group itself) are flattened: their simple values become rows and
# their lists tables. Anything else is a plain Name = Value row, the Linux
# discovery script decoded.
#
# No schema reachable (fully offline): rows and choice values are named from
# the definition ids instead of showing nothing.
#
# The list endpoint omits settingInstance; the single GET with $select carries
# it (same contract as the export hydration in ReusableSettingsObjectBase).
# Documenting straight from the tenant therefore fetches it when the source
# tenant is available, and attaches it to the object so an export of the same
# run is complete.
$script:_docReusableSettingDefinitions = $null
function Reset-ReusableSettingDefinitionCache {
$script:_docReusableSettingDefinitions = $null
}
# All reusable-setting definitions (roots and children) as Graph returns them,
# loaded once per session. Generic schema, so gated on connectivity only, not
# on SourceTenantUnavailable - documenting an export while signed into another
# tenant still resolves names.
function Get-ReusableSettingDefinitions {
param([DocumentationContext]$Context)
if ($null -ne $script:_docReusableSettingDefinitions) { return $script:_docReusableSettingDefinitions }
if (-not (Test-DocumentationGraphAvailable)) { return @() }
try {
$resp = Invoke-MSGraphAPI -Url "/deviceManagement/reusableSettings" -ODataMetadata 'minimal' -AdditionalHeaders (Get-DocAcceptLanguageHeaders $Context)
$script:_docReusableSettingDefinitions = @($resp.value)
}
catch {
Write-LogError "Failed to fetch the reusable setting definitions" $_.Exception
$script:_docReusableSettingDefinitions = @()
}
return $script:_docReusableSettingDefinitions
}
# A readable name from a definition id when the schema did not give one:
# the part after the parent id ("..._{id}_autoresolve" -> "Autoresolve"), else
# the last segment that is not a {placeholder}.
function Get-ReusableSettingFallbackName {
param([string]$Id, [string]$ParentId)
if ([string]::IsNullOrEmpty($Id)) { return '' }
$tail = $Id
if ($ParentId -and $Id.StartsWith("$ParentId`_", [StringComparison]::OrdinalIgnoreCase) -and $Id.Length -gt $ParentId.Length + 1) {
$tail = $Id.Substring($ParentId.Length + 1)
}
else {
$segments = @($Id.Split('_') | Where-Object { $_ -and $_ -notmatch '^\{.*\}$' })
if ($segments.Count -gt 0) { $tail = $segments[-1] }
}
$tail = $tail.Replace('_', ' ').Trim()
if ($tail.Length -eq 0) { return '' }
return $tail.Substring(0, 1).ToUpperInvariant() + $tail.Substring(1)
}
# Row name: the schema display name; derived from the id only when no schema
# resolved the row at all. A schema row with a BLANK name is one Microsoft
# hides (the GUID id of a firewall address) and stays blank, so callers skip it.
function Get-ReusableSettingRowName {
param($Row, [string]$ParentId, [object[]]$Definitions)
$name = [string]$Row.Name
if (-not [string]::IsNullOrWhiteSpace($name)) { return $name.Trim() }
if ($Definitions -and $Row.SettingId -and ($Definitions | Where-Object id -EQ $Row.SettingId | Select-Object -First 1)) { return '' }
return Get-ReusableSettingFallbackName $Row.SettingId $ParentId
}
# Value of a simple / choice row: what the walker resolved, else - for a choice
# whose option the schema did not name - the option suffix ("..._true" -> "True").
function Get-ReusableSettingRowValue {
param($Row)
$value = $Row.Value
if ($null -eq $value -or ([string]$value).Length -eq 0) {
$raw = [string]$Row.RawValue
if ($raw -and $Row.SettingId -and $Row.Type -like '*ChoiceSettingInstance') {
$value = Get-ReusableSettingFallbackName $raw $Row.SettingId
}
elseif ($raw) { $value = $raw }
}
if ($value -is [string] -and [string]$Row.SettingId -like '*discoveryscript*') {
# The discovery-script definition stores the script base64-encoded.
try {
$decoded = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($value))
if ($decoded) { $value = $decoded }
}
catch { }
}
return $value
}
# True when a walker node is a list or group container.
function Test-ReusableSettingGroupNode {
param($Row)
return ([string]$Row.Type -like '*GroupSettingCollectionInstance' -or [string]$Row.Type -like '*GroupSettingInstance')
}
# Emit the documentation rows for one walker node (and what it contains).
function ConvertTo-ReusableSettingDocRows {
param(
$Node,
[DocumentationContext]$Context,
[string]$ParentId,
[int]$Level = 0,
[object[]]$Definitions = @()
)
if (-not $Node) { return }
$type = [string]$Node.Type
if ($type -like '*GroupSettingCollectionInstance') {
$items = @($Node.ChildSettings)
$nested = $false
foreach ($item in $items) {
foreach ($child in @($item.Settings)) {
if (Test-ReusableSettingGroupNode $child) { $nested = $true; break }
}
if ($nested) { break }
}
if ($nested -or $items.Count -eq 0) {
# A group of groups: its simple values become rows and its lists tables.
foreach ($item in $items) {
foreach ($child in @($item.Settings)) {
ConvertTo-ReusableSettingDocRows -Node $child -Context $Context -ParentId $Node.SettingId -Level $Level -Definitions $Definitions
}
}
return
}
# A list of flat items: one table, a column per named child (schema
# order, first appearance), rows in item order.
$columns = [System.Collections.Generic.List[string]]::new()
$tableRows = @()
$flatItems = @()
foreach ($item in $items) {
$cells = [ordered]@{}
$parts = @()
foreach ($child in @($item.Settings)) {
$colName = Get-ReusableSettingRowName $child $Node.SettingId $Definitions
if ([string]::IsNullOrEmpty($colName)) { continue } # the unnamed GUID id of a firewall address
if (-not $columns.Contains($colName)) { [void]$columns.Add($colName) }
$cellValue = [string](Get-ReusableSettingRowValue $child)
$cells[$colName] = $cellValue
if ($cellValue.Length -gt 0) { $parts += "${colName}: $cellValue" }
}
$tableRows += ,$cells
$flatItems += ($parts -join $Context.PropertySeparator)
}
$table = foreach ($cells in $tableRows) {
$rowObj = [ordered]@{}
foreach ($col in $columns) { $rowObj[$col] = if ($cells.Contains($col)) { $cells[$col] } else { '' } }
[PSCustomObject]$rowObj
}
$label = Get-ReusableSettingRowName $Node $ParentId $Definitions
# Microsoft named the firewall list root " Id"; the category (Firewall)
# is the readable label there.
if ([string]::IsNullOrWhiteSpace($label) -or $label -eq 'Id') { $label = [string]$Node.Category }
if ([string]::IsNullOrWhiteSpace($label)) { $label = Get-ReusableSettingFallbackName $Node.SettingId $null }
$Context.AddSetting([PSCustomObject]@{
Name = $label
Value = ($flatItems -join $Context.ObjectSeparator)
Description = $Node.Description
Category = $Node.Category
SubCategory = $Node.SubCategory
Level = $Level
SettingId = $Node.SettingId
RowIndex = $Node.RowIndex
RawValue = $Node.RawJsonValue
RawJsonValue = $Node.RawJsonValue
FullValueTable = @($table)
})
return
}
if ($type -like '*GroupSettingInstance') {
foreach ($child in @($Node.ChildSettings)) {
ConvertTo-ReusableSettingDocRows -Node $child -Context $Context -ParentId $Node.SettingId -Level $Level -Definitions $Definitions
}
return
}
$rowName = Get-ReusableSettingRowName $Node $ParentId $Definitions
if ([string]::IsNullOrEmpty($rowName)) { return } # hidden by the schema
$Context.AddSetting([PSCustomObject]@{
Name = $rowName
Value = (Get-ReusableSettingRowValue $Node)
Description = $Node.Description
Category = $Node.Category
SubCategory = $Node.SubCategory
Level = $Level
SettingId = $Node.SettingId
RowIndex = $Node.RowIndex
RawValue = $Node.RawValue
RawJsonValue = $Node.RawJsonValue
DefaultValue = $Node.DefaultValue
})
# A choice can carry dependent children.
foreach ($child in @($Node.ChildSettings)) {
if ($child -and $child.PSObject.Properties['SettingId']) {
ConvertTo-ReusableSettingDocRows -Node $child -Context $Context -ParentId $Node.SettingId -Level ($Level + 1) -Definitions $Definitions
}
}
}
# The setting instance: from the object, else from the source tenant (the list
# endpoint leaves it out). Attached to the object so an export of the same run
# carries it.
function Get-ReusableSettingInstance {
param($PolicyObject, [DocumentationContext]$Context)
$obj = $PolicyObject.JsonObject
if ($obj.settingInstance) { return $obj.settingInstance }
if (-not $obj.id -or $Context.SourceTenantUnavailable -or -not (Test-DocumentationGraphAvailable)) { return $null }
try {
# minimal, not none: with none Graph drops the @odata.type of every
# setting instance, and the walker cannot tell a list from a value.
$live = Invoke-MSGraphAPI -Url "/deviceManagement/reusablePolicySettings/$($obj.id)?`$select=settinginstance,displayname,description" -ODataMetadata 'minimal' -NoError
if ($live -and $live.settingInstance) {
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'settingInstance' -Value $live.settingInstance -Force
return $live.settingInstance
}
Write-Log "Reusable setting '$($PolicyObject.Name)' ($($obj.id)) returned no settingInstance" 2
}
catch {
Write-LogError "Failed to fetch the setting instance of reusable setting '$($PolicyObject.Name)'" $_.Exception
}
return $null
}
# The configuration-categories list carries only ordinary categories; one that
# exists for reusable settings alone (Device Control) is reachable by id only.
# Fetch it once and add it to the session cache, so both the Type row and the
# walker's row categories resolve.
function Resolve-ReusableSettingCategory {
param([string]$CategoryId, [DocumentationContext]$Context)
if ([string]::IsNullOrEmpty($CategoryId)) { return }
if ($Context.CfgCategories | Where-Object id -EQ $CategoryId | Select-Object -First 1) { return }
if (-not (Test-DocumentationGraphAvailable)) { return }
try {
$cat = Invoke-MSGraphAPI -Url "/deviceManagement/configurationCategories/$CategoryId" -ODataMetadata 'minimal' -AdditionalHeaders (Get-DocAcceptLanguageHeaders $Context) -NoError
if ($cat -and $cat.id) {
$Context.CfgCategories += @($cat)
Set-CacheObject "CfgCategories" $Context.CfgCategories -Persistent
}
}
catch {
Write-LogError "Failed to fetch configuration category $CategoryId" $_.Exception
}
}
# What kind of reusable setting this is, for the basic info: the category of
# the root definition (Firewall, Device Control), else the definition's own
# name (Script), else derived from the id.
function Get-ReusableSettingTypeName {
param($RootDefinition, [string]$DefinitionId, [DocumentationContext]$Context)
if ($RootDefinition -and $RootDefinition.categoryId) {
$cat = $Context.CfgCategories | Where-Object id -EQ $RootDefinition.categoryId | Select-Object -First 1
if ($cat -and -not [string]::IsNullOrWhiteSpace([string]$cat.displayName)) { return [string]$cat.displayName }
}
$name = if ($RootDefinition) { ([string]$RootDefinition.displayName).Trim() } else { '' }
if (-not [string]::IsNullOrWhiteSpace($name) -and $name -ne 'Id') { return $name }
return Get-ReusableSettingFallbackName $DefinitionId $null
}
function Invoke-DocReusableSetting {
param($PolicyObject, [DocumentationContext]$Context)
$obj = $PolicyObject.JsonObject
if ($PolicyObject.Name) {
Add-BasicPropertyValue (Get-LanguageString 'SettingDetails.nameName') $PolicyObject.Name 'displayName'
}
$descValue = if ($obj.description) { $obj.description } else { '' }
Add-BasicPropertyValue (Get-LanguageString 'SettingDetails.descriptionName') $descValue 'description'
Initialize-SettingsCatalogSchemaCache $Context
$definitions = @(Get-ReusableSettingDefinitions $Context)
$rootDef = $null
if ($obj.settingDefinitionId) {
$rootDef = $definitions | Where-Object id -EQ $obj.settingDefinitionId | Select-Object -First 1
if ($rootDef) { Resolve-ReusableSettingCategory ([string]$rootDef.categoryId) $Context }
Add-BasicPropertyValue (Get-LanguageString 'TableHeaders.type') (Get-ReusableSettingTypeName $rootDef ([string]$obj.settingDefinitionId) $Context) 'settingDefinitionId'
}
Add-BasicAdditionalValues $PolicyObject # created / modified / version
$instance = Get-ReusableSettingInstance $PolicyObject $Context
if (-not $instance) { return }
if ($Context.Options -and $Context.Options['IncludeScripts'] -eq $false -and [string]$obj.settingDefinitionId -like '*script*') { return }
# The walker resolves names, options and categories from the inline
# definitions; its buffer is not used, the returned tree is.
Reset-SettingsCatalogPolicyBuffer
$root = Add-SettingsSetting $instance $definitions
Reset-SettingsCatalogPolicyBuffer
if (-not $root) { return }
ConvertTo-ReusableSettingDocRows -Node $root -Context $Context -ParentId $null -Level 0 -Definitions $definitions
}
class ReusableSettingDocHandler : DocumentationHandlerBase {
ReusableSettingDocHandler() {
@@ -14,54 +334,7 @@ class ReusableSettingDocHandler : DocumentationHandlerBase {
}
[void] Document([object]$PolicyObject, [DocumentationContext]$Context) {
$obj = $PolicyObject.JsonObject
if ($PolicyObject.Name) {
Add-BasicPropertyValue (Get-LanguageString 'SettingDetails.nameName') $PolicyObject.Name 'displayName'
}
$descValue = if ($obj.description) { $obj.description } else { '' }
Add-BasicPropertyValue (Get-LanguageString 'SettingDetails.descriptionName') $descValue 'description'
$category = Get-LanguageString 'TableHeaders.settings'
if ($obj.settingDefinitionId) {
$definitionLabel = Get-LanguageString 'SettingDetails.settingIdName' -IgnoreMissing
if (-not $definitionLabel) { $definitionLabel = 'Setting definition' }
Add-CustomSettingObject ([PSCustomObject]@{
Name = $definitionLabel
Value = [string]$obj.settingDefinitionId
EntityKey = 'settingDefinitionId'
Category = $category
SubCategory = $null
})
}
$rawValue = [string]$obj.settingInstance.simpleSettingValue.value
if ($rawValue -and -not ($Context.Options -and $Context.Options['IncludeScripts'] -eq $false)) {
# The discovery-script definition stores the script base64-encoded;
# fall back to the raw value for definitions that don't.
$value = $rawValue
try {
$decoded = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($rawValue))
if ($decoded) { $value = $decoded }
}
catch { }
$valueLabel = if ([string]$obj.settingDefinitionId -like '*discoveryscript*') {
Get-LanguageString 'ProactiveRemediations.Create.Settings.DetectionScriptMultiLineTextBox.label'
}
else {
$lbl = Get-LanguageString 'SettingDetails.valueName' -IgnoreMissing
if ($lbl) { $lbl } else { 'Value' }
}
Add-CustomSettingObject ([PSCustomObject]@{
Name = $valueLabel
Value = $value
EntityKey = 'settingInstanceValue'
Category = $category
SubCategory = $null
})
}
Invoke-DocReusableSetting $PolicyObject $Context
}
}
+178 -1
View File
@@ -38,9 +38,18 @@ Add-SettingsObject -Title "Graph Page Size" -Key "GraphPageSize" -Type "List" `
[PSCustomObject]@{ Name = "1000"; Value = "1000" },
[PSCustomObject]@{ Name = "All"; Value = "All" }
) `
-DefaultValue "0" -Description "How many items load at a time" `
-DefaultValue "0" -Description "How many items load at a time. All loads every page in one go." `
-SubPath "IntuneManager" -Section "IntuneManager"
# The list's "All" entry is not a number: it means no $top on the list URL and
# every page in one call, even where the view asked for a single page. Casting
# it used to throw, and the fallback made it 20 - so the "pick All" workaround
# for duplicate imports paged at 20 instead (#384).
function Test-GraphPageSizeAll
{
return ("$(Get-SettingValue 'GraphPageSize' '0')" -eq 'All')
}
Add-SettingsObject -Title "Root folder" -Key "RootFolder" -Type "Folder" `
-Description "Root folder for exporting/importing objects" `
-SubPath "IntuneManager" -Section "ImportExport"
@@ -725,6 +734,10 @@ function Get-PoliciesTypeFromObject
}
}
# The @odata.id named exactly one candidate's endpoint - remembered for the
# fallback below.
$idMatchedType = if(@($checkPolicies).Count -eq 1) { $checkPolicies[0] } else { $null }
if($checkPolicies.Count -eq 0) {
if($FromPolicyTypes.Count -gt 0 ) {
$checkPolicies = $FromPolicyTypes
@@ -758,6 +771,17 @@ function Get-PoliciesTypeFromObject
return $checkPolicies[0]
}
# An @odata.id that names exactly one type's endpoint identifies the object
# even when that type's CheckPolicy declines it. The script types' CheckPolicy
# always answers $false, so every exported PowerShell / shell / custom-attribute
# script ("@odata.id": "deviceManagement/deviceShellScripts('<id>')") was
# dropped and never imported - found by the online assignment round trip
# (2026-10-17). A strict @odata.type matcher keeps the final say, as above.
if($idMatchedType -and -not $idMatchedType.StrictODataTypeCheck) {
Write-Log "Resolved policy type '$($idMatchedType.Id)' for object with OData.id = $($PolicyObject.'@odata.id') from its endpoint (no CheckPolicy match)" 4
return $idMatchedType
}
if($null -eq $PSBoundParameters["FromPolicyTypes"]) {
# Expected not to find some policies if policy types is passed in
Write-Log "Could not find policy type based on object with OData.type = $($PolicyObject.'@odata.type') and OData.id = $($PolicyObject.'@odata.id')" 3
@@ -1073,6 +1097,159 @@ function Resolve-IntuneImportUpdateTarget
return New-IntuneImportMatchResult -Action "Create" -Message "Create new object"
}
# ---- Import candidates (#384) ------------------------------------------------
#
# The per-view Import dialog matched files only against the rows it had loaded,
# so an existing policy on a page not loaded yet was "new" and got imported a
# second time. Loading every page fixes that but costs the whole type each time
# the dialog opens, most of it never compared against anything.
#
# Instead look up only what could match the selected files, per policy type:
# - by id, on a same-tenant import (the matcher's Id strategy only runs then),
# batched through Invoke-GraphBatchRequest;
# - by a server-side name search (Get-GraphPolicies -NameFilter, which also
# re-checks client-side) for the name the other strategies compare: the name
# without the organization tokens, and every policy reference token.
# A type whose endpoint rejects $filter, or a selection that would need more
# searches than listing the type costs, is listed once instead. The result is
# merged with the rows already loaded; the matcher itself is unchanged, so the
# lookup only has to return a superset of what could match.
$script:ImportCandidateNameSearchLimit = 20
# Name searches that cover every name-based matcher strategy for one file.
function Get-IntuneImportCandidateSearchTerms
{
param($ImportPolicy)
$terms = [System.Collections.Generic.List[string]]::new()
$name = [string]$ImportPolicy.Name
if([string]::IsNullOrWhiteSpace($name)) { return @() }
# Exact name and normalized name, with one search: the LONGEST WORD of the
# normalized name. Normalization only removes organization names, trims
# separators and collapses whitespace, so each of its words occurs intact in
# every name that matches exactly or after normalization. The whole
# normalized string does not: "Baseline Windows" normalizes to "BASELINE
# WINDOWS", which is no substring of the original, and an organization name
# in the middle splits it too (code review). The matcher then picks the real
# match from what comes back. The organization itself is never searched - the
# target's copy may carry another.
$core = Normalize-IntuneImportPolicyName -Name $name
$words = @(([string]$core).Split(' ', [StringSplitOptions]::RemoveEmptyEntries) | Sort-Object Length -Descending)
# However short: "Contoso - AV" normalizes to "AV", and only "av" finds the
# existing "AV" (code review). The full name is the fallback only when the
# name is nothing but organization names - then just the exact name can match.
$term = if($words.Count -gt 0) { $words[0] } else { $name.Trim() }
[void]$terms.Add($term.ToLowerInvariant())
foreach($token in @(Get-IntuneImportPolicyReferenceTokens -Name $name)) {
if($token -and -not ($terms | Where-Object { $_ -eq $token })) { [void]$terms.Add($token) }
}
return $terms.ToArray()
}
# Existing objects of one type by id, from one batched lookup. Ids that no
# longer exist (or that the endpoint cannot GET directly) are simply absent.
function Get-IntuneImportCandidatesById
{
param($PolicyType, [string[]]$Ids, [int]$TokenId)
$requests = [System.Collections.Generic.List[PSCustomObject]]::new()
$n = 0
foreach($id in $Ids) {
[void]$requests.Add([PSCustomObject]@{ id = "$n"; method = 'GET'; url = "$(([string]$PolicyType.API).TrimStart('/'))/$id" })
$n++
}
if($requests.Count -eq 0) { return @() }
$results = @()
try { $results = @(Invoke-GraphBatchRequest $requests "Import candidates" -TokenId $TokenId -IncludedFailed -SkipWarnings) }
catch { Write-LogError "Import candidates: id lookup failed for $($PolicyType.Id)" $_.Exception; return @() }
$tokenInfo = Get-OperationTokenInfo $TokenId
$found = foreach($r in $results) {
if(-not $r -or -not $r.body -or $r.body.PSObject.Properties['error']) { continue }
if($r.PSObject.Properties['Status'] -and [int]$r.Status -ge 300) { continue }
$policy = $PolicyType.GetObject($r.body)
if(-not $policy) { continue }
if($tokenInfo) {
$policy.TenantID = $tokenInfo.TenantID
$policy._TokenID = $tokenInfo.Id
}
$policy
}
return @($found)
}
function Get-IntuneImportCandidates
{
param(
$ImportPolicies,
$LoadedPolicies,
[string]$ImportType = "alwaysImport",
[bool]$SameTenant,
# Every page of the view is loaded: the loaded rows are already complete.
[switch]$AllLoaded,
[int]$TokenId = (Get-DefaultTokenId)
)
$candidates = [System.Collections.Generic.List[object]]::new()
$seen = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
$add = {
param($p)
if(-not $p) { return }
$key = "$($p.PolicyType.Id)|$($p.Id)"
if($p.Id -and -not $seen.Add($key)) { return }
[void]$candidates.Add($p)
}
foreach($p in @($LoadedPolicies)) { & $add $p }
# Always import never compares; a complete list needs no help.
if($ImportType -eq "alwaysImport" -or $AllLoaded) { return $candidates.ToArray() }
$byType = @($ImportPolicies | Where-Object { $_ -and $_.PolicyType }) | Group-Object { $_.PolicyType.Id }
foreach($group in $byType) {
$type = $group.Group[0].PolicyType
if($SameTenant) {
$ids = @($group.Group | ForEach-Object { [string]$_.Id } | Where-Object { $_ } | Select-Object -Unique)
foreach($p in @(Get-IntuneImportCandidatesById -PolicyType $type -Ids $ids -TokenId $TokenId)) { & $add $p }
}
$terms = [System.Collections.Generic.List[string]]::new()
foreach($file in $group.Group) {
foreach($term in @(Get-IntuneImportCandidateSearchTerms $file)) {
if(-not ($terms | Where-Object { $_ -eq $term })) { [void]$terms.Add($term) }
}
}
if($terms.Count -eq 0) { continue }
# Get-GraphPolicies clears $script:GraphPagingCache on every call that is
# not a paging call. That cache is the VIEW's "more pages to load" state,
# and the dialogs read its absence as "every page is loaded" - so these
# searches made the next matching pass skip the lookup (code review). The
# view's paging state is put back whatever happens here.
$viewPaging = $script:GraphPagingCache
try {
if($type.SupportsNameFilter -ne $true -or $terms.Count -gt $script:ImportCandidateNameSearchLimit) {
Write-Log "Import candidates: listing $($type.Id) once ($($terms.Count) name searches, name filter supported: $($type.SupportsNameFilter -eq $true))"
foreach($p in @(Get-GraphPolicies -PolicyType $type.Id -TokenId $TokenId)) { & $add $p }
}
else {
foreach($term in $terms) {
foreach($p in @(Get-GraphPolicies -PolicyType $type.Id -NameFilter $term -TokenId $TokenId)) { & $add $p }
}
}
}
finally {
$script:GraphPagingCache = $viewPaging
}
}
return $candidates.ToArray()
}
function Invoke-IntuneImportReplace
{
# Replace-mode import: import the file as a NEW object, copy assignments,
+30 -3
View File
@@ -118,9 +118,11 @@ function Invoke-GraphBatchRequest
# same path even with batching on: a $batch envelope around one GET is a
# whole extra round-trip for nothing (fifty-three of them on one measured
# export).
if($requestObjects.Count -gt 0 -and (-not (Test-GraphBatchEnabled) -or $requestObjects.Count -eq 1))
# Writes under Multi Admin Approval go direct too (Test-MSGraphApprovalDirectWrites).
$approvalDirect = ($requestObjects.Count -gt 1) -and (Test-MSGraphApprovalDirectWrites $requestObjects)
if($requestObjects.Count -gt 0 -and (-not (Test-GraphBatchEnabled) -or $requestObjects.Count -eq 1 -or $approvalDirect))
{
$reason = if(Test-GraphBatchEnabled) { 'single request' } else { 'batching off' }
$reason = if($approvalDirect) { 'Multi Admin Approval' } elseif(Test-GraphBatchEnabled) { 'single request' } else { 'batching off' }
foreach($r in @(Invoke-GraphBatchRequestDirect -RequestObjects $requestObjects -BatchType $BatchType -TokenId $TokenId `
-AllPages:$AllPages -SkipWarnings:$SkipWarnings -IncludedFailed:$IncludedFailed -Reason $reason)) { [void]$directResults.Add($r) }
return $directResults.ToArray()
@@ -380,6 +382,7 @@ function Invoke-GraphBatchRequestDirect
$script:AllGraphCalls[$script:AllGraphCalls.Count - 1]
} else { $null }
$content = $null
$approvalsBefore = @(Get-MSGraphApprovalPending).Count
try { $content = Invoke-MSGraphAPI @callArgs } catch { }
$status = 0
@@ -397,7 +400,13 @@ function Invoke-GraphBatchRequestDirect
$ok = ($status -ge 200 -and $status -lt 300)
if(-not $ok -and -not $IncludedFailed) {
if(-not $SkipWarnings) { Write-Log "Direct request $($o.id) ($method $($o.url)) returned $status. Skipping..." 2 }
# A write Multi Admin Approval held is queued, not failed - say so, next
# to the request id that names the object.
$held = (@(Get-MSGraphApprovalPending).Count -gt $approvalsBefore)
if($held) {
if(-not $SkipWarnings) { Write-Log "Direct request $($o.id) ($method $($o.url)) is waiting for Multi Admin Approval" 2 }
}
elseif(-not $SkipWarnings) { Write-Log "Direct request $($o.id) ($method $($o.url)) returned $status. Skipping..." 2 }
continue
}
[void]$results.Add([PSCustomObject]@{ id = $o.id; status = $status; headers = @{}; body = $content })
@@ -1823,6 +1832,24 @@ function Get-GraphTranslatedDependencyObject
#endregion
#Region Remove Graph object properties
# Strip assignments from a create (POST) or update (PATCH) request body, in any
# casing, together with their @odata annotations. GitHub #441, measured live:
# "Assignments" makes the POST fail with 400 ("does not exist on type"), and
# lowercase "assignments" is accepted but silently ignored - the new object has
# none. PATCH refuses navigation properties outright. Assignments are applied by
# the separate assignment step, which reads them from the SOURCE object, so only
# the request body (a clone) loses them.
function Remove-GraphAssignmentsFromBody
{
param([PSCustomObject]$Body)
if($null -eq $Body) { return }
foreach($name in @($Body.PSObject.Properties | Where-Object { $_.Name -like 'assignments*' } | ForEach-Object Name)) {
Remove-Property $Body $name
}
}
function Remove-GraphPropertiesForImport
{
param(
+44
View File
@@ -156,6 +156,50 @@ function ConvertTo-MSGraphApprovalJustification
return [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($Justification))
}
# True when a Multi Admin Approval justification is configured and the queue holds
# a write. Invoke-GraphBatchRequest then sends the queue as direct requests: they
# carry the justification header (Invoke-MSGraphAPI) and report the 412 "waiting for
# approval" answer, while $batch sub-requests went out without the header and were
# refused with 400 (GitHub #442).
function Test-MSGraphApprovalDirectWrites
{
param($RequestObjects)
if([String]::IsNullOrWhiteSpace((Get-SettingValue "MultiAdminApprovalJustification"))) { return $false }
return (@($RequestObjects | Where-Object { ([string]$_.method).ToUpperInvariant() -in @('POST','PATCH','PUT','DELETE') }).Count -gt 0)
}
# Every write Multi Admin Approval held this session, in order. Invoke-MSGraphAPI
# adds to it; an operation counts what it has before it starts and reports what was
# added since, so a bulk import can say "2 waiting for approval" instead of
# "0 imported" (GitHub #442). Nested operations each see only their own entries.
$script:MSGraphApprovalPending = [System.Collections.Generic.List[PSCustomObject]]::new()
function Add-MSGraphApprovalPending
{
param([string]$Method, [string]$Url, [string]$ApprovalCode)
$script:MSGraphApprovalPending.Add([PSCustomObject]@{
Method = $Method
Url = $Url
ApprovalCode = $ApprovalCode
})
}
function Get-MSGraphApprovalPending
{
return $script:MSGraphApprovalPending.ToArray()
}
# The import dialogs' note for a run whose writes were held; $null when none were.
function Get-MSGraphApprovalPendingSummary
{
param($Count)
if(-not $Count -or [int]$Count -le 0) { return $null }
return "$Count object(s) are waiting for Multi Admin Approval. Another administrator must approve them in the Intune admin center under Tenant administration > Multi Admin Approval. The approval codes are in the log."
}
function Get-MSGraphApprovalCodeFromError
{
param($Response, $GraphError)
+8
View File
@@ -149,6 +149,14 @@ function Merge-PolicyHydrateBody
}
foreach($prop in $Body.PSObject.Properties) {
# An EMPTY assignments array from the re-read does not replace loaded
# assignments: some endpoints answer the single-object $expand with []
# while the list $expand and /assignments return the rows (Compliance
# Policy V2, measured live 2026-10-17). Exports then lost them.
if($prop.Name -eq 'assignments' -and @($prop.Value).Count -eq 0 -and
$Policy.JsonObject.PSObject.Properties['assignments'] -and @($Policy.JsonObject.assignments).Count -gt 0) {
continue
}
if($Policy.JsonObject.PSObject.Properties[$prop.Name]) {
$Policy.JsonObject.($prop.Name) = $prop.Value
}