feat(compare): add offline tenant comparison and launcher menu entry

Scripts/Compare-Tenants.py compares two export folders across all
common categories (settings catalog, device config, compliance,
autopilot, ESP, roles, apps, ...) by flattening objects and ignoring
ids, timestamps, scope tags, OData metadata and names. Policies are
matched by name after stripping per-tenant prefixes (regex), then by
fuzzy name similarity, then by content similarity. Optional assignment
comparison. Writes Markdown and CSV reports.

Start-IntuneToolkit.ps1: new menu item 22 prompts for both exports and
runs the script.
This commit is contained in:
2026-11-24 11:56:43 +01:00
parent 7e1349f1c9
commit 5d8e387288
4 changed files with 379 additions and 0 deletions
+1
View File
@@ -125,6 +125,7 @@ The launcher caches tenant display names in `Settings.json` so the TUI can show
| `Start-IntuneToolkit.ps1` | Unified reverse-numbered `fzf`/numbered menu; remembers tenants; launches all other tools. |
| `Scripts/Start-HeadlessIntune.ps1` | Single-action wrapper (`Export`, `Import`, `DeployCISBaseline`, `GenerateReports`) with optional interactive TUI. |
| `Scripts/Export-SettingsReport.py` | Generate a flat CSV of policy settings/values. Includes a `Platform` column and resolves Settings Catalog names from `configurationSettings.json` (auto-exported with Settings Catalog). |
| `Scripts/Compare-Tenants.py` | Offline comparison of two export folders (all categories incl. Autopilot, roles). Handles different name prefixes (`--strip-a/--strip-b`), fuzzy/content matching, optional `--include-assignments`. Writes Markdown + CSV. |
| `Scripts/Export-EntraRoleMembership.ps1` | Export active + PIM-eligible Microsoft Entra directory role memberships (group assignments expanded) to CSV. |
| `Scripts/Export-Policies.ps1` | Export policies to JSON. |
| `Scripts/Import-Policies.ps1` | Import policies from JSON. |
+13
View File
@@ -1,5 +1,18 @@
# macOS Intune Toolkit Changelog
## 2026-11-24 — v4.5.0 — Offline tenant comparison
### Added
- **`Scripts/Compare-Tenants.py`**
- Compares two export folders (no Graph calls) across every common category — Settings Catalog, device configuration, compliance, Autopilot, ESP, roles, apps, etc. — by flattening each object and ignoring ids, timestamps, scope tags, OData metadata and names.
- Matches policies by name after stripping per-tenant prefixes (`--strip-a`, `--strip-b`, regex), then by fuzzy name similarity, then by near-identical content (`--no-fuzzy` to disable). GUIDs are resolved to names via the exported Groups/AssignmentFilters; unresolved GUIDs are masked.
- `--include-assignments` also compares assignments (group names, filters, intent, role assignment members/scopes).
- Writes `tenant-comparison.md` (per-category summary, only-in-A/B, setting-level diffs, fuzzy matches to verify) and `tenant-comparison.csv`.
### Changed
- **`Start-IntuneToolkit.ps1`**
- New menu item **22. Compare two tenant exports (offline)** in the Reporting group. Prompts for both export folders, labels, prefix regexes, output folder, assignments and fuzzy matching, then runs `Scripts/Compare-Tenants.py`. No tenant connection needed.
## 2026-11-24 — v4.4.3 — Create new folder in folder browser
### Added
+322
View File
@@ -0,0 +1,322 @@
#!/usr/bin/env python3
"""Compare two IntuneManagement export folders (offline, no Graph calls).
Works for every exported category (Settings Catalog, device configuration,
compliance, Autopilot, ESP, roles, ...) by flattening each JSON object into
path -> value pairs and ignoring what is expected to differ between tenants:
ids, timestamps, scope tags, OData metadata, names and (by default) assignments.
Policies are matched per category:
1. exact - same name after stripping the tenant prefix (--strip-a/--strip-b)
2. fuzzy - similar names (--fuzzy-threshold)
3. content - different names but near-identical settings (--content-threshold)
GUID values are resolved to names through the exported Groups / AssignmentFilters
folders; unresolved GUIDs are masked so they do not show up as differences.
Outputs (in --output-dir): tenant-comparison.md and tenant-comparison.csv
"""
from __future__ import annotations
import argparse
import csv
import difflib
import hashlib
import json
import re
from pathlib import Path
from typing import Any
GUID_RE = re.compile(r"^[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$")
SKIP_CATEGORIES = {"Groups", "ADMXFiles"}
LOOKUP_CATEGORIES = ("Groups", "AssignmentFilters")
NAME_KEYS = ("displayName", "name")
ASSIGNMENT_KEYS = {"assignments", "roleAssignments", "groupAssignments"}
VOLATILE = {
"id", "createdDateTime", "lastModifiedDateTime", "modifiedDateTime", "version",
"roleScopeTagIds", "supportsScopeTags", "settingCount", "creationSource",
"isAssigned", "deviceStatuses", "userStatuses", "deviceStatusOverview",
"userStatusOverview", "deviceSettingStateSummaries", "organizationId",
"createdByAppId", "securityIdentifier", "mailNickname", "renewedDateTime",
"largeIcon", "uploadState", "publishingState", "dependentAppCount",
"supersedingAppCount", "supersededAppCount", "committedContentVersion",
"size", "description", "isBuiltInRoleDefinition",
}
# Order matters: first match identifies a list element across tenants
IDENT_PATHS = (
("settingInstance", "settingDefinitionId"), ("settingDefinitionId",),
("definitionId",), ("definition", "displayName"), ("omaUri",),
("displayName",), ("name",), ("@odata.type",),
)
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--root-a", required=True, type=Path, help="Export folder of tenant A (contains category folders)")
p.add_argument("--root-b", required=True, type=Path, help="Export folder of tenant B")
p.add_argument("--label-a", default="A")
p.add_argument("--label-b", default="B")
p.add_argument("--strip-a", default="", help="Regex removed from tenant A names, e.g. '^SSD\\s*-\\s*'")
p.add_argument("--strip-b", default="", help="Regex removed from tenant B names, e.g. '^SSE\\s*-\\s*'")
p.add_argument("--categories", nargs="*", help="Only compare these category folders (default: all common)")
p.add_argument("--include-assignments", action="store_true", help="Also compare assignments (group names, filters, intent)")
p.add_argument("--fuzzy-threshold", type=float, default=0.85, help="Name similarity 0-1 for fuzzy matching")
p.add_argument("--content-threshold", type=float, default=0.9, help="Settings similarity 0-1 for content matching")
p.add_argument("--no-fuzzy", action="store_true", help="Exact name matching only")
p.add_argument("--max-diffs", type=int, default=40, help="Max setting differences per policy in the Markdown report")
p.add_argument("--output-dir", type=Path, default=Path("."))
return p.parse_args()
def norm_name(raw: str, strip: str) -> str:
if strip:
raw = re.sub(strip, "", raw, count=1, flags=re.IGNORECASE)
return re.sub(r"[^a-z0-9]+", " ", raw.lower()).strip()
def clean_name(raw: str, strip: str) -> str:
return re.sub(strip, "", raw, count=1, flags=re.IGNORECASE).strip() if strip else raw
def load_json(path: Path) -> Any:
try:
return json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
return None
class Tenant:
def __init__(self, root: Path, strip: str, label: str):
self.root, self.strip, self.label = root, strip, label
self.names: dict[str, str] = {}
for cat in LOOKUP_CATEGORIES:
for f in (root / cat).rglob("*.json") if (root / cat).is_dir() else []:
d = load_json(f)
if isinstance(d, dict) and d.get("id") and d.get("displayName"):
self.names[d["id"].lower()] = d["displayName"]
mig = load_json(root / "MigrationTable.json")
for o in (mig or {}).get("Objects", []) if isinstance(mig, dict) else []:
if o.get("Id") and o.get("DisplayName"):
self.names.setdefault(o["Id"].lower(), o["DisplayName"])
def categories(self) -> set[str]:
return {d.name for d in self.root.iterdir() if d.is_dir() and d.name not in SKIP_CATEGORIES}
def scalar(self, v: Any) -> str:
if isinstance(v, str):
if GUID_RE.match(v):
name = self.names.get(v.lower())
return clean_name(name, self.strip) if name else "<guid>"
if len(v) > 200:
return f"<sha1:{hashlib.sha1(v.encode()).hexdigest()[:10]} len={len(v)}>"
return v
return json.dumps(v)
def ident(self, item: dict) -> str:
for path in IDENT_PATHS:
cur: Any = item
for k in path:
cur = cur.get(k) if isinstance(cur, dict) else None
if cur not in (None, ""):
return self.scalar(cur)
return ""
def flatten(self, obj: Any, path: str, out: dict, top: bool = False) -> None:
if isinstance(obj, dict):
for k, v in obj.items():
if "@odata" in k or k.startswith("#") or k in VOLATILE or k in ASSIGNMENT_KEYS or k.endswith("DateTime"):
continue
if top and k in NAME_KEYS:
continue
self.flatten(v, f"{path}.{k}" if path else k, out)
elif isinstance(obj, list):
if obj and all(not isinstance(x, (dict, list)) for x in obj):
out[path] = frozenset(self.scalar(x) for x in obj)
return
seen: dict[str, int] = {}
for i, item in enumerate(obj):
key = self.ident(item) if isinstance(item, dict) else ""
key = key or str(i)
seen[key] = seen.get(key, 0) + 1
if seen[key] > 1:
key = f"{key}#{seen[key]}"
self.flatten(item, f"{path}[{key}]", out)
elif obj not in (None, ""):
out[path] = self.scalar(obj)
def assignments(self, obj: dict) -> frozenset:
res = set()
for key in ASSIGNMENT_KEYS:
for a in obj.get(key) or []:
if not isinstance(a, dict):
continue
t = a.get("target")
if t:
kind = str(t.get("@odata.type", "")).split(".")[-1].replace("AssignmentTarget", "")
s = f"{kind}: {self.scalar(t['groupId']) if t.get('groupId') else '-'}"
if t.get("deviceAndAppManagementAssignmentFilterId"):
ftype = t.get("deviceAndAppManagementAssignmentFilterType", "")
s += f" [filter {ftype}: {self.scalar(t['deviceAndAppManagementAssignmentFilterId'])}]"
if a.get("intent"):
s += f" intent={a['intent']}"
else: # role assignment
members = sorted(self.scalar(m) for m in a.get("members", []))
scopes = sorted(self.scalar(m) for m in a.get("resourceScopes", []))
s = f"role assignment '{clean_name(a.get('displayName', ''), self.strip)}' members={members} scopes={scopes}"
res.add(s)
return frozenset(res)
def load_category(self, cat: str, with_assignments: bool) -> dict[str, dict]:
"""Return {unique key: entry} for one category."""
files = sorted((self.root / cat).rglob("*.json"))
companions = {f.name[: -len("_Settings.json")]: f for f in files if f.name.endswith("_Settings.json")}
entries: dict[str, dict] = {}
for f in files:
if f.name.endswith("_Settings.json"):
continue
d = load_json(f)
if not isinstance(d, dict):
continue
comp = companions.get(f.stem)
if comp:
d["_settings"] = load_json(comp)
raw = next((d[k] for k in NAME_KEYS if d.get(k)), f.stem)
key = norm_name(raw, self.strip) or f.stem.lower()
n = 1
while key in entries:
n += 1
key = f"{norm_name(raw, self.strip)} #{n}"
flat: dict[str, Any] = {}
self.flatten(d, "", flat, top=True)
if with_assignments:
flat["(assignments)"] = self.assignments(d)
entries[key] = {"name": clean_name(raw, self.strip), "raw": raw, "flat": flat}
return entries
def show(v: Any) -> str:
s = "" if v is None else (", ".join(sorted(v)) if isinstance(v, frozenset) else str(v))
return s if len(s) <= 300 else s[:297] + "..."
def diff_flat(a: dict, b: dict) -> list[tuple[str, str, str]]:
rows = []
for k in sorted(set(a) | set(b)):
va, vb = a.get(k), b.get(k)
if va == vb:
continue
if isinstance(va, frozenset) and isinstance(vb, frozenset):
rows.append((k, "only here: " + show(va - vb), "only here: " + show(vb - va)))
else:
rows.append((k, show(va), show(vb)))
return rows
def jaccard(a: dict, b: dict) -> float:
sa = {(k, str(v)) for k, v in a.items() if k != "(assignments)"}
sb = {(k, str(v)) for k, v in b.items() if k != "(assignments)"}
if min(len(sa), len(sb)) < 3:
return 0.0
return len(sa & sb) / len(sa | sb)
def match_category(ea: dict, eb: dict, args: argparse.Namespace) -> list[tuple]:
"""Return [(keyA|None, keyB|None, how, score)]."""
pairs = [(k, k, "exact", 1.0) for k in ea if k in eb]
ra = [k for k in ea if k not in eb]
rb = [k for k in eb if k not in ea]
if not args.no_fuzzy:
for how, scorer, thr in (
("fuzzy", lambda x, y: difflib.SequenceMatcher(None, x, y).ratio(), args.fuzzy_threshold),
("content", lambda x, y: jaccard(ea[x]["flat"], eb[y]["flat"]), args.content_threshold),
):
cands = sorted(((scorer(x, y), x, y) for x in ra for y in rb), reverse=True)
used_a, used_b = set(), set()
for score, x, y in cands:
if score < thr:
break
if x in used_a or y in used_b:
continue
used_a.add(x); used_b.add(y)
pairs.append((x, y, how, round(score, 2)))
ra = [k for k in ra if k not in used_a]
rb = [k for k in rb if k not in used_b]
pairs += [(k, None, "", 0.0) for k in ra] + [(None, k, "", 0.0) for k in rb]
return pairs
def main() -> None:
args = parse_args()
for r in (args.root_a, args.root_b):
if not r.is_dir():
raise SystemExit(f"Not a folder: {r}")
ta = Tenant(args.root_a, args.strip_a, args.label_a)
tb = Tenant(args.root_b, args.strip_b, args.label_b)
cats = sorted(ta.categories() & tb.categories())
if args.categories:
cats = [c for c in cats if c in set(args.categories)]
if not cats:
raise SystemExit("No common category folders found. Point --root-a/--root-b at folders containing e.g. SettingsCatalog/")
la, lb = args.label_a, args.label_b
csv_rows, summary, sections = [], [], []
for cat in cats:
ea = ta.load_category(cat, args.include_assignments)
eb = tb.load_category(cat, args.include_assignments)
counts = {"identical": 0, "differs": 0, f"only {la}": 0, f"only {lb}": 0, "fuzzy/content": 0}
lines = []
for ka, kb, how, score in sorted(match_category(ea, eb, args), key=lambda p: (p[0] or p[1])):
pa, pb = ea.get(ka), eb.get(kb)
if not pb:
counts[f"only {la}"] += 1
csv_rows.append([cat, pa["raw"], "", "", "", f"only {la}", "", "", ""])
lines.append(f"- **only {la}**: {pa['name']}")
continue
if not pa:
counts[f"only {lb}"] += 1
csv_rows.append([cat, "", pb["raw"], "", "", f"only {lb}", "", "", ""])
lines.append(f"- **only {lb}**: {pb['name']}")
continue
diffs = diff_flat(pa["flat"], pb["flat"])
status = "differs" if diffs else "identical"
counts[status] += 1
if how in ("fuzzy", "content"):
counts["fuzzy/content"] += 1
tag = f" _({how} match {score})_" if how != "exact" else ""
if diffs or how != "exact":
head = f"- **{status}**: {pa['name']}" + (f" ↔ {pb['name']}" if pa["name"] != pb["name"] else "") + tag
lines.append(head)
for k, va, vb in diffs[: args.max_diffs]:
lines.append(f" - `{k}`: {la}=`{va}` / {lb}=`{vb}`")
if len(diffs) > args.max_diffs:
lines.append(f" - … {len(diffs) - args.max_diffs} more (see CSV)")
for k, va, vb in diffs or [("", "", "")]:
csv_rows.append([cat, pa["raw"], pb["raw"], how, score, status, k, va, vb])
summary.append((cat, counts))
if lines:
sections.append(f"## {cat}\n\n" + "\n".join(lines))
args.output_dir.mkdir(parents=True, exist_ok=True)
with open(args.output_dir / "tenant-comparison.csv", "w", newline="", encoding="utf-8") as fh:
w = csv.writer(fh)
w.writerow(["Category", f"Policy {la}", f"Policy {lb}", "Match", "Score", "Status", "Setting", f"Value {la}", f"Value {lb}"])
w.writerows(csv_rows)
cols = ["identical", "differs", f"only {la}", f"only {lb}", "fuzzy/content"]
md = [f"# Tenant comparison: {la} vs {lb}", "",
f"- {la}: `{args.root_a}`", f"- {lb}: `{args.root_b}`",
f"- Assignments compared: {'yes' if args.include_assignments else 'no'}", "",
"| Category | " + " | ".join(cols) + " |", "|---|" + "---|" * len(cols)]
for cat, c in summary:
md.append(f"| {cat} | " + " | ".join(str(c[x]) for x in cols) + " |")
md += ["", "`fuzzy/content` counts matches that were not an exact name match; check them below.", ""]
(args.output_dir / "tenant-comparison.md").write_text("\n".join(md) + "\n" + "\n\n".join(sections) + "\n", encoding="utf-8")
tot = {x: sum(c[x] for _, c in summary) for x in cols}
print(f"Compared {len(cats)} categories: " + ", ".join(f"{v} {k}" for k, v in tot.items()))
print(f"Wrote {args.output_dir / 'tenant-comparison.md'} and tenant-comparison.csv")
if __name__ == "__main__":
main()
+43
View File
@@ -328,6 +328,7 @@ $menuItems = @(
# Reporting
"16. Generate reports"
"20. Export Entra role membership"
"22. Compare two tenant exports (offline)"
# Tenant & auth admin
"12. Initialize auth (one-time setup)"
"13. Refresh tenant names"
@@ -490,6 +491,48 @@ while($true)
continue
}
if($choiceNumber -eq 22)
{
# Offline comparison of two export folders; no tenant connection needed
$python = Get-Command python3 -ErrorAction SilentlyContinue
if(-not $python) { $python = Get-Command python -ErrorAction SilentlyContinue }
if(-not $python) { Write-Host "Python 3 is required." -ForegroundColor Red; continue }
$sides = @()
foreach($side in "A","B")
{
$root = Read-Host "Export folder of tenant $side"
if([string]::IsNullOrWhiteSpace($root)) { Write-Host "Required." -ForegroundColor Red; $sides = $null; break }
$root = [IO.Path]::GetFullPath(($root.Trim().Trim('"',"'") -replace '^~', $HOME))
if(-not (Test-Path -LiteralPath $root -PathType Container)) { Write-Host "Folder not found: $root" -ForegroundColor Red; $sides = $null; break }
$defaultLabel = Split-Path $root -Leaf
$label = Read-Host "Label for tenant $side (default: $defaultLabel)"
if([string]::IsNullOrWhiteSpace($label)) { $label = $defaultLabel }
$strip = Read-Host "Name prefix regex to strip for tenant $side, e.g. ^SSD\s*-\s* (Enter for none)"
$sides += ,@($root, $label, $strip)
}
if(-not $sides) { continue }
$outputDir = Read-Host "Output directory for the comparison report"
if([string]::IsNullOrWhiteSpace($outputDir)) { Write-Host "Required." -ForegroundColor Red; continue }
$outputDir = [IO.Path]::GetFullPath(($outputDir.Trim().Trim('"',"'") -replace '^~', $HOME))
$pyArgs = @(
(Join-Path $projectRoot "Scripts/Compare-Tenants.py"),
"--root-a", $sides[0][0], "--label-a", $sides[0][1], "--strip-a", $sides[0][2],
"--root-b", $sides[1][0], "--label-b", $sides[1][1], "--strip-b", $sides[1][2],
"--output-dir", $outputDir
)
if((Read-Host "Compare assignments too? [y/N]") -like 'y*') { $pyArgs += "--include-assignments" }
if((Read-Host "Fuzzy name/content matching? [Y/n]") -like 'n*') { $pyArgs += "--no-fuzzy" }
Write-Host "`nComparing ..." -ForegroundColor Cyan
& $python.Source @pyArgs
Write-Host "`nPress any key to return to the menu..." -ForegroundColor DarkGray
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
continue
}
if($choiceNumber -eq 17)
{
$defaultBaseline = Join-Path $projectRoot "Baselines/CISM365-v7-Generated.yaml"