diff --git a/CHANGELOG.md b/CHANGELOG.md index 0282a12..f5aeb6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ All notable changes to this project will be documented in this file. The format follows [Conventional Commits](https://www.conventionalcommits.org/) and [Semantic Versioning](https://semver.org/): a new feature or capability bumps MINOR, a bug fix or performance change that leaves the public surface alone bumps PATCH, and docs/tests/chore-only commits don't bump. While the module is pre-1.0 a breaking change also bumps MINOR and is called out under a **Breaking Changes** heading — 1.0.0 is reserved for the point the public surface is declared stable, after which breaking changes bump MAJOR. There is intentionally no `[Unreleased]` section — every entry is dated at ship time. +## [1.1.0] - 2026-11-16 + +### Features + +- **`Export-InforcerTenantDocumentation -Baseline` takes several baselines** and reads the tenant once. The policy list is the slow call (20 to 40 s on a large tenant) and every `-Baseline` call used to repeat it; a baseline's membership takes a fraction of a second. Without `-OutputPath` it returns one DocModel per baseline; with a directory it writes one `{TenantName}-{Baseline}-Documentation` file per baseline (a single baseline keeps the old `{TenantName}-Documentation` name; two baseline names that make the same file name get `-2`). A baseline that does not resolve is a `BaselineFilterFailed` error and the others are still exported. A file `-OutputPath` with several baselines is refused (`OutputPathIsFileForSeveralBaselines`). Measured on the inforcer Blueprint Library: 22 baselines in 48 s, previously about 34 minutes. Graph names (`-FetchGraphData`) and the Settings Catalog are resolved once for all of them. + +### Bug Fixes + +Found by reading every per-baseline document of the inforcer Blueprint Library. + +- **Settings nested more than two objects deep rendered as empty rows.** Below two levels an object fell through to `ToString()`, which is empty for a `PSCustomObject`. Conditional Access device filter rules, guest and external user types and Entra's passkey migration opt-out showed nothing. The limit is now 10 and exists only to stop runaway recursion. +- **A setting stored as a dotted `@odata.type` was dropped.** Entra's device registration setting is `azureADRegistration.allowedToRegister.@odata.type = #microsoft.graph.allDeviceRegistrationMembership`, so "Users may register their devices" showed no setting. A dotted path ending in `@odata.type` is now rendered as that setting ("All Device Registration Membership"). Every other `@odata` key is still skipped. +- **List items showed only "N items".** An item without a display name or name was dropped, and the fields of named items were never shown, so an authentication method's Include Targets read "1 items" and nothing else. Each item now lists its fields ("Item 1", Target Type group, ID all_users). A single-field item is one row, and an id is never used as a label, so it stays a value that Graph resolution can reach. Objects, lists and encoded payloads inside an item render like any other setting, and an item's description is kept. A list and an item label with fields under it are headers, so `Compare-InforcerEnvironments` keeps them in the setting path. A field with the same value on every item of a list is shown once, under "All items", and a field that repeats the item's label is left out: Defender's custom indicators (492 Shadow AI domains) would otherwise repeat twelve identical fields per domain, about 8,400 rows for one policy, where it is now about 2,000. A field goes under "All items" only when every item has it with that value, and `Compare-InforcerEnvironments` keeps every item's own fields, so one changed item never moves the rest. A MAM app is one row again, labelled by its package id. +- **The HTML hid section headers.** With "hide empty" on (the default), a header row with no value was hidden like an empty setting, so the rows under it lost their context. Headers now stay visible. +- **Authentication strength combinations fell apart.** `allowedCombinations` items such as `password,softwareOath` were joined with commas and split again, giving "…, password, Software OATH Token, password, …". A list whose items contain a comma is now joined with `; `, and each combination reads "Password + Software OATH Token". + ## [1.0.1] - 2026-11-16 ### Bug Fixes diff --git a/Tests/Fix.DocReadability.Tests.ps1 b/Tests/Fix.DocReadability.Tests.ps1 new file mode 100644 index 0000000..f92ebe2 --- /dev/null +++ b/Tests/Fix.DocReadability.Tests.ps1 @@ -0,0 +1,333 @@ +# Fix.DocReadability.Tests.ps1 +# Export-InforcerTenantDocumentation readability, found by reading every per-baseline document of the +# inforcer Blueprint Library (2026-11-16): settings below two levels rendered empty, a dotted +# @odata.type setting was dropped, list items showed only "N items", authentication strength +# combinations fell apart, and every -Baseline re-read the whole tenant. Fixtures are synthetic. + +BeforeAll { + Remove-Module -Name 'InforcerCommunity' -ErrorAction SilentlyContinue + Import-Module (Join-Path $PSScriptRoot '../module/InforcerCommunity.psd1') -Force + $script:M = Get-Module InforcerCommunity + + function global:Get-ReadabilityRows([object]$PolicyData) { + & $script:M { param($pd) ConvertTo-FlatSettingRows -PolicyData $pd } $PolicyData + } +} + +AfterAll { + Remove-Item function:global:Get-ReadabilityRows -ErrorAction SilentlyContinue +} + +Describe 'ConvertTo-FlatSettingRows shows what the policy configures' { + It 'renders a setting nested three objects deep instead of an empty row' { + $rows = Get-ReadabilityRows ([pscustomobject]@{ data = [pscustomobject]@{ PasskeyMigrationOptOut = [pscustomobject]@{ + optOutSettings = [pscustomobject]@{ passkeyDynamicMigration = $true } } } }) + $leaf = @($rows | Where-Object { $_.Value -eq 'True' }) + $leaf.Count | Should -Be 1 + $leaf[0].Name | Should -Match 'Passkey Dynamic Migration' + $leaf[0].Indent | Should -Be 3 + } + + It 'renders a Conditional Access device filter rule' { + $rows = Get-ReadabilityRows ([pscustomobject]@{ conditions = [pscustomobject]@{ devices = [pscustomobject]@{ + deviceFilter = [pscustomobject]@{ mode = 'exclude'; rule = 'device.isCompliant -eq True' } } } }) + @($rows | Where-Object { $_.Value -eq 'device.isCompliant -eq True' }).Count | Should -Be 1 + } + + It 'turns a dotted path ending in @odata.type into the setting it names' { + $rows = Get-ReadabilityRows ([pscustomobject]@{ data = [pscustomobject]@{ UserAllowedToRegister = [pscustomobject]@{ + 'azureADRegistration.allowedToRegister.@odata.type' = '#microsoft.graph.allDeviceRegistrationMembership' } } }) + $leaf = @($rows | Where-Object { $_.Value -match 'Registration Membership' }) + $leaf.Count | Should -Be 1 + $leaf[0].Value | Should -Not -Match 'microsoft\.graph|#' + } + + It 'still drops @odata.type and other @odata keys that are serialisation metadata' { + $rows = Get-ReadabilityRows ([pscustomobject]@{ '@odata.type' = '#microsoft.graph.x'; '_value@odata.type' = '#Guid' + 'grant@odata.context' = 'https://graph.microsoft.com/x'; state = 'enabled' }) + @($rows).Count | Should -Be 1 + $rows[0].Value | Should -Be 'enabled' + } + + It 'lists every field of a list item that has no name' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ includeTargets = @([pscustomobject]@{ targetType = 'group'; id = 'all_users' }; [pscustomobject]@{ id = $null }) })) + $rows[0].Value | Should -Be '2 items' + $rows[1].Name | Should -Be 'Item 1' + @($rows | Where-Object { $_.Name -eq 'Item 2' }).Count | Should -Be 0 -Because 'an item with nothing set has nothing to show' + @($rows | Where-Object { $_.Value -eq 'group' -and $_.Indent -eq 2 }).Count | Should -Be 1 + @($rows | Where-Object { $_.Value -eq 'all_users' -and $_.Indent -eq 2 }).Count | Should -Be 1 + } + + It 'labels a named list item by its name and keeps its id out of the label' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ passkeyProfiles = @([pscustomobject]@{ + id = '00000000-0000-0000-0000-000000000001'; name = 'Default passkey profile'; passkeyTypes = 'deviceBound' }) })) + $rows[1].Name | Should -Be 'Default passkey profile' + @($rows | Where-Object { $_.Value -eq 'deviceBound' }).Count | Should -Be 1 + @($rows | Where-Object { "$($_.Name)$($_.Value)" -match '00000000-0000' }).Count | Should -Be 0 + } + + It 'gives a list item with a single field one row' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ excludeTargets = @([pscustomobject]@{ id = '00000000-0000-0000-0000-0000000000a1' }) })) + $rows.Count | Should -Be 2 + $rows[1].Value | Should -Be '00000000-0000-0000-0000-0000000000a1' -Because 'as a value, GUID resolution and masking can reach it' + } + + It 'marks a list and its item labels as headers, so comparisons keep their context' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ includeTargets = @([pscustomobject]@{ targetType = 'group'; id = 'all_users' }) })) + $rows[0].IsConfigured | Should -BeFalse -Because 'the list is a parent in the setting path' + $rows[1].IsConfigured | Should -BeFalse -Because 'Item 1 is a parent of its fields' + @($rows | Where-Object { $_.Value -eq 'all_users' })[0].IsConfigured | Should -BeTrue + } + + It 'keeps a name-only list item a setting' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ apps = @([pscustomobject]@{ bundleId = 'com.example.app' }) })) + @($rows | Where-Object { $_.Name -eq 'com.example.app' })[0].IsConfigured | Should -BeTrue + } + + It 'renders objects and lists nested inside a list item' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ profiles = @([pscustomobject]@{ name = 'P1' + options = [pscustomobject]@{ enabled = $true }; types = @('a', 'b') }) })) + $enabled = @($rows | Where-Object { $_.Name -match 'Enabled' -and $_.Value -eq 'True' }) + $enabled.Count | Should -Be 1 + $enabled[0].Indent | Should -Be 3 + @($rows | Where-Object { $_.Value -eq 'a, b' }).Count | Should -Be 1 + } + + It 'decodes an encoded payload inside a list item like any other payload' { + $b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('')) + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ profiles = @([pscustomobject]@{ name = 'P1'; payload = $b64 }) })) + @($rows | Where-Object { "$($_.Value)" -like '__SCRIPT_CODE__')).Count | Should -Be 0 + } +} + +Describe 'A comparison sees every list item''s own fields' { + It 'reports only the item that changed when the others share its old value' { + $result = & $script:M { + $model = { + param($p2Action) + ConvertTo-InforcerDocModel -ComparisonMode -DocData @{ + Tenant = [pscustomobject]@{ tenantFriendlyName = 'T'; msTenantId = '00000000-0000-0000-0000-000000000001' } + TenantId = 1; CollectedAt = [datetime]::UtcNow; Baselines = @() + Policies = @([pscustomobject]@{ id = 'p1'; displayName = 'Indicators'; policyTypeId = 3; product = 'Defender' + primaryGroup = 'Endpoint'; secondaryGroup = 'Indicators' + policyData = [pscustomobject]@{ indicators = @( + [pscustomobject]@{ displayName = 'a.example'; action = 'Block' } + [pscustomobject]@{ displayName = 'b.example'; action = $p2Action }) } }) + } + } + Compare-InforcerDocModels -SourceModel (& $model 'Block') -DestinationModel (& $model 'Allow') + } + $result.Counters.Conflicting | Should -Be 1 -Because 'only b.example changed' + $result.Counters.SourceOnly | Should -Be 0 + $result.Counters.DestOnly | Should -Be 0 + } + + It 'keeps item fields per item in lists nested inside objects and items too' { + $pd = [pscustomobject]@{ outer = [pscustomobject]@{ profiles = @([pscustomobject]@{ name = 'P1'; targets = @( + [pscustomobject]@{ displayName = 'a'; mode = 'on' } + [pscustomobject]@{ displayName = 'b'; mode = 'on' }) }) } } + $rows = @(& $script:M { param($pd) ConvertTo-FlatSettingRows -PolicyData $pd -ComparisonMode } $pd) + @($rows | Where-Object { $_.Name -eq 'All items' }).Count | Should -Be 0 + @($rows | Where-Object { $_.Name -eq 'Mode' }).Count | Should -Be 2 + @(Get-ReadabilityRows $pd | Where-Object { $_.Name -eq 'All items' }).Count | Should -Be 1 -Because 'a document still shows it once' + } +} diff --git a/docs/CMDLET-REFERENCE.md b/docs/CMDLET-REFERENCE.md index 618032f..b325b15 100644 --- a/docs/CMDLET-REFERENCE.md +++ b/docs/CMDLET-REFERENCE.md @@ -776,7 +776,7 @@ The HTML output features a modern admin dashboard design with a collapsible side | **Show** | Switch | No | Open the generated HTML in the default browser, each file once per call (also when tenants are piped). Requires `-OutputPath` and `-Format Html`. **Defaults to on interactively, off in CI** (`CI`, `TF_BUILD`, `GITHUB_ACTIONS`, `GITLAB_CI`, `JENKINS_URL`, `TEAMCITY_VERSION`, `BUILDKITE`). `-Show` forces it, `-Show:$false` suppresses it; an explicit value always wins. | | **SettingsCatalogPath** | String | No | Path to a local `settings.json` for Intune Settings Catalog name resolution. When omitted, the latest data is downloaded from the [IntuneSettingsCatalogData](https://github.com/royklo/IntuneSettingsCatalogData) GitHub release and cached at `~/.inforcercommunity/data/settings.json` (~65 MB). The cache is used as is for 24 hours; after that the module checks the release and downloads only when a newer catalog exists. A download replaces the cache only when it is a valid catalog of at most 512 MB. Offline, the cached copy is used, or raw setting IDs when there is none. | | **FetchGraphData** | Switch | No | Signs in to Microsoft Graph interactively for the exported tenant (or reuses an existing Graph session for that tenant that already has the scopes), then resolves IDs to names: assignment groups and filters, scope tags, and the groups, directory roles, named locations and applications in Conditional Access policies. Requests `Directory.Read.All`, `Policy.Read.All` and `DeviceManagementConfiguration.Read.All`. Requires the `Microsoft.Graph.Authentication` module; without it, or when sign-in fails, raw IDs are kept with a warning. See [Graph integration](#graph-integration--fetchgraphdata). | -| **Baseline** | String | No | Filter to policies belonging to a specific baseline (name or ID). Policies are matched by id, by name only when there is no id. A same-named policy whose product, category or description differs is not used in its place, and one that still matches several is left out; both are named in a warning. A baseline that cannot be resolved or holds no policies is an error (`BaselineFilterFailed`) and nothing is exported. | +| **Baseline** | String[] | No | Filter to policies belonging to one or more baselines (names or IDs). Several baselines read the tenant once and produce one DocModel, or one `{TenantName}-{Baseline}-Documentation` file, per baseline. Policies are matched by id, by name only when there is no id. A same-named policy whose product, category or description differs is not used in its place, and one that still matches several is left out; both are named in a warning. A baseline that cannot be resolved or holds no policies is an error (`BaselineFilterFailed`); the other baselines are still exported. | | **Tag** | String | No | Filter to policies with a specific inforcer tag (case-insensitive). | ### Examples diff --git a/module/InforcerCommunity.psd1 b/module/InforcerCommunity.psd1 index ef101db..0c3d210 100644 --- a/module/InforcerCommunity.psd1 +++ b/module/InforcerCommunity.psd1 @@ -1,6 +1,6 @@ @{ RootModule = 'InforcerCommunity.psm1' - ModuleVersion = '1.0.1' + ModuleVersion = '1.1.0' GUID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' Author = 'Roy Klooster' Description = 'Community PowerShell module for the Inforcer API. Created by Roy Klooster. Not owned or officially maintained by Inforcer.' @@ -38,7 +38,7 @@ PSData = @{ ProjectUri = 'https://github.com/royklo/InforcerCommunity' LicenseUri = 'https://github.com/royklo/InforcerCommunity/blob/main/LICENSE' - ReleaseNotes = 'v1.0.1: Export-InforcerTenantDocumentation -Baseline documents exactly the baseline''s policies (same-named policies no longer leak in); a -Baseline that does not resolve or holds no policies is an error (BaselineFilterFailed) instead of exporting the whole tenant; name/value settings keep their values; -FetchGraphData reuses an app-only Graph session instead of opening a browser. See CHANGELOG.md.' + ReleaseNotes = 'v1.1.0: Export-InforcerTenantDocumentation -Baseline takes several baselines and reads the tenant once (22 baselines: 34 min -> 48 s). Documents now show settings nested more than two levels deep, list items with their fields, Entra settings stored as a dotted @odata.type, and authentication strength combinations intact. See CHANGELOG.md.''s policies (same-named policies no longer leak in); a -Baseline that does not resolve or holds no policies is an error (BaselineFilterFailed) instead of exporting the whole tenant; name/value settings keep their values; -FetchGraphData reuses an app-only Graph session instead of opening a browser. See CHANGELOG.md.' Tags = @('Inforcer', 'API', 'Community') } } diff --git a/module/Private/ConvertTo-InforcerDocModel.ps1 b/module/Private/ConvertTo-InforcerDocModel.ps1 index 420f9b9..a6229f0 100644 --- a/module/Private/ConvertTo-InforcerDocModel.ps1 +++ b/module/Private/ConvertTo-InforcerDocModel.ps1 @@ -374,7 +374,7 @@ function ConvertTo-InforcerDocModel { } } elseif ($null -ne $policy.policyData) { # Non-catalog -- use ConvertTo-FlatSettingRows (per D-07) - foreach ($row in (ConvertTo-FlatSettingRows -PolicyData $policy.policyData)) { + foreach ($row in (ConvertTo-FlatSettingRows -PolicyData $policy.policyData -ComparisonMode:$ComparisonMode)) { [void]$settings.Add($row) } } @@ -419,7 +419,16 @@ function ConvertTo-InforcerDocModel { $val = $row.Value # Resolve camelCase values (e.g. allowedCombinations like "password,softwareOath") $val = $row.Value - if (-not [string]::IsNullOrWhiteSpace($val) -and $val -is [string]) { + if ($name -eq 'Allowed Combinations' -and $val -is [string] -and $val.Contains(';')) { + # Only this setting: other values hold semicolons too (scripts, extension lists). + # A list whose items hold commas is joined with '; ' (ConvertTo-FlatSettingRows), so + # each item is one combination: "password,softwareOath" -> "Password + Software OATH Token". + $row.Value = @(foreach ($item in $val -split ';') { + $it = (($item -split ',') | ForEach-Object { $_.Trim() }) -join ',' + if ($caFriendlyValues.ContainsKey($it)) { $caFriendlyValues[$it] } + else { @(foreach ($p in $it -split ',') { if ($caFriendlyValues.ContainsKey($p)) { $caFriendlyValues[$p] } else { $p } }) -join ' + ' } + }) -join '; ' + } elseif (-not [string]::IsNullOrWhiteSpace($val) -and $val -is [string]) { # Try full value first (handles combo keys like "password,microsoftAuthenticatorPush") $trimmedVal = $val.Trim() $normalizedVal = (($trimmedVal -split ',') | ForEach-Object { $_.Trim() }) -join ',' diff --git a/module/Private/ConvertTo-InforcerHtml.ps1 b/module/Private/ConvertTo-InforcerHtml.ps1 index 39efe9b..fa577c0 100644 --- a/module/Private/ConvertTo-InforcerHtml.ps1 +++ b/module/Private/ConvertTo-InforcerHtml.ps1 @@ -999,6 +999,10 @@ tr:hover td { background: var(--row-hover); } elseif ($trimmed -match '^\s*#!/') { $codeClass = 'sh-code'; $summaryClass = 'sh-code-summary'; $label = 'View script' } else { $codeClass = 'ps-code'; $summaryClass = 'ps-code-summary'; $label = 'View script' } $settingVal = "
$label
$encCode
" + } elseif ($setting.IsConfigured -eq $false -and [string]::IsNullOrWhiteSpace("$($setting.Value)")) { + # A header: left blank rather than marked empty, so hide-empty keeps it visible + # and the rows under it keep their context. + $settingVal = '' } else { $settingVal = ConvertTo-SafeHtmlValue -Value $setting.Value -AllowMultiValue } diff --git a/module/Private/ConvertTo-InforcerSettingRows.ps1 b/module/Private/ConvertTo-InforcerSettingRows.ps1 index 9698d59..55a4868 100644 --- a/module/Private/ConvertTo-InforcerSettingRows.ps1 +++ b/module/Private/ConvertTo-InforcerSettingRows.ps1 @@ -224,6 +224,9 @@ function ConvertTo-FlatSettingRows { The policyData object from a non-catalog policy. May be $null (returns empty list). .PARAMETER Depth Current nesting depth (recursion accumulator). Default 0. + .PARAMETER ComparisonMode + Keep every list item's fields under that item. A document shows a field shared by every + item once; a comparison needs each item's own path, or one changed item moves the rest. .EXAMPLE ConvertTo-FlatSettingRows -PolicyData $policy.policyData #> @@ -233,16 +236,18 @@ function ConvertTo-FlatSettingRows { $PolicyData, [Parameter()] - [int]$Depth = 0 + [int]$Depth = 0, + + [Parameter()] + [switch]$ComparisonMode ) $rows = [System.Collections.Generic.List[object]]::new() if ($null -eq $PolicyData) { return $rows } - # Track emitted dotted-path parent rows to avoid duplicates (only init at top level) - if ($Depth -eq 0) { - $script:_emittedDotParents = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) - } + # Dotted-path parent rows already emitted for this object. Per object, not per policy: two list + # items with the same dotted keys each need the parent row in their own path. + $emittedDotParents = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) $skip = @( '@odata.type', '@odata.context', 'id', 'createdDateTime', 'lastModifiedDateTime', @@ -251,24 +256,34 @@ function ConvertTo-FlatSettingRows { 'policyGuid' ) + # Only a guard against runaway recursion. It was 2, and below that an object fell through to + # ToString(), which is empty for a PSCustomObject: a Conditional Access device filter rule, the + # guest user types and Entra's passkey migration opt-out rendered as empty rows. + $maxDepth = 10 + foreach ($prop in $PolicyData.PSObject.Properties) { if ($prop.Name -in $skip) { continue } - if ($prop.Name -match '@odata') { continue } + # A dotted path ending in @odata.type is the setting itself, e.g. Entra's + # azureADRegistration.allowedToRegister.@odata.type = #microsoft.graph.allDeviceRegistrationMembership + # ("all users may register"). Every other @odata key is serialisation metadata. + if ($prop.Name -match '^(?.+)\.@odata\.type$' -and $prop.Value -is [string]) { + $prop = [PSCustomObject]@{ Name = $Matches.path; Value = (ConvertTo-FriendlySettingName -Name ($prop.Value -replace '^#?microsoft\.graph\.', '')) } + } elseif ($prop.Name -match '@odata') { continue } # Skip internal flags (but keep linkedComplianceScript — it's rendered by MR card) if ($prop.Name -eq '_claimedByCompliancePolicy') { continue } if ($prop.Name -eq 'Length' -and $prop.Value -is [int]) { continue } $val = $prop.Value - if ($val -is [PSObject] -and $val.PSObject.Properties.Count -gt 0 -and $Depth -lt 2) { + if ($val -is [PSObject] -and $val.PSObject.Properties.Count -gt 0 -and $Depth -lt $maxDepth) { [void]$rows.Add([PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $prop.Name) Value = '' Indent = $Depth IsConfigured = $false }) - foreach ($r in (ConvertTo-FlatSettingRows -PolicyData $val -Depth ($Depth + 1))) { + foreach ($r in (ConvertTo-FlatSettingRows -PolicyData $val -Depth ($Depth + 1) -ComparisonMode:$ComparisonMode)) { [void]$rows.Add($r) } - } elseif ($val -is [array] -and $val.Count -gt 0 -and $val[0] -is [PSObject] -and $Depth -lt 2) { + } elseif ($val -is [array] -and $val.Count -gt 0 -and $val[0] -is [PSObject] -and $Depth -lt $maxDepth) { # Array of objects — show count + extract display names (original behavior) # Special handling: recurse into scheduledActionConfigurations for compliance rules $propLower = $prop.Name.ToLowerInvariant() @@ -282,59 +297,110 @@ function ConvertTo-FlatSettingRows { }) foreach ($item in $val) { if ($item -is [PSObject]) { - foreach ($r in (ConvertTo-FlatSettingRows -PolicyData $item -Depth ($Depth + 1))) { + foreach ($r in (ConvertTo-FlatSettingRows -PolicyData $item -Depth ($Depth + 1) -ComparisonMode:$ComparisonMode)) { [void]$rows.Add($r) } } } } else { + # A header (IsConfigured $false): the items below it are the settings, and a + # comparison needs the list in their path to tell two lists' items apart. [void]$rows.Add([PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $prop.Name) Value = "$($val.Count) items" Indent = $Depth - IsConfigured = $true + IsConfigured = $false }) + $itemNumber = 0 + $entries = [System.Collections.Generic.List[object]]::new() foreach ($item in $val) { - if ($item -is [PSObject]) { - $itemName = $null - foreach ($nameField in @('displayName', 'name', 'id', 'bundleId', 'packageId')) { - $nv = $item.PSObject.Properties[$nameField] - if ($nv -and $nv.Value) { $itemName = $nv.Value.ToString(); break } - } - # Fallback: check nested mobileAppIdentifier (MAM app protection policies) - if (-not $itemName) { - $mai = $item.PSObject.Properties['mobileAppIdentifier'] - if ($mai -and $mai.Value -is [PSObject]) { - foreach ($nameField in @('bundleId', 'packageId')) { - $nv2 = $mai.Value.PSObject.Properties[$nameField] - if ($nv2 -and $nv2.Value) { $itemName = $nv2.Value.ToString(); break } - } + if ($item -isnot [PSObject]) { continue } + $itemNumber++ + # The label is a human-readable field. An id is not: it stays a value row, + # where GUID resolution and masking can reach it. + $itemName = $null; $labelField = $null + foreach ($nameField in @('displayName', 'name', 'bundleId', 'packageId')) { + $nv = $item.PSObject.Properties[$nameField] + if ($nv -and $nv.Value) { $itemName = $nv.Value.ToString(); $labelField = $nameField; break } + } + # Fallback: check nested mobileAppIdentifier (MAM app protection policies) + if (-not $itemName) { + $mai = $item.PSObject.Properties['mobileAppIdentifier'] + if ($mai -and $mai.Value -is [PSObject]) { + foreach ($nameField in @('bundleId', 'packageId')) { + $nv2 = $mai.Value.PSObject.Properties[$nameField] + if ($nv2 -and $nv2.Value) { $itemName = $nv2.Value.ToString(); $labelField = 'mobileAppIdentifier'; break } } } - # A name/value pair (Entra directory setting templates such as Password - # Protection) carries its setting in 'value'. It used to be dropped, so - # "Lockout Threshold" rendered empty while the policy set it to 10. - $itemValue = '' - $vp = $item.PSObject.Properties['value'] - if ($itemName -and $vp -and ($vp.Value -is [string] -or $vp.Value -is [ValueType])) { - $itemValue = $vp.Value.ToString() - $itemName = ConvertTo-FriendlySettingName -Name $itemName - } - if ($itemName) { - [void]$rows.Add([PSCustomObject]@{ - Name = $itemName - Value = $itemValue - Indent = $Depth + 1 - IsConfigured = $true - }) + } + # A name/value pair (Entra directory setting templates such as Password + # Protection) carries its setting in 'value'. + $vp = $item.PSObject.Properties['value'] + if ($itemName -and $vp -and ($vp.Value -is [string] -or $vp.Value -is [ValueType])) { + $entries.Add(@{ Row = [PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $itemName); Value = $vp.Value.ToString(); Indent = $Depth + 1; IsConfigured = $true } }) + continue + } + # Every other field of the item, through the same rendering as any setting (decoding, + # dotted paths, nesting). They used to be dropped, so an authentication method's + # Include Targets showed "1 items" and nothing else. + $fields = [ordered]@{} + foreach ($ip in $item.PSObject.Properties) { + # @odata keys are left to the renderer, which keeps a dotted @odata.type setting. + if ($ip.Name -eq $labelField -or ($itemName -and $ip.Name -eq 'id')) { continue } + $fields[$ip.Name] = $ip.Value + } + $fieldRows = [System.Collections.Generic.List[object]]::new() + # The renderer skips 'id' and 'description' as policy metadata. On an item they are + # content: the id is an unlabelled item's identity, the description says what it is. + foreach ($own in @(@{ Key = 'id'; Name = 'ID'; Use = (-not $itemName) }, @{ Key = 'description'; Name = 'Description'; Use = $true })) { + if ($own.Use -and $fields.Contains($own.Key) -and "$($fields[$own.Key])" -ne '') { + $fieldRows.Add([PSCustomObject]@{ Name = $own.Name; Value = "$($fields[$own.Key])"; Indent = $Depth + 2; IsConfigured = $true }) } } + foreach ($r in (ConvertTo-FlatSettingRows -PolicyData ([PSCustomObject]$fields) -Depth ($Depth + 2) -ComparisonMode:$ComparisonMode)) { + if ($r.IsConfigured -and [string]::IsNullOrEmpty("$($r.Value)")) { continue } + # A field that repeats the label (an indicator's title and value) says nothing new. + if (-not $ComparisonMode -and $itemName -and $r.Indent -eq $Depth + 2 -and $r.IsConfigured -and "$($r.Value)" -eq $itemName) { continue } + $fieldRows.Add($r) + } + $keys = [System.Collections.Generic.HashSet[string]]::new() + foreach ($r in $fieldRows) { if ($r.IsConfigured -and $r.Indent -eq $Depth + 2) { [void]$keys.Add("$($r.Name)`0$($r.Value)") } } + $entries.Add(@{ Name = $itemName; Number = $itemNumber; Fields = $fieldRows; Keys = $keys }) + } + # A top-level field with the same value on every item is shown once, under "All items": + # Defender's 492 Shadow AI indicators differ only in domain, type and timestamps, and + # repeating the other twelve fields per domain made one policy 8,000 rows. + # Every entry takes part, so "All items" never claims a field one of them lacks. + $shared = [System.Collections.Generic.HashSet[string]]::new() + if (-not $ComparisonMode -and $entries.Count -gt 1 -and -not @($entries | Where-Object { $_.Row })) { + $shared.UnionWith($entries[0].Keys) + foreach ($e in $entries) { $shared.IntersectWith($e.Keys) } + } + if ($shared.Count) { + [void]$rows.Add([PSCustomObject]@{ Name = 'All items'; Value = ''; Indent = $Depth + 1; IsConfigured = $false }) + foreach ($r in $entries[0].Fields) { if ($r.IsConfigured -and $r.Indent -eq $Depth + 2 -and $shared.Contains("$($r.Name)`0$($r.Value)")) { [void]$rows.Add($r) } } + } + foreach ($e in $entries) { + if ($e.Row) { [void]$rows.Add($e.Row); continue } + $fieldRows = @($e.Fields | Where-Object { -not ($_.IsConfigured -and $_.Indent -eq $Depth + 2 -and $shared.Contains("$($_.Name)`0$($_.Value)")) }) + if (-not $e.Name -and $fieldRows.Count -eq 1 -and $fieldRows[0].IsConfigured) { + $fieldRows[0].Indent = $Depth + 1 + [void]$rows.Add($fieldRows[0]) + continue + } + if (-not $e.Name -and $fieldRows.Count -eq 0) { continue } + # The label is a header over its fields; a name-only item is itself the setting. + [void]$rows.Add([PSCustomObject]@{ Name = $(if ($e.Name) { $e.Name } else { "Item $($e.Number)" }); Value = ''; Indent = $Depth + 1; IsConfigured = ($fieldRows.Count -eq 0) }) + foreach ($r in $fieldRows) { [void]$rows.Add($r) } } } } else { $strVal = if ($null -eq $val) { '' } elseif ($val -is [array]) { - $joined = @($val | ForEach-Object { if ($_ -is [string] -or $_ -is [ValueType]) { $_.ToString() } }) -join ', ' + $items = @($val | ForEach-Object { if ($_ -is [string] -or $_ -is [ValueType]) { $_.ToString() } }) + # An item that holds a comma itself (authentication strength combinations + # such as "password,softwareOath") would merge into its neighbours. + $joined = $items -join $(if (@($items | Where-Object { $_.Contains(',') }).Count) { '; ' } else { ', ' }) if ([string]::IsNullOrWhiteSpace($joined) -and $val.Count -gt 0) { "$($val.Count) items" } else { $joined } } else { $val.ToString() } # hashedScriptContent matches this pattern too, but the helper rejects digests. @@ -349,8 +415,8 @@ function ConvertTo-FlatSettingRows { $parentName = ConvertTo-FriendlySettingName -Name $segments[$i] # Only emit parent row if it hasn't been emitted yet (track via a script-scoped set) $parentKey = ($segments[0..$i] -join '.').ToLowerInvariant() - if (-not $script:_emittedDotParents.Contains($parentKey)) { - [void]$script:_emittedDotParents.Add($parentKey) + if (-not $emittedDotParents.Contains($parentKey)) { + [void]$emittedDotParents.Add($parentKey) [void]$rows.Add([PSCustomObject]@{ Name = $parentName Value = '' diff --git a/module/Public/Export-InforcerTenantDocumentation.ps1 b/module/Public/Export-InforcerTenantDocumentation.ps1 index bd1b064..427b2f6 100644 --- a/module/Public/Export-InforcerTenantDocumentation.ps1 +++ b/module/Public/Export-InforcerTenantDocumentation.ps1 @@ -65,14 +65,17 @@ Microsoft.Graph.Authentication module. If Graph cannot be reached, or refuses a call for a missing permission, the affected names stay as raw IDs with a warning. .PARAMETER Baseline - Filter to only policies that belong to a specific baseline. Accepts a baseline GUID or - friendly name (e.g., "Inforcer Blueprint Baseline - Tier 1 - Foundations"). Uses the + Filter to only policies that belong to a baseline. Accepts one or more baseline GUIDs or + friendly names (e.g., "Inforcer Blueprint Baseline - Tier 1 - Foundations"). Uses the Inforcer alignment details API to retrieve the list of policies in the baseline, then filters the documentation to only those policies. The baseline name is shown in the header. + Several baselines read the tenant once and produce one DocModel, or with -OutputPath one + {TenantName}-{Baseline}-Documentation file, per baseline. Each baseline policy is matched by id; by name only when it has no id the tenant knows. A same-named policy whose product, category or description differs is a different policy and is - not used in its place; one that still matches several is left out. Both are named in a warning. A baseline that cannot be resolved, or holds no - policies, is an error (BaselineFilterFailed) and nothing is exported. + not used in its place; one that still matches several is left out. Both are named in a + warning. A baseline that cannot be resolved, or holds no policies, is an error + (BaselineFilterFailed); nothing is exported for it and the other baselines still are. .PARAMETER Tag Filter to only policies that have a specific Inforcer tag (e.g., "IAM - Core", "Tier 1"). Matches against the tag name property on each policy (case-insensitive, contains match). @@ -130,7 +133,7 @@ param( [switch]$FetchGraphData, [Parameter(Mandatory = $false)] - [string]$Baseline, + [string[]]$Baseline, [Parameter(Mandatory = $false)] [string]$Tag @@ -144,6 +147,11 @@ begin { process { $tenantCount++ +if (@($Baseline).Count -gt 1 -and $Format.Count -eq 1 -and $OutputPath -and [System.IO.Path]::HasExtension($OutputPath)) { + throw [System.Management.Automation.ErrorRecord]::new( + [System.ArgumentException]::new("-OutputPath '$OutputPath' is a file, so each baseline would overwrite the last. Pass a directory; each baseline gets its own {TenantName}-{Baseline}-Documentation file."), + 'OutputPathIsFileForSeveralBaselines', [System.Management.Automation.ErrorCategory]::InvalidArgument, $OutputPath) +} if ($tenantCount -gt 1 -and $Format.Count -eq 1 -and $OutputPath -and [System.IO.Path]::HasExtension($OutputPath)) { throw [System.Management.Automation.ErrorRecord]::new( [System.ArgumentException]::new("-OutputPath '$OutputPath' is a file, so a second tenant would overwrite the first. Pass a directory when piping several tenants; each gets its own {TenantName}-Documentation file."), @@ -175,61 +183,7 @@ if (-not [string]::IsNullOrEmpty($resolvedCatalogPath)) { $docData = Get-InforcerDocData @docDataParams if ($null -eq $docData) { return } -# Filter to baseline policies if -Baseline specified -$baselineFilterName = $null -if (-not [string]::IsNullOrWhiteSpace($Baseline)) { - Write-Host "Filtering to baseline: $Baseline" -ForegroundColor Cyan - $baselineFilterName = Select-InforcerBaselinePolicies -DocData $docData -BaselineId $Baseline -WarningVariable selectWarnings - # This used to warn and export every policy in the tenant, under the baseline's name: a - # document that claims to be one baseline and is the whole estate. Compare treats the same - # failure as an error (SourceBaselineFilterFailed); so does Export now. - if ($null -eq $baselineFilterName) { - $why = if ($selectWarnings) { " $(@($selectWarnings)[-1])" } else { '' } - Write-Error -Message "Could not filter to baseline '$Baseline', so nothing was exported.$why" ` - -ErrorId 'BaselineFilterFailed' -Category InvalidResult - return - } -} - -# Filter by tag if -Tag specified -if (-not [string]::IsNullOrWhiteSpace($Tag)) { - Write-Host "Filtering to tag: $Tag" -ForegroundColor Cyan - $originalCount = @($docData.Policies).Count - - # Collected before the filter so a no-match can name the tags that do exist. - $availableTags = [System.Collections.Generic.SortedSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) - foreach ($pol in @($docData.Policies)) { - foreach ($t in @($pol.tags)) { - if ($null -eq $t) { continue } - $n = if ($t -is [PSObject] -and $t.PSObject.Properties['name']) { $t.name } else { $t.ToString() } - if (-not [string]::IsNullOrWhiteSpace($n)) { [void]$availableTags.Add($n) } - } - } - - $docData.Policies = @($docData.Policies | Where-Object { - $policyTags = $_.tags - if ($null -eq $policyTags -or @($policyTags).Count -eq 0) { return $false } - foreach ($t in @($policyTags)) { - $tagName = if ($t -is [PSObject] -and $t.PSObject.Properties['name']) { $t.name } else { $t.ToString() } - if ($tagName -and $tagName.IndexOf($Tag, [System.StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true } - } - return $false - }) - Write-Host " Filtered to $(@($docData.Policies).Count) of $originalCount policies with tag '$Tag'" -ForegroundColor Gray - - # No match used to render anyway: a 0.1 KB document and exit 0, which reads as "nothing in - # this tenant is tagged that way" when the likelier cause is a tag name that does not exist. - # Naming the real tags is the difference between a dead end and a correctable mistake. - if (@($docData.Policies).Count -eq 0) { - $known = if ($availableTags.Count -gt 0) { $availableTags -join "', '" } else { $null } - $detail = if ($known) { "Tags present in this tenant: '$known'." } else { 'No policy in this tenant carries any tag.' } - Write-Error -Message "No policy matched tag '$Tag', so there is nothing to document. $detail" ` - -ErrorId 'TagMatchedNothing' -Category ObjectNotFound - return - } -} - -# Load Settings Catalog only if there are Settings Catalog policies (policyTypeId 10) +# Load Settings Catalog only if the tenant has Settings Catalog policies (policyTypeId 10) $hasCatalogPolicies = @($docData.Policies | Where-Object { $_.policyTypeId -eq 10 }).Count -gt 0 if ($hasCatalogPolicies) { $catalogParams = @{} @@ -241,7 +195,8 @@ if ($hasCatalogPolicies) { Write-Host ' No Intune/Defender policies found, skipping Settings Catalog load' -ForegroundColor Gray } -# Graph maps are built fresh for this tenant only; nothing carries over between piped tenants or calls. +# Graph maps are built fresh for this tenant only, once for all its baselines; nothing carries over +# between piped tenants or calls. $graphMaps = @{} if ($FetchGraphData) { $tenantLabel = if ($docData.Tenant -and $docData.Tenant.tenantFriendlyName) { " for $($docData.Tenant.tenantFriendlyName)" } else { '' } @@ -249,86 +204,158 @@ if ($FetchGraphData) { $graphMaps = Resolve-InforcerGraphEnrichment -DocData $docData -ConditionalAccess } -Write-Host 'Building documentation model...' -ForegroundColor Cyan -$docModelParams = @{ DocData = $docData } -foreach ($key in 'GroupNameMap', 'FilterMap', 'RoleNameMap', 'LocationNameMap', 'AppNameMap', 'ScopeTagMap') { - if ($graphMaps[$key]) { $docModelParams[$key] = $graphMaps[$key] } -} -$docModel = ConvertTo-InforcerDocModel @docModelParams -if ($null -eq $docModel) { return } +# One tenant read serves every -Baseline: the policy list is the slow call (20-40 s on a large +# tenant), a baseline's membership is a fraction of a second. Each pass starts from the full list. +$allPolicies = @($docData.Policies) +# A blank entry is skipped, never read as "no filter": that would put the whole tenant in a +# document beside the baselines asked for. Only an omitted or all-blank -Baseline means everything. +$named = @($Baseline | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) +$baselineTargets = @(if ($named.Count) { $named } else { $null }) +# 'Tier 1' and 'Tier-1' make the same file name; the second would overwrite the first. +$usedFileStems = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) +foreach ($baselineTarget in $baselineTargets) { + $docData.Policies = $allPolicies + + # Filter to baseline policies if -Baseline specified + $baselineFilterName = $null + if ($baselineTarget) { + Write-Host "Filtering to baseline: $baselineTarget" -ForegroundColor Cyan + $baselineFilterName = Select-InforcerBaselinePolicies -DocData $docData -BaselineId $baselineTarget -WarningVariable selectWarnings + # This used to warn and export every policy in the tenant, under the baseline's name: a + # document that claims to be one baseline and is the whole estate. Compare treats the same + # failure as an error (SourceBaselineFilterFailed); so does Export now. + if ($null -eq $baselineFilterName) { + $why = if ($selectWarnings) { " $(@($selectWarnings)[-1])" } else { '' } + Write-Error -Message "Could not filter to baseline '$baselineTarget', so nothing was exported.$why" ` + -ErrorId 'BaselineFilterFailed' -Category InvalidResult + continue + } + } -# Add filter metadata so renderers can show what's active -if ($baselineFilterName) { $docModel['FilterBaseline'] = $baselineFilterName } -if (-not [string]::IsNullOrWhiteSpace($Tag)) { $docModel['FilterTag'] = $Tag } + # Filter by tag if -Tag specified + if (-not [string]::IsNullOrWhiteSpace($Tag)) { + Write-Host "Filtering to tag: $Tag" -ForegroundColor Cyan + $originalCount = @($docData.Policies).Count + + # Collected before the filter so a no-match can name the tags that do exist. + $availableTags = [System.Collections.Generic.SortedSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($pol in @($docData.Policies)) { + foreach ($t in @($pol.tags)) { + if ($null -eq $t) { continue } + $n = if ($t -is [PSObject] -and $t.PSObject.Properties['name']) { $t.name } else { $t.ToString() } + if (-not [string]::IsNullOrWhiteSpace($n)) { [void]$availableTags.Add($n) } + } + } -$policyCount = 0 -foreach ($product in $docModel.Products.Values) { - foreach ($policies in $product.Categories.Values) { $policyCount += @($policies).Count } -} -Write-Host " Found $policyCount policies across $($docModel.Products.Count) products" -ForegroundColor Gray - -# ── No -OutputPath: hand back the DocModel and touch nothing ─────────────────── -# Writing is opt-in even here, where the verb promises a file. The old default put documents in -# whatever directory you happened to be standing in and opened a browser for them, which is -# wrong in a pipeline and wrong for a caller that only wants the model to read. -if ([string]::IsNullOrWhiteSpace($OutputPath)) { - Write-Host 'Done. Pass -OutputPath to write files.' -ForegroundColor Cyan - return $docModel -} + $docData.Policies = @($docData.Policies | Where-Object { + $policyTags = $_.tags + if ($null -eq $policyTags -or @($policyTags).Count -eq 0) { return $false } + foreach ($t in @($policyTags)) { + $tagName = if ($t -is [PSObject] -and $t.PSObject.Properties['name']) { $t.name } else { $t.ToString() } + if ($tagName -and $tagName.IndexOf($Tag, [System.StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true } + } + return $false + }) + Write-Host " Filtered to $(@($docData.Policies).Count) of $originalCount policies with tag '$Tag'" -ForegroundColor Gray + + # No match used to render anyway: a 0.1 KB document and exit 0, which reads as "nothing in + # this tenant is tagged that way" when the likelier cause is a tag name that does not exist. + # Naming the real tags is the difference between a dead end and a correctable mistake. + if (@($docData.Policies).Count -eq 0) { + $known = if ($availableTags.Count -gt 0) { $availableTags -join "', '" } else { $null } + $detail = if ($known) { "Tags present in this tenant: '$known'." } else { 'No policy in this tenant carries any tag.' } + Write-Error -Message "No policy matched tag '$Tag', so there is nothing to document. $detail" ` + -ErrorId 'TagMatchedNothing' -Category ObjectNotFound + continue + } + } -# Render each requested format and write to disk -$extensionMap = @{ Html = 'html'; Markdown = 'md'; Excel = 'xlsx' } -$formatIndex = 0 -$htmlFile = $null -$safeName = $docModel.TenantName -replace '[^\w\-]', '-' + Write-Host 'Building documentation model...' -ForegroundColor Cyan + $docModelParams = @{ DocData = $docData } + foreach ($key in 'GroupNameMap', 'FilterMap', 'RoleNameMap', 'LocationNameMap', 'AppNameMap', 'ScopeTagMap') { + if ($graphMaps[$key]) { $docModelParams[$key] = $graphMaps[$key] } + } + $docModel = ConvertTo-InforcerDocModel @docModelParams + if ($null -eq $docModel) { continue } -foreach ($fmt in $Format) { - $formatIndex++ - $ext = $extensionMap[$fmt] + # Add filter metadata so renderers can show what's active + if ($baselineFilterName) { $docModel['FilterBaseline'] = $baselineFilterName } + if (-not [string]::IsNullOrWhiteSpace($Tag)) { $docModel['FilterTag'] = $Tag } - if ($Format.Count -eq 1 -and [System.IO.Path]::HasExtension($OutputPath)) { - $filePath = $OutputPath - } else { - $filePath = Join-Path $OutputPath "$safeName-Documentation.$ext" + $policyCount = 0 + foreach ($product in $docModel.Products.Values) { + foreach ($policies in $product.Categories.Values) { $policyCount += @($policies).Count } } - - $parentDir = Split-Path -Parent $filePath - if (-not [string]::IsNullOrEmpty($parentDir) -and -not (Test-Path -LiteralPath $parentDir)) { - [void](New-Item -ItemType Directory -Force -Path $parentDir) + Write-Host " Found $policyCount policies across $($docModel.Products.Count) products" -ForegroundColor Gray + + # ── No -OutputPath: hand back the DocModel and touch nothing ─────────────────── + # Writing is opt-in even here, where the verb promises a file. The old default put documents in + # whatever directory you happened to be standing in and opened a browser for them, which is + # wrong in a pipeline and wrong for a caller that only wants the model to read. + if ([string]::IsNullOrWhiteSpace($OutputPath)) { + Write-Host 'Done. Pass -OutputPath to write files.' -ForegroundColor Cyan + $docModel + continue } - Write-Host "Rendering $fmt ($formatIndex/$($Format.Count))..." -ForegroundColor Cyan + # Render each requested format and write to disk + $extensionMap = @{ Html = 'html'; Markdown = 'md'; Excel = 'xlsx' } + $formatIndex = 0 + $htmlFile = $null + $safeName = $docModel.TenantName -replace '[^\w\-]', '-' + # Several baselines in one call each get their own file. + if ($baselineTargets.Count -gt 1) { $safeName += '-' + ($baselineFilterName -replace '[^\w\-]', '-') } + $stem = $safeName; $n = 2 + while (-not $usedFileStems.Add($safeName)) { $safeName = "$stem-$n"; $n++ } + + foreach ($fmt in $Format) { + $formatIndex++ + $ext = $extensionMap[$fmt] + + if ($Format.Count -eq 1 -and [System.IO.Path]::HasExtension($OutputPath)) { + $filePath = $OutputPath + } else { + $filePath = Join-Path $OutputPath "$safeName-Documentation.$ext" + } - if ($fmt -eq 'Excel') { - # Excel writes directly to disk via ImportExcel - Export-InforcerDocExcel -DocModel $docModel -FilePath $filePath - if (-not (Test-Path -LiteralPath $filePath)) { continue } - } else { - $content = switch ($fmt) { - 'Html' { ConvertTo-InforcerHtml -DocModel $docModel } - 'Markdown' { ConvertTo-InforcerMarkdown -DocModel $docModel } + $parentDir = Split-Path -Parent $filePath + if (-not [string]::IsNullOrEmpty($parentDir) -and -not (Test-Path -LiteralPath $parentDir)) { + [void](New-Item -ItemType Directory -Force -Path $parentDir) } - Set-Content -Path $filePath -Value $content -Encoding UTF8 - if ($fmt -eq 'Html') { $htmlFile = $filePath } - } - $fileInfo = Get-Item -LiteralPath $filePath - $sizeKb = [math]::Round($fileInfo.Length / 1KB, 1) - Write-Host " Exported: $filePath ($sizeKb KB)" -ForegroundColor Green - $fileInfo -} + Write-Host "Rendering $fmt ($formatIndex/$($Format.Count))..." -ForegroundColor Cyan + + if ($fmt -eq 'Excel') { + # Excel writes directly to disk via ImportExcel + Export-InforcerDocExcel -DocModel $docModel -FilePath $filePath + if (-not (Test-Path -LiteralPath $filePath)) { continue } + } else { + $content = switch ($fmt) { + 'Html' { ConvertTo-InforcerHtml -DocModel $docModel } + 'Markdown' { ConvertTo-InforcerMarkdown -DocModel $docModel } + } + Set-Content -Path $filePath -Value $content -Encoding UTF8 + if ($fmt -eq 'Html') { $htmlFile = $filePath } + } -# -Show defaults to on interactively and off in CI (Test-InforcerInteractiveHost), so a human -# who asked for a report sees it while a build agent is never handed a browser to open. -if ($Show -and $htmlFile -and (Test-Path -LiteralPath $htmlFile)) { - $fullHtmlPath = (Resolve-Path -LiteralPath $htmlFile).Path - if ($openedHtml.Add($fullHtmlPath)) { - if ($IsMacOS) { Start-Process 'open' -ArgumentList $fullHtmlPath } - elseif ($IsWindows) { Start-Process $fullHtmlPath } - elseif ($IsLinux) { Start-Process 'xdg-open' -ArgumentList $fullHtmlPath } + $fileInfo = Get-Item -LiteralPath $filePath + $sizeKb = [math]::Round($fileInfo.Length / 1KB, 1) + Write-Host " Exported: $filePath ($sizeKb KB)" -ForegroundColor Green + $fileInfo } -} -Write-Host "Done. $($Format.Count) file(s) exported for tenant '$($docModel.TenantName)'." -ForegroundColor Cyan + # -Show defaults to on interactively and off in CI (Test-InforcerInteractiveHost), so a human + # who asked for a report sees it while a build agent is never handed a browser to open. + if ($Show -and $htmlFile -and (Test-Path -LiteralPath $htmlFile)) { + $fullHtmlPath = (Resolve-Path -LiteralPath $htmlFile).Path + if ($openedHtml.Add($fullHtmlPath)) { + if ($IsMacOS) { Start-Process 'open' -ArgumentList $fullHtmlPath } + elseif ($IsWindows) { Start-Process $fullHtmlPath } + elseif ($IsLinux) { Start-Process 'xdg-open' -ArgumentList $fullHtmlPath } + } + } + + Write-Host "Done. $($Format.Count) file(s) exported for tenant '$($docModel.TenantName)'." -ForegroundColor Cyan +} } }