24 Commits
Author SHA1 Message Date
tomas.kracmar ad3b53026c chore(release): 4.6.2 2026-11-24 13:12:55 +01:00
tomas.kracmar cd0d516951 docs: document tenant comparison, bulk scope tags, full export, wrapper and lazy migration
README: intune wrapper, menu overview, batch/sorted export, tenant comparison
section, bulk scope tags, lazy group/filter creation. AGENTS.md: structure,
menu $menuDefs convention, folder picker, SettingOverrides, FullExportRoot.
2026-11-24 13:12:55 +01:00
tomas.kracmar 57917e9183 feat(toolkit): use the folder picker for launcher path prompts
Move the fzf folder browser to Scripts/Private/Select-FolderPath.ps1 so
the launcher can use it too. Full tenant export root, tenant A and B
export folders and the report folder of the offline compare, the
earlier-export choice of the drift check and the report paths now open
the picker. It starts at the nearest existing folder, falls back to a
plain prompt without fzf and understands ~ and quotes.
2026-11-24 13:12:12 +01:00
tomas.kracmar f2f200f904 feat(toolkit): number menu entries automatically
The menu is now a list of entries in display order; the numbers 1-24 are
assigned at startup instead of being hand-picked per item, so adding or
moving an entry never needs renumbering. Dispatch keeps stable internal
ids. README reference to 'delete tenant auth and app registration' is now
item 24.
2026-11-24 13:12:11 +01:00
tomas.kracmar e964813ffe docs: changelog for v4.6.0 (upstream ports, batching, lazy migration, drift, scope tags) 2026-11-24 12:27:17 +01:00
tomas.kracmar d55908e975 feat(bulk): add bulk scope tag tool
Scripts/Bulk-ScopeTags.ps1 (menu item 24) adds, replaces or removes scope
tags across object types, optionally filtered by name, or cleans up tag
ids that no longer exist. Shows the plan per type, supports -WhatIf and
-Force, applies changes with batched PATCH requests and skips objects
whose tag list would not change. Design follows upstream 4.0
Set-GraphBulkScopeTags.
2026-11-24 12:27:17 +01:00
tomas.kracmar df3cda9843 feat(compare): offer a drift check after the full tenant export
After menu item 23 finishes it offers to compare with the newest earlier
export of the same tenant (assignments included) and writes the report to
<root>/_drift/<old>-to-<new>/. Compare-Tenants.py now also accepts a
folder that holds a single export folder (e.g. a dated folder containing
Exports/).
2026-11-24 12:27:16 +01:00
tomas.kracmar 0302286505 feat(import): create only the groups and filters an import references
With Import assignments, migration-table groups are no longer all looked
up or created up front. They are resolved on demand in
Update-JsonForEnvironment, so only groups referenced by imported objects
are created in the target tenant. Assignment filters that exist in the
export but not in the target are created on demand too (needs Replace
dependency ids). Synced source groups log a warning and are created as
cloud groups. New groups get a random 10-character mailNickname like the
Entra portal; group lookup escapes apostrophes in names.
2026-11-24 12:27:16 +01:00
tomas.kracmar 523311700d feat(upstream): port Win32 scripts, quality update policies, sorted JSON
Ported from Micke-K/IntuneManagement 3.10.1.x-3.11.0 (MIT):
- Win32 app install/uninstall scripts are exported (#ScriptInfo plus the
  script files next to the JSON) and recreated on import and copy.
- New object type Quality Updates (Policies)
  (windowsQualityUpdatePolicies); the old type is titled
  "Quality Updates (Profiles)".
- SortJsonProperties setting writes exported JSON with sorted properties
  for stable diffs; always on for headless export.
- EndpointManager.psm1 three-way merged with upstream (page-size flags,
  app fixes). UI-only changes were not taken.
2026-11-24 12:27:16 +01:00
tomas.kracmar 77440ffe36 feat(export): use the Graph batch API by default for headless export
Headless export now fetches objects 20 per $batch call (was one call per
object because UseBatchAPI defaulted to off). -NoBatchApi on
Export-Policies.ps1 / Start-HeadlessIntune.ps1 falls back to single calls.

Adds per-run setting overrides ($global:SettingOverrides, consulted by
Get-SettingValue, set by Invoke-IntuneHeadlessBatch and never persisted).
Verify on a tenant by exporting with and without -NoBatchApi and comparing
the two folders with Compare-Tenants.py.
2026-11-24 12:27:16 +01:00
tomas.kracmar b8e333f92d feat: add intune shell wrapper
./intune starts the launcher without typing pwsh. ./intune <Script> [args]
runs Scripts/<Script>.ps1 or .py. Resolves symlinks so it can be linked
onto PATH; reports a missing pwsh/python3 and lists scripts for an unknown
name.
2026-11-24 12:27:15 +01:00
tomas.kracmar 1733c22c86 feat(toolkit): add full tenant export menu entry
Menu item 23 exports every default object type with assignments for the
current tenant into <root>/<TenantName>-yymmdd (adds -HHmm if the folder
exists). The export root is asked for and remembered in Settings.json
(FullExportRoot, default ~/Local/IntuneExports).
2026-11-24 12:27:15 +01:00
tomas.kracmar 5d8e387288 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.
2026-11-24 11:56:43 +01:00
tomas.kracmar 7e1349f1c9 feat(tui): add create-new-folder option to folder browser
Select-FolderPath gets a [Create new folder] entry. It prompts for a
name, validates it, creates the folder inside the current one and
navigates into it.
2026-11-24 11:40:11 +01:00
tomas.kracmar 37ac448d94 feat(roles): export built-in Intune roles; fix ASCII header failure
- Drop the ExpiresOn request header. Under an en-US culture its date
  contains U+202F before AM/PM, so every Graph call failed with
  "Request headers must contain only ASCII characters". Nothing reads it.
- Export all role definitions with their assignments, including built-in
  roles (was custom only via isBuiltIn eq false).
- On import, skip creating built-in roles. When Import assignments is on,
  recreate their assignments against the exported role id (built-in ids
  are identical across tenants). Custom-role behaviour is unchanged.
2026-11-24 11:34:52 +01:00
tomas.kracmarandClaude Sonnet 5 60a655e6d4 refactor(tui): reorder main menu into logical groups
Menu had grown by prepending each new feature to the top, so items
had no relation to their neighbors. Grouped into Export/Import, Bulk
operations, Baselines & compliance, Reporting, Tenant & auth admin,
with Exit last. Item numbers (used for dispatch) unchanged, only
display order moved.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 18:51:18 +02:00
tomas.kracmarandClaude Sonnet 5 81c5e96fc7 feat(tui): add fzf-based folder browser for export/import path prompts
Read-Host has no tab-completion (that's a top-level PSReadLine feature,
not available to script prompts), so reuse the fzf dependency already
required for menus to browse folders interactively instead: navigate
into subfolders, go up with .., confirm current folder, or type a path
manually. Falls back to plain Read-Host when fzf isn't installed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 11:53:05 +02:00
tomas.kracmarandClaude Sonnet 5 30170a1909 fix(tui): stop re-asking action when launcher already picked Export/Import
Same missing-passthrough bug as the earlier tenant re-prompt fix, this time
for -Action: Start-IntuneManagementTui.ps1 always showed the
Export/Import/DeployCISBaseline/GenerateReports picker even when the
launcher's menu items 1/2 had already decided it. Launcher now passes
-Action through, TUI skips the prompt when supplied.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 11:37:35 +02:00
tomas.kracmarandClaude Sonnet 5 ae71f8458d feat(toolkit): add bulk delete tool, fix TUI exit hang and tenant re-prompt
- New Scripts/Bulk-DeletePolicies.ps1: type-DELETE confirmation, -WhatIf dry-run
- Fix infinite loop in Start-IntuneToolkit.ps1 when fzf missing (numbered-menu
  Exit returned "EXIT" but check only matched fzf's "[Exit]" string)
- Start-IntuneManagementTui.ps1 no longer re-prompts for TenantId when the
  launcher already resolved one; also fixes misleading "regex" wording on
  the Name filter prompt (it's a literal substring match)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 11:31:22 +02:00
tomas.kracmarandClaude Sonnet 4.6 2f0d937ca1 fix(ca-exporter): resolve AuthenticationFlows TransferMethods and surface in Excel
Raw object dump replaced with TransferMethods extraction (falls back to
AdditionalProperties for older module versions). Field added to the
Conditions section of Excel detail sheets.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-27 09:53:42 +02:00
tomas.kracmarandClaude Sonnet 4.6 b10258c5b4 fix(ca-exporter): pre-fetch auth context class references to fix ID resolution
Replaced per-policy Graph API calls with a single pre-fetch of all
authentication context class references into a hashtable, consistent
with every other lookup in the script. Also fixes silent ID drops when
DisplayName was missing — GetOrDefault now falls back to the raw ID.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-27 09:49:48 +02:00
tomas.kracmar 6bf7345eb7 release: v4.2.0 — Entra directory role membership export
- Add Scripts/Export-EntraRoleMembership.ps1 to export active + PIM-eligible
  Entra directory role memberships (with group expansion) to CSV.
- Wire the new script into Start-IntuneToolkit.ps1 as menu item 20.
- Document the new script in README.md and AGENTS.md.
- Bump VERSION to 4.2.0 and add CHANGELOG entry.
- Harden .gitignore against local operational artifacts (accounts/ folder,
  deploy.sh, restart_gateways.sh).
2026-07-07 14:57:02 +02:00
tomas.kracmar 90209a7ec4 feat(reporting): expand settings report and add CA documentation
- Export-SettingsReport.py: add coverage for Compliance V2, Endpoint
  Security, Device Management Intents, ADMX, scripts (base64 decoded),
  App Protection/Configuration, updates, enrollment, Autopilot, W365,
  filters, and more; add OMA-URI and customSettings expansion
- Start-IntuneToolkit.ps1: add menu item 19 for Conditional Access
  documentation
- Add Invoke-ConditionalAccessDocumentation.ps1 for CA policy docs
  (CSV/Excel)
- .gitignore: exclude CA documentation CSV/XLSX outputs
- CHANGELOG: document the new reporting capabilities
2026-06-29 15:12:37 +02:00
tomas.kracmar 122aa2d4e3 fix(reporting): add Platform column and clean up Windows artifacts
- Export-SettingsReport.py: add Platform column for Settings Catalog
  (platforms field) and legacy policies (platform/platformType or
  @odata.type inference)
- MSGraph.psm1: store GraphMetaData.xml in cross-platform data folder
  (Get-CloudApiDataFolder) instead of literal %LOCALAPPDATA% path
- MSALAuthentication.psm1: skip TokenCacheHelperEx on non-Windows with
  an info log instead of failing on missing ProtectedData.dll
- .gitignore: remove literal %LOCALAPPDATA% patterns
- AGENTS.md, CHANGELOG: document reporting and cross-platform fixes
2026-06-22 11:56:55 +02:00
22 changed files with 3886 additions and 223 deletions
+8 -3
View File
@@ -20,11 +20,11 @@ IntuneManagement.log
Exporting */ Exporting */
*.backup/ *.backup/
*.backup *.backup
Scripts/ConditionalAccessDocumentation.csv
Scripts/ConditionalAccessDocumentation.xlsx
# Graph metadata cache # Graph metadata cache (now stored in the platform-specific data folder)
GraphMetaData.xml GraphMetaData.xml
%LOCALAPPDATA%/
*%LOCALAPPDATA%*
CloudAPIPowerShellManagement/ CloudAPIPowerShellManagement/
# Local application settings (contains secrets on non-macOS platforms) # Local application settings (contains secrets on non-macOS platforms)
@@ -36,3 +36,8 @@ __pycache__/
*.pyo *.pyo
.venv-pdf/ .venv-pdf/
.venv/ .venv/
# Local operational artifacts that are not part of the toolkit
accounts/
deploy.sh
restart_gateways.sh
+17 -4
View File
@@ -6,7 +6,7 @@
This repository is **macOS Intune Management** (also referred to as the IntuneManagement toolkit). It is a cross-platform, headless, PowerShell-first CLI for exporting, importing, migrating, and managing Microsoft Intune policies across tenants. This repository is **macOS Intune Management** (also referred to as the IntuneManagement toolkit). It is a cross-platform, headless, PowerShell-first CLI for exporting, importing, migrating, and managing Microsoft Intune policies across tenants.
- **Current version:** `4.1.0` (see `VERSION`). - **Current version:** `4.6.2` (see `VERSION`).
- **Primary workflow:** export policies from a source tenant as JSON, optionally capture assignments, then import them into a target tenant with app-only, browser, or device-code authentication. - **Primary workflow:** export policies from a source tenant as JSON, optionally capture assignments, then import them into a target tenant with app-only, browser, or device-code authentication.
- **Additional capabilities:** declarative baseline deployment from YAML, bulk assignment management, backup/restore of assignments, bulk device operations, policy rename, CSV/Markdown reporting from local backups, and a CIS M365 rapid baseline for tenant-level workloads. - **Additional capabilities:** declarative baseline deployment from YAML, bulk assignment management, backup/restore of assignments, bulk device operations, policy rename, CSV/Markdown reporting from local backups, and a CIS M365 rapid baseline for tenant-level workloads.
- **Important historical note:** the old WPF UI surface has been removed. The repo is intentionally CLI-first and headless. - **Important historical note:** the old WPF UI surface has been removed. The repo is intentionally CLI-first and headless.
@@ -37,6 +37,7 @@ There is no compiled application, no `pyproject.toml`/`package.json`/`Cargo.toml
```text ```text
. .
├── Start-IntuneToolkit.ps1 # Unified terminal UI launcher (recommended entry point) ├── Start-IntuneToolkit.ps1 # Unified terminal UI launcher (recommended entry point)
├── intune # Bash wrapper: launcher, or `intune <Script> [args]` without typing pwsh
├── Core.psm1 # Headless runtime helpers, settings, logging, module loader ├── Core.psm1 # Headless runtime helpers, settings, logging, module loader
├── Runtime/ ├── Runtime/
│ ├── IntuneManagement.Runtime.psd1 # Module manifest │ ├── IntuneManagement.Runtime.psd1 # Module manifest
@@ -55,7 +56,8 @@ There is no compiled application, no `pyproject.toml`/`package.json`/`Cargo.toml
│ ├── Initialize-IntuneAuth.ps1 # One-time Entra app + secret setup │ ├── Initialize-IntuneAuth.ps1 # One-time Entra app + secret setup
│ ├── Deploy-IntuneBaseline.ps1 # YAML-driven baseline deployer │ ├── Deploy-IntuneBaseline.ps1 # YAML-driven baseline deployer
│ ├── ConvertTo-IntuneBaseline.ps1 # Export folder → baseline skeleton │ ├── ConvertTo-IntuneBaseline.ps1 # Export folder → baseline skeleton
│ ├── *_Bulk*.ps1 # Assignments, rename, device operations │ ├── *_Bulk*.ps1 # Assignments, rename, delete, scope tags, device operations
│ ├── Compare-Tenants.py # Offline comparison of two export folders (tenants A/B or drift)
│ ├── *.py # Reporting and PDF conversion utilities │ ├── *.py # Reporting and PDF conversion utilities
│ └── Private/ │ └── Private/
│ └── Start-IntuneManagementTui.ps1 │ └── Start-IntuneManagementTui.ps1
@@ -99,6 +101,8 @@ The toolkit stores persistent configuration in a platform-specific JSON settings
Per-tenant settings are stored under a key matching the tenant GUID. On macOS, the client secret is stored in the macOS Keychain (service `IntuneMgmt-<AppId>`, account `IntuneManagement`) instead of inside the JSON file. On non-macOS platforms the secret is written to the JSON file — treat that file as sensitive. Per-tenant settings are stored under a key matching the tenant GUID. On macOS, the client secret is stored in the macOS Keychain (service `IntuneMgmt-<AppId>`, account `IntuneManagement`) instead of inside the JSON file. On non-macOS platforms the secret is written to the JSON file — treat that file as sensitive.
The launcher also stores `FullExportRoot` (last export root used by the full tenant export) in this file.
Operational logs are written to `IntuneManagement.log` in the same data folder by default. Operational logs are written to `IntuneManagement.log` in the same data folder by default.
## Authentication ## Authentication
@@ -122,15 +126,19 @@ The launcher caches tenant display names in `Settings.json` so the TUI can show
| Script | Purpose | | Script | Purpose |
|---|---| |---|---|
| `Start-IntuneToolkit.ps1` | Unified reverse-numbered `fzf`/numbered menu; remembers tenants; launches all other tools. | | `intune` | Bash wrapper (macOS/Linux): launcher by default, or `intune <Script> [args]` to run any `Scripts/*.ps1`/`*.py` without typing `pwsh`. Symlink onto PATH. |
| `Start-IntuneToolkit.ps1` | `fzf`/numbered menu; remembers tenants; launches all other tools. Entries are a list in display order (`$menuDefs`); numbers are assigned automatically and each entry has a stable internal `Id` used for dispatch. Includes the full tenant export (dated folder + drift check) and tenant comparison. |
| `Scripts/Start-HeadlessIntune.ps1` | Single-action wrapper (`Export`, `Import`, `DeployCISBaseline`, `GenerateReports`) with optional interactive TUI. | | `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. Settings Catalog names are resolved from `configurationSettings.json` (auto-exported with Settings Catalog). | | `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/Export-Policies.ps1` | Export policies to JSON. |
| `Scripts/Import-Policies.ps1` | Import policies from JSON. | | `Scripts/Import-Policies.ps1` | Import policies from JSON. |
| `Scripts/Initialize-IntuneAuth.ps1` | One-time Entra app setup; also supports `-RotateSecret`, `-Delete`, `-DeleteApp`. | | `Scripts/Initialize-IntuneAuth.ps1` | One-time Entra app setup; also supports `-RotateSecret`, `-Delete`, `-DeleteApp`. |
| `Scripts/Deploy-IntuneBaseline.ps1` | Declarative YAML baseline deployment with `-WhatIf` support. | | `Scripts/Deploy-IntuneBaseline.ps1` | Declarative YAML baseline deployment with `-WhatIf` support. |
| `Scripts/ConvertTo-IntuneBaseline.ps1` | Convert an existing export into a baseline skeleton. | | `Scripts/ConvertTo-IntuneBaseline.ps1` | Convert an existing export into a baseline skeleton. |
| `Scripts/Bulk-AssignmentManager.ps1` | Bulk add/remove policy assignments. | | `Scripts/Bulk-AssignmentManager.ps1` | Bulk add/remove policy assignments. |
| `Scripts/Bulk-ScopeTags.ps1` | Bulk add/replace/remove scope tags or clean up orphaned tag ids across object types; `-WhatIf`, batched PATCH. |
| `Scripts/Bulk-AppAssignment.ps1` | Bulk add/remove application assignments. | | `Scripts/Bulk-AppAssignment.ps1` | Bulk add/remove application assignments. |
| `Scripts/Backup-Restore-Assignments.ps1` | Backup and restore assignments across tenants. | | `Scripts/Backup-Restore-Assignments.ps1` | Backup and restore assignments across tenants. |
| `Scripts/Bulk-RenamePolicies.ps1` | Search/replace or prefix policy names and descriptions. | | `Scripts/Bulk-RenamePolicies.ps1` | Search/replace or prefix policy names and descriptions. |
@@ -229,4 +237,9 @@ python3 -m py_compile Scripts/_ConvertFrom-CISPDF.py
- The project is deployed manually: clone the repository and run `pwsh ./Start-IntuneToolkit.ps1` or the relevant script. - The project is deployed manually: clone the repository and run `pwsh ./Start-IntuneToolkit.ps1` or the relevant script.
- Version is tracked in the `VERSION` file and referenced by `README.md` and `CHANGELOG_macOS_IntuneToolkit.md`. - Version is tracked in the `VERSION` file and referenced by `README.md` and `CHANGELOG_macOS_IntuneToolkit.md`.
- There is no installer, no signed module package, and no automated release pipeline. - There is no installer, no signed module package, and no automated release pipeline.
- Menu: add an entry to `$menuDefs` in `Start-IntuneToolkit.ps1` with a new unique `Id` and handle that `Id` in the dispatch `switch` or an `if($choiceNumber -eq <Id>)` block. Do not renumber ids.
- Folder prompts in the launcher/TUI use `Select-FolderPath` (`Scripts/Private/Select-FolderPath.ps1`, fzf browser with create-folder and a plain-prompt fallback).
- Run-level setting overrides: `$global:SettingOverrides` (hashtable, set by `Invoke-IntuneHeadlessBatch`, read first by `Get-SettingValue`, never persisted). Headless export sets `UseBatchAPI` (default on, `-NoBatchApi` to disable) and `SortJsonProperties`.
- Import migration is lazy: groups from the migration table (and exported assignment filters missing in the target) are created in `Update-JsonForEnvironment` only when an imported object references them.
- Verify batch vs non-batch export with `Compare-Tenants.py` on two exports of the same tenant (expect no differences).
- When adding a new workload or object type, register it in both `Extensions/EndpointManager.psm1` (as an `Add-ViewItem`) and `Headless/IntuneManagement.Headless.psm1` (in `Get-DefaultIntunePolicyObjectTypes`) if it should be available headlessly. - When adding a new workload or object type, register it in both `Extensions/EndpointManager.psm1` (as an `Add-ViewItem`) and `Headless/IntuneManagement.Headless.psm1` (in `Get-DefaultIntunePolicyObjectTypes`) if it should be available headlessly.
+171
View File
@@ -1,5 +1,159 @@
# macOS Intune Toolkit Changelog # macOS Intune Toolkit Changelog
## 2026-11-24 — v4.6.2 — Folder picker in the launcher
### Changed
- **`Scripts/Private/Select-FolderPath.ps1`** (new, shared)
- The fzf folder browser (browse, create new folder, type a path) moved out of the TUI script so the launcher can use it too. When the start path does not exist it opens at the nearest existing parent. Without `fzf` it falls back to a plain prompt, with `~` and quotes handled and an optional default.
- **`Start-IntuneToolkit.ps1`**
- Folder prompts now use the picker: export root of *Full tenant export*, the export folders of tenants A and B plus the output folder in *Compare two tenant exports* (B opens next to A), the earlier-export choice of the drift check (answer `b`), and the paths in *Generate reports*.
## 2026-11-24 — v4.6.1 — Sequential menu numbers
### Changed
- **`Start-IntuneToolkit.ps1`**
- Menu numbers were whatever each item was given when it was added (1, 2, 23, 7, 5, 6, 3, ...). The menu is now a list of entries in display order and the numbers 1-24 are assigned automatically, so adding or moving an entry never needs renumbering. Dispatch still uses stable internal ids. Numbers for items 3 and up changed; the README reference to "delete tenant auth and app registration" is now item **24**.
## 2026-11-24 — v4.6.0 — Upstream 3.10/3.11 fixes, faster export, lazy migration, drift, bulk scope tags
### Added
- **`Scripts/Bulk-ScopeTags.ps1`** (menu item 24)
- Add, replace or remove scope tags across object types (optionally by name filter), or clean up tag ids that no longer exist. Shows the plan per type, supports `-WhatIf`, `-Force` and non-interactive use (`-Action`, `-ScopeTags`, `-ObjectTypes`, `-NameFilter`). Applies changes with batched PATCH requests; objects whose tag list would not change are skipped. Design follows upstream 4.0 `Set-GraphBulkScopeTags`.
- **Drift check in menu item 23**: after a full export, offers to compare with the newest earlier export of the same tenant (assignments included) and writes the report to `<root>/_drift/<old>-to-<new>/`.
- **Quality Updates (Policies)** object type (`windowsQualityUpdatePolicies`, Id `QualityUpdatePolicies`); the old type is titled *Quality Updates (Profiles)*.
- **Win32 app install/uninstall scripts** are exported (`#ScriptInfo`, plus the script files next to the JSON) and re-created on import and copy (upstream 3.10.1.18/3.10.3).
- **`SortJsonProperties`** setting: exported JSON has sorted properties for stable diffs. Always on for headless export.
- `-NoBatchApi` on `Export-Policies.ps1` / `Start-HeadlessIntune.ps1` / `Export-IntunePolicies`.
- `Compare-Tenants.py` accepts a folder that contains a single export folder (e.g. `SSD-260707` holding `Exports/`).
### Changed
- **Headless export uses the Graph batch API by default** (20 objects per call; `-NoBatchApi` falls back to one call per object). Run-level settings overrides (`$global:SettingOverrides`, set by the headless layer, never persisted) make this possible.
- **Migration creates only what is used**: with *Import assignments*, Entra groups are looked up or created in the target tenant only when an imported object references them (previously every exported group was created). Assignment filters that exist in the export but not in the target are created on demand too (needs *Replace dependency ids*). Synced source groups log a warning and are created as cloud groups. Group lookup now escapes apostrophes in names.
- New cloud groups get a random 10-character mailNickname like the Entra portal (was name + timestamp).
- Merged upstream 3.10.1.x–3.11.0 changes to `EndpointManager.psm1` (page-size flags, app fixes). Not ported: UI-only changes, system-browser sign-in, update check, the ADMX/registry import tool fixes (no `IntuneTools.psm1` in this fork).
## 2026-11-24 — v4.5.2 — Shell wrapper
### Added
- **`intune`** (repo root, bash)
- Start the toolkit without typing `pwsh`: `./intune` opens the launcher, `./intune -TenantId <id>` passes parameters to it, and `./intune <Script> [args]` runs any `Scripts/<Script>.ps1` or `.py` (e.g. `intune Export-Policies -TenantId <id> -ExportPath ~/out`, `intune Compare-Tenants --root-a ... --root-b ...`). Resolves symlinks, so `ln -s "$PWD/intune" ~/.local/bin/intune` works from anywhere. Prints a clear message when `pwsh` or `python3` is missing and lists available scripts for an unknown name.
## 2026-11-24 — v4.5.1 — Full tenant export menu entry
### Added
- **`Start-IntuneToolkit.ps1`**
- New menu item **23. Full tenant export (all types + assignments, dated folder)**. Asks for an export root folder (remembered in `Settings.json` as `FullExportRoot`, default `~/Local/IntuneExports`), then exports every default object type with assignments for the current tenant into `<root>/<TenantName>-yymmdd` (adds `-HHmm` if that folder already exists). Pair with item 22 to see drift between two exports of the same tenant.
## 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
- **`Scripts/Private/Start-IntuneManagementTui.ps1`**
- `Select-FolderPath` has a new **[Create new folder]** entry. It asks for a name, creates the folder inside the current one and moves into it. Invalid names and creation errors are reported without leaving the browser.
## 2026-11-24 — v4.4.2 — Export built-in Intune roles, fix ASCII header failure
### Fixed
- **`Extensions/MSGraph.psm1`** / **`Extensions/MSALAuthentication.psm1`**
- Every Graph call failed with `Request headers must contain only ASCII characters` when PowerShell ran with an en-US culture: the unused `ExpiresOn` request header held a date with a U+202F space before AM/PM. Header removed (nothing reads it).
### Changed
- **`Extensions/EndpointManager.psm1`** (Role Definitions)
- Export now includes built-in roles with their role assignments (was custom roles only).
- Import skips creating built-in roles. When *Import assignments* is enabled, their assignments are still recreated against the built-in role id (same in every tenant). Custom-role behaviour is unchanged.
## 2026-08-07 — v4.4.1 — Reorder TUI menu into logical groups
### Changed
- **`Start-IntuneToolkit.ps1`**
- Menu had grown by prepending each new feature to the top, so items ended up in reverse-add order with no relation between neighbors. Reordered into groups — Export/Import, Bulk operations, Baselines & compliance, Reporting, Tenant & auth admin — with Exit last. Item numbers (used for dispatch) are unchanged, only display order moved, so no other script or doc references needed updating.
## 2026-08-07 — v4.4.0 — Folder browser for Export/Import path prompts
### Added
- **`Scripts/Private/Start-IntuneManagementTui.ps1`**
- New `Select-FolderPath` helper: when `fzf` is available, the Export/Import root folder prompt (and the report flow's export/backup-root/output-dir prompts) becomes an interactive folder browser — navigate into subfolders, go up with `..`, confirm the current folder, or type a path manually. `Read-Host` alone has no tab-completion (that's a top-level PSReadLine feature, not available to script prompts), so this reuses the `fzf` dependency already required for menus instead of building custom completion.
- Falls back to a plain `Read-Host` prompt when `fzf` isn't installed — no regression from prior behavior.
## 2026-08-07 — v4.3.1 — Fix redundant action prompt
### Fixed
- **`Scripts/Private/Start-IntuneManagementTui.ps1`**
- Choosing **1. Export policies** or **2. Import policies** in the launcher still re-asked "Select action" (Export/Import/DeployCISBaseline/GenerateReports) — the same missing-passthrough issue as the tenant re-prompt fix below, just for `-Action`. Now accepts `-Action` and skips the prompt when it's already supplied.
- **`Start-IntuneToolkit.ps1`** / **`Scripts/Start-HeadlessIntune.ps1`**
- Menu items 1/2 now pass `-Action Export` / `-Action Import` through to the headless script and on to the TUI.
## 2026-08-07 — v4.3.0 — Bulk delete tool and TUI fixes
### Added
- **`Scripts/Bulk-DeletePolicies.ps1`**
- Select object type, filter by name, multi-select objects, and delete them from the tenant.
- Requires typing `DELETE` to confirm since the operation is irreversible. Supports `-WhatIf` dry-run.
- Wired into `Start-IntuneToolkit.ps1` as menu item **21. Bulk delete policies**.
### Fixed
- **`Start-IntuneToolkit.ps1`**
- Fixed an infinite loop when `fzf` is not installed: the numbered-menu fallback returned `"EXIT"` for the tenant-selection Exit option, but the check only matched the fzf path's `"[Exit]"` string, so choosing Exit was silently ignored and the tenant became the literal string `"EXIT"`.
- **`Scripts/Private/Start-IntuneManagementTui.ps1`**
- The interactive Export/Import/GenerateReports/DeployCISBaseline flow always re-prompted for a Tenant ID even when the tenant was already selected in the outer launcher, because it was invoked with no parameters and had an empty `param()` block. It now accepts `-TenantId` and skips its three tenant prompts when the value is already supplied.
- Clarified the "Name filter" prompt text — it's a plain case-insensitive substring match, not a regex (the underlying match escapes the value via `[RegEx]::Escape()`), so the old `'^Win-OIB-'` example was misleading.
- **`Scripts/Start-HeadlessIntune.ps1`**
- Passes `-TenantId` through to `Start-IntuneManagementTui.ps1` so the fix above takes effect.
## 2026-06-23 — v4.2.0 — Entra directory role membership export
### Added
- **`Scripts/Export-EntraRoleMembership.ps1`**
- Exports all active and PIM-eligible Microsoft Entra directory role memberships to CSV.
- Expands group-assigned roles to transitive group members.
- Marks whether each role is privileged.
- Supports the toolkit's standard `-AuthMode` (`AppOnly`, `Browser`, `DeviceCode`) and reads saved credentials from `Settings.json`/macOS Keychain.
- **`Start-IntuneToolkit.ps1`**
- Added menu item **20. Export Entra role membership** that launches the new script and prompts for the CSV output path.
- **`README.md`**
- Listed `Scripts/Export-EntraRoleMembership.ps1` in the entry points and documented its purpose.
### Repository hygiene
- **`.gitignore`**
- Ignore the local `accounts/` folder and stray operational shell scripts (`deploy.sh`, `restart_gateways.sh`).
---
## 2026-06-22 — Expanded settings report coverage and Conditional Access documentation
### Added
- **`Scripts/Export-SettingsReport.py`**
- Greatly expanded coverage: Settings Catalog, Compliance Policies V2, Endpoint Security, Device Management Intents, Administrative Templates, Device Configuration (with OMA-URI expansion), Compliance Policies V1, PowerShell/Shell/Compliance/Health scripts (base64-decoded previews), App Protection, App Configuration, Update Policies, Enrollment restrictions, Autopilot, W365, Filters, and more.
- Added dedicated processors for intent-style settings (`_Settings.json` companion files) and ADMX definition values.
- Added base64 decoding for script content with a configurable preview length.
- **`Scripts/Invoke-ConditionalAccessDocumentation.ps1`**
- New menu-driven Conditional Access policy documentation script (menu item **19** in `Start-IntuneToolkit.ps1`).
- Exports CA policies to CSV and optionally Excel, resolving object IDs to display names.
- **`Start-IntuneToolkit.ps1`**
- Added menu item **19. Document Conditional Access policies**.
### Fixed
- **`.gitignore`**
- Ignore `Scripts/ConditionalAccessDocumentation.csv` and `.xlsx` output files so tenant-specific documentation is not committed by accident.
---
## 2026-06-14 — Auto-export Settings Catalog definitions for report resolution ## 2026-06-14 — Auto-export Settings Catalog definitions for report resolution
### Added ### Added
@@ -9,6 +163,23 @@
- This lets `Scripts/Export-SettingsReport.py` resolve `settingDefinitionId` values to the human-readable names shown in the Intune portal without any manual steps. - This lets `Scripts/Export-SettingsReport.py` resolve `settingDefinitionId` values to the human-readable names shown in the Intune portal without any manual steps.
- Errors during definition export are logged but do not fail the policy export. - Errors during definition export are logged but do not fail the policy export.
- **`Scripts/Export-SettingsReport.py`**
- New `Platform` column between `Policy` and `Setting`.
- For Settings Catalog, platform is read from the `platforms` field (e.g. `macOS`, `windows10`).
- For legacy policies, platform is inferred from `platform`/`platformType` or from `@odata.type` (e.g. `#microsoft.graph.iosCompliancePolicy` → `iOS`).
### Fixed
- **`Extensions/MSGraph.psm1`**
- `Get-GraphMetaData` now stores `GraphMetaData.xml` in the cross-platform data folder (`Get-CloudApiDataFolder`) instead of the literal Windows path `%LOCALAPPDATA%\CloudAPIPowerShellManagement\GraphMetaData.xml`.
- Removed the stray `%LOCALAPPDATA%\CloudAPIPowerShellManagement` folder from the repository and moved the existing `GraphMetaData.xml` to the correct macOS app-data location.
- **`Extensions/MSALAuthentication.psm1`**
- On non-Windows platforms the toolkit now skips `TokenCacheHelperEx` compilation with an informational log instead of throwing a `System.Security.Cryptography.ProtectedData.dll` error.
- Applied the same skip to the legacy `Add-MSALPrereq_old` function for consistency.
- **`.gitignore`**
- Removed the literal `%LOCALAPPDATA%` ignore patterns; kept `GraphMetaData.xml` and `CloudAPIPowerShellManagement/` ignores as safeguards.
### Modified ### Modified
- **`AGENTS.md`** - **`AGENTS.md`**
- Added `Scripts/Export-SettingsReport.py` to the main entry points table and noted the automatic Settings Catalog name resolution. - Added `Scripts/Export-SettingsReport.py` to the main entry points table and noted the automatic Settings Catalog name resolution.
+6
View File
@@ -792,6 +792,12 @@ function Get-SettingValue
{ {
param($Key, $DefaultValue, [switch]$GlobalOnly, [switch]$TenantOnly, $TenantID) param($Key, $DefaultValue, [switch]$GlobalOnly, [switch]$TenantOnly, $TenantID)
# Per-run overrides (e.g. set by the headless layer); never persisted to Settings.json
if($global:SettingOverrides -is [hashtable] -and $global:SettingOverrides.ContainsKey($Key))
{
return $global:SettingOverrides[$Key]
}
$settingObj = $null $settingObj = $null
foreach($section in $global:appSettingSections) foreach($section in $global:appSettingSections)
{ {
+207 -17
View File
@@ -163,6 +163,7 @@ function Invoke-InitializeModule
PreImportCommand = { Start-PreImportConditionalAccess @args } PreImportCommand = { Start-PreImportConditionalAccess @args }
PostExportCommand = { Start-PostExportConditionalAccess @args } PostExportCommand = { Start-PostExportConditionalAccess @args }
ExpandAssignmentsList = $false ExpandAssignmentsList = $false
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -177,6 +178,7 @@ function Invoke-InitializeModule
PreImportCommand = { Start-PreImportTermsOfUse @args } PreImportCommand = { Start-PreImportTermsOfUse @args }
PostExportCommand = { Start-PostExportTermsOfUse @args } PostExportCommand = { Start-PostExportTermsOfUse @args }
GroupId = "ConditionalAccess" GroupId = "ConditionalAccess"
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -188,6 +190,7 @@ function Invoke-InitializeModule
ImportOrder = 50 ImportOrder = 50
GroupId = "ConditionalAccess" GroupId = "ConditionalAccess"
ExpandAssignmentsList = $false ExpandAssignmentsList = $false
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -207,6 +210,7 @@ function Invoke-InitializeModule
Permissons=@("DeviceManagementConfiguration.ReadWrite.All") Permissons=@("DeviceManagementConfiguration.ReadWrite.All")
Dependencies = @("ReusableSettings") Dependencies = @("ReusableSettings")
GroupId = "EndpointSecurity" GroupId = "EndpointSecurity"
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -239,6 +243,7 @@ function Invoke-InitializeModule
PostExportCommand = { Start-PostExportCompliancePolicies @args } PostExportCommand = { Start-PostExportCompliancePolicies @args }
PreUpdateCommand = { Start-PreUpdateCompliancePolicies @args } PreUpdateCommand = { Start-PreUpdateCompliancePolicies @args }
GroupId = "CompliancePolicies" GroupId = "CompliancePolicies"
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -286,6 +291,7 @@ function Invoke-InitializeModule
SkipRemoveProperties = @('Id') # Id is removed by PreImport. Required for default profile SkipRemoveProperties = @('Id') # Id is removed by PreImport. Required for default profile
PropertiesToRemoveForUpdate = @('isDefaultProfile','disableClientTelemetry') PropertiesToRemoveForUpdate = @('isDefaultProfile','disableClientTelemetry')
GroupId = "TenantAdmin" GroupId = "TenantAdmin"
SupportsPageSize = $false
}) })
<# <#
@@ -313,6 +319,7 @@ function Invoke-InitializeModule
GroupId = "Azure" GroupId = "Azure"
SkipAddIDOnExport = $true SkipAddIDOnExport = $true
ExpandAssignmentsList = $false ExpandAssignmentsList = $false
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -336,6 +343,7 @@ function Invoke-InitializeModule
AssignmentsType = "enrollmentConfigurationAssignments" AssignmentsType = "enrollmentConfigurationAssignments"
PropertiesToRemoveForUpdate = @('priority') PropertiesToRemoveForUpdate = @('priority')
GroupId = "WinEnrollment" GroupId = "WinEnrollment"
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -359,6 +367,7 @@ function Invoke-InitializeModule
AssignmentsType = "enrollmentConfigurationAssignments" AssignmentsType = "enrollmentConfigurationAssignments"
GroupId = "EnrollmentRestrictions" GroupId = "EnrollmentRestrictions"
ViewProperties = @("displayName","platformType","description","Id") ViewProperties = @("displayName","platformType","description","Id")
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -374,6 +383,7 @@ function Invoke-InitializeModule
SkipRemoveProperties = @('Id') SkipRemoveProperties = @('Id')
GroupId = "WinEnrollment" GroupId = "WinEnrollment"
Icon = "EnrollmentStatusPage" Icon = "EnrollmentStatusPage"
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -450,6 +460,7 @@ function Invoke-InitializeModule
PreImportAssignmentsCommand = { Start-PreImportAssignmentsTermsAndConditions @args } PreImportAssignmentsCommand = { Start-PreImportAssignmentsTermsAndConditions @args }
GroupId = "TenantAdmin" GroupId = "TenantAdmin"
ExpandAssignmentsList = $false ExpandAssignmentsList = $false
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -470,6 +481,7 @@ function Invoke-InitializeModule
Dependencies = @("Applications") Dependencies = @("Applications")
GroupId = "AppProtection" GroupId = "AppProtection"
ExpandAssignmentsList = $false ExpandAssignmentsList = $false
SupportsPageSize = $false
}) })
# These are also included in the managedAppPolicies API # These are also included in the managedAppPolicies API
@@ -489,6 +501,7 @@ function Invoke-InitializeModule
Icon = "AppConfiguration" Icon = "AppConfiguration"
GroupId = "AppConfiguration" GroupId = "AppConfiguration"
ExpandAssignmentsList = $false ExpandAssignmentsList = $false
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -521,8 +534,8 @@ function Invoke-InitializeModule
ImportOrder = 60 ImportOrder = 60
Expand="categories,assignments" # ODataMetadata is set to minimal so assignments can't be autodetected Expand="categories,assignments" # ODataMetadata is set to minimal so assignments can't be autodetected
ODataMetadata="minimal" # categories property not supported with ODataMetadata full ODataMetadata="minimal" # categories property not supported with ODataMetadata full
PostFileImportCommand = { Start-PostFileImportApplications @args } PostFileImportCommand = { Start-PostFileImportApplication @args }
PostCopyCommand = { Start-PostCopyApplications @args } PostCopyCommand = { Start-PostCopyApplication @args }
PreUpdateCommand = { Start-PreUpdateApplication @args } PreUpdateCommand = { Start-PreUpdateApplication @args }
PreImportCommand = { Start-PreImportCommandApplication @args } PreImportCommand = { Start-PreImportCommandApplication @args }
DetailExtension = { Add-DetailExtensionApplications @args } DetailExtension = { Add-DetailExtensionApplications @args }
@@ -592,7 +605,7 @@ function Invoke-InitializeModule
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
Title = "Quality Updates" Title = "Quality Updates (Profiles)"
Id = "QualityUpdates" Id = "QualityUpdates"
ViewID = "IntuneGraphAPI" ViewID = "IntuneGraphAPI"
API = "/deviceManagement/windowsQualityUpdateProfiles" API = "/deviceManagement/windowsQualityUpdateProfiles"
@@ -600,6 +613,18 @@ function Invoke-InitializeModule
Icon = "UpdatePolicies" Icon = "UpdatePolicies"
GroupId = "WinQualityUpdates" GroupId = "WinQualityUpdates"
PropertiesToRemoveForUpdate = @('releaseDateDisplayName','deployableContentDisplayName') PropertiesToRemoveForUpdate = @('releaseDateDisplayName','deployableContentDisplayName')
SupportsPageSize = $false
})
Add-ViewItem (New-Object PSObject -Property @{
Title = "Quality Updates (Policies)"
Id = "QualityUpdatePolicies"
ViewID = "IntuneGraphAPI"
API = "/deviceManagement/windowsQualityUpdatePolicies"
Permissons=@("DeviceManagementConfiguration.ReadWrite.All")
Icon = "UpdatePolicies"
GroupId = "WinQualityUpdates"
SupportsPageSize = $false
}) })
# Locations are not FULLY supported # Locations are not FULLY supported
@@ -670,6 +695,7 @@ function Invoke-InitializeModule
Permissons=@("DeviceManagementConfiguration.ReadWrite.All") Permissons=@("DeviceManagementConfiguration.ReadWrite.All")
Icon="DeviceConfiguration" Icon="DeviceConfiguration"
GroupId = "DeviceConfiguration" GroupId = "DeviceConfiguration"
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -677,7 +703,6 @@ function Invoke-InitializeModule
Id = "RoleDefinitions" Id = "RoleDefinitions"
ViewID = "IntuneGraphAPI" ViewID = "IntuneGraphAPI"
API = "/deviceManagement/roleDefinitions" API = "/deviceManagement/roleDefinitions"
QUERYLIST = "`$filter=isBuiltIn%20eq%20false"
PostExportCommand = { Start-PostExportRoleDefinitions @args } PostExportCommand = { Start-PostExportRoleDefinitions @args }
PreImportCommand = { Start-PreImportRoleDefinitions @args } PreImportCommand = { Start-PreImportRoleDefinitions @args }
PostFileImportCommand = { Start-PostFileImportRoleDefinitions @args } PostFileImportCommand = { Start-PostFileImportRoleDefinitions @args }
@@ -800,6 +825,7 @@ function Invoke-InitializeModule
PreDeleteCommand = { Start-PreDeleteADMXFiles @args } PreDeleteCommand = { Start-PreDeleteADMXFiles @args }
ViewProperties = @("fileName","status","Id") ViewProperties = @("fileName","status","Id")
PropertiesToRemove = @("languageCodes","targetPrefix","targetNamespace","policyType","revision","status","uploadDateTime") PropertiesToRemove = @("languageCodes","targetPrefix","targetNamespace","policyType","revision","status","uploadDateTime")
SupportsPageSize = $false
}) })
<# <#
@@ -843,6 +869,7 @@ function Invoke-InitializeModule
ExpandAssignmentsList = $false ExpandAssignmentsList = $false
Icon = "ConditionalAccess" Icon = "ConditionalAccess"
GroupId = "EndpointSecurity" GroupId = "EndpointSecurity"
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -858,6 +885,7 @@ function Invoke-InitializeModule
ExpandAssignmentsList = $false ExpandAssignmentsList = $false
Icon = "ConditionalAccess" Icon = "ConditionalAccess"
GroupId = "EndpointSecurity" GroupId = "EndpointSecurity"
SupportsPageSize = $false
}) })
Add-ViewItem (New-Object PSObject -Property @{ Add-ViewItem (New-Object PSObject -Property @{
@@ -898,6 +926,7 @@ function Invoke-InitializeModule
QUERYLIST = "`$top=500" QUERYLIST = "`$top=500"
Permissons = @("DeviceManagementConfiguration.ReadWrite.All") Permissons = @("DeviceManagementConfiguration.ReadWrite.All")
GroupId = "DeviceConfiguration" GroupId = "DeviceConfiguration"
ExpandAssignmentsList = $false
}) })
} }
@@ -1078,7 +1107,14 @@ function Set-EMViewPanel
$global:btnLoadAllPages.add_click({ $global:btnLoadAllPages.add_click({
Write-Status "Loading $($global:curObjectType.Title) objects" Write-Status "Loading $($global:curObjectType.Title) objects"
[array]$graphObjects = Get-GraphObjects -property $global:curObjectType.ViewProperties -objectType $global:curObjectType -AllPages [array]$graphObjects = Get-GraphObjects -property $global:curObjectType.ViewProperties -objectType $global:curObjectType -AllPages
$graphObjects | Where-Object { $_ -ne $null } | ForEach-Object { $global:dgObjects.ItemsSource.AddNewItem($_) | Out-Null } if(-not $global:dgObjects.Columns)
{
Show-GraphObjects -FromGraphObjects $graphObjects
}
else
{
$graphObjects | Where-Object { $_ -ne $null } | ForEach-Object { $global:dgObjects.ItemsSource.AddNewItem($_) | Out-Null }
}
$global:dgObjects.ItemsSource.CommitNew() $global:dgObjects.ItemsSource.CommitNew()
Set-GraphPagesButtonStatus Set-GraphPagesButtonStatus
Invoke-FilterBoxChanged $global:txtFilter -ForceUpdate Invoke-FilterBoxChanged $global:txtFilter -ForceUpdate
@@ -1088,7 +1124,14 @@ function Set-EMViewPanel
$global:btnLoadNextPage.add_click({ $global:btnLoadNextPage.add_click({
Write-Status "Loading $($global:curObjectType.Title) objects" Write-Status "Loading $($global:curObjectType.Title) objects"
[array]$graphObjects = Get-GraphObjects -property $global:curObjectType.ViewProperties -objectType $global:curObjectType -SinglePage [array]$graphObjects = Get-GraphObjects -property $global:curObjectType.ViewProperties -objectType $global:curObjectType -SinglePage
$graphObjects | Where-Object { $_ -ne $null } | ForEach-Object { $global:dgObjects.ItemsSource.AddNewItem($_) | Out-Null } if(-not $global:dgObjects.Columns)
{
Show-GraphObjects -FromGraphObjects $graphObjects
}
else
{
$graphObjects | Where-Object { $_ -ne $null } | ForEach-Object { $global:dgObjects.ItemsSource.AddNewItem($_) | Out-Null }
}
$global:dgObjects.ItemsSource.CommitNew() $global:dgObjects.ItemsSource.CommitNew()
Set-GraphPagesButtonStatus Set-GraphPagesButtonStatus
Invoke-FilterBoxChanged $global:txtFilter Invoke-FilterBoxChanged $global:txtFilter
@@ -2334,7 +2377,7 @@ function local:Add-AppConfigurationTargets
$appName, $appId, $appType = $targetedApp -split "[|][!][|]" $appName, $appId, $appType = $targetedApp -split "[|][!][|]"
if(-not $appName -or -not $appId) if(-not $appName -or -not $appId)
{ {
Write-Log "App Name and Id is missing in string: $appApp" 2 Write-Log "App Name and Id is missing in string: $targetedApp" 2
continue continue
} }
$tmpApps = (Invoke-GraphRequest -Url "/deviceAppManagement/mobileApps?`$filter=displayName eq '$appName'").value $tmpApps = (Invoke-GraphRequest -Url "/deviceAppManagement/mobileApps?`$filter=displayName eq '$appName'").value
@@ -2384,15 +2427,16 @@ function Start-PreImportAssignmentsAppConfiguration
#region Applications #region Applications
function Start-PostCopyApplications function Start-PostCopyApplication
{ {
param($objCopyFrom, $objNew, $objectType) param($objCopyFrom, $objNew, $objectType)
Start-ImportApp $objNew Start-ImportApp $objNew
Start-AddInstallScripts $objNew $objCopyFrom
Write-Status "" Write-Status ""
} }
function Start-PostFileImportApplications function Start-PostFileImportApplication
{ {
param($obj, $objectType, $file) param($obj, $objectType, $file)
@@ -2413,6 +2457,7 @@ function Start-PostFileImportApplications
} }
Start-ImportApp $obj $tmpFilName Start-ImportApp $obj $tmpFilName
Start-AddInstallScripts $obj $tmpObj
} }
function local:Start-ImportApp function local:Start-ImportApp
@@ -2488,6 +2533,84 @@ function local:Start-ImportApp
} }
} }
function local:Start-AddInstallScripts
{
param($obj, $fromAppObj)
if($fromAppObj -and ($fromAppObj.activeInstallScript."#ScriptInfo" -or $fromAppObj.activeUninstallScript."#ScriptInfo"))
{
Write-Log "Importing scripts for $($obj.displayName)"
$scriptsAdded = $false
$jsonData = @{}
$jsonData."@odata.type" = "#microsoft.graph.win32LobApp"
$jsonData."committedContentVersion" = "1"
foreach ($scriptType in @('activeInstallScript','activeUninstallScript')) {
$scriptInfo = $fromAppObj.$scriptType.'#ScriptInfo'
if (-not $scriptInfo) { continue }
Write-Log "Add $($scriptType -replace '^active','') script: $($scriptInfo.displayName)"
$json = [ordered]@{
'@odata.type' = $scriptInfo.'@odata.type'
displayName = $scriptInfo.displayName
enforceSignatureCheck = $scriptInfo.enforceSignatureCheck
runAs32Bit = $scriptInfo.runAs32Bit
content = $scriptInfo.content
} | ConvertTo-Json -Depth 10 -Compress
$scriptObject = Invoke-GraphRequest -Url "deviceAppManagement/mobileApps/$($obj.id)/microsoft.graph.win32LobApp/contentVersions/1/scripts" -Method POST -Content $json
if ($scriptObject) {
$jsonData.$scriptType = @{ targetId = $scriptObject.Id }
$scriptsAdded = $true
}
}
$i = 0
while($true)
{
$scripts = Invoke-GraphRequest -Url "deviceAppManagement/mobileApps/$($obj.id)/microsoft.graph.win32LobApp/contentVersions/1/scripts"
if(-not $scripts)
{
Write-Log "Failed to retrieve scripts for app after adding. Skipping Install/Uninstall script config." 2
return
}
if(($scripts.value.state | Select -Unique) -eq "commitSuccess")
{
Write-Log "Scripts added successfully"
break
}
if($i -ge 12)
{
Write-Log "Install/Uninstall scripts are still not in pending state after waiting for 1 minute." 3
return
}
Write-Log "Waiting for scripts to be added..."
Start-Sleep -Seconds 5
$i++
}
if($scriptsAdded)
{
Write-Log "Add script info to app"
$json = ConvertTo-Json $jsonData -Depth 10
$status = Invoke-GraphRequest -Url "deviceAppManagement/mobileApps/$($obj.id)" -Method PATCH -Body $json
if($status -eq $true)
{
Write-Log "Install/Uninstall script info updated successfully"
}
else
{
Write-Log "Failed to update Install/Uninstall script info" 2
}
}
}
}
function Start-PreUpdateApplication function Start-PreUpdateApplication
{ {
param($obj, $objectType, $curObject, $fromObj) param($obj, $objectType, $curObject, $fromObj)
@@ -2525,6 +2648,9 @@ function Start-PreImportCommandApplication
$obj.officeSuiteAppDefaultFileFormat = "officeOpenXMLFormat" $obj.officeSuiteAppDefaultFileFormat = "officeOpenXMLFormat"
} }
} }
if($obj.activeInstallScript) { $obj.activeInstallScript = $null }
if($obj.activeUninstallScript) { $obj.activeUninstallScript = $null }
} }
function Add-DetailExtensionApplications function Add-DetailExtensionApplications
@@ -2712,6 +2838,8 @@ function Start-PreImportAssignmentsApplications
function Start-PreDeleteApplications function Start-PreDeleteApplications
{ {
param($obj, $objectType)
if($obj.'@odata.type' -eq "#microsoft.graph.microsoftStoreForBusinessApp") if($obj.'@odata.type' -eq "#microsoft.graph.microsoftStoreForBusinessApp")
{ {
# Don't delete Microsoft Store for Business Apps # Don't delete Microsoft Store for Business Apps
@@ -2749,6 +2877,16 @@ function Start-PostExportApplications
} }
} }
} }
if($obj.activeInstallScript.'#ScriptInfo'.displayName)
{
[IO.File]::WriteAllBytes((Join-Path $path "$($fi.BaseName)_$($obj.activeInstallScript.'#ScriptInfo'.displayName)"), ([System.Convert]::FromBase64String($obj.activeInstallScript.'#ScriptInfo'.content)))
}
if($obj.activeUninstallScript.'#ScriptInfo'.displayName)
{
[IO.File]::WriteAllBytes((Join-Path $path "$($fi.BaseName)_$($obj.activeUninstallScript.'#ScriptInfo'.displayName)"), ([System.Convert]::FromBase64String($obj.activeUninstallScript.'#ScriptInfo'.content)))
}
} }
catch catch
{ {
@@ -2792,7 +2930,7 @@ function Start-PostExportApplications
} }
else else
{ {
Write-Log "Cound not find encryption file" Write-Log "Could not find encryption file"
} }
} }
} }
@@ -2852,7 +2990,7 @@ function Add-ScriptExportApplications
function Start-PostGetApplications { function Start-PostGetApplications {
param($obj, $objectType) param($obj, $objectType)
if($obj.Object.dependentAppCount -is [Int] -and ($obj.Object.dependentAppCount -gt 0 -or $obj.Object.supersededAppCount -gt 0)) { if(($obj.Object.dependentAppCount -as [int]) -gt 0 -or ($obj.Object.supersededAppCount -as [int]) -gt 0) {
$relationships = (Invoke-GraphRequest -Url "/deviceAppManagement/mobileApps/$($obj.Id)/relationships?`$filter=targetType%20eq%20microsoft.graph.mobileAppRelationshipType%27child%27").value $relationships = (Invoke-GraphRequest -Url "/deviceAppManagement/mobileApps/$($obj.Id)/relationships?`$filter=targetType%20eq%20microsoft.graph.mobileAppRelationshipType%27child%27").value
$dependencyApps = @() $dependencyApps = @()
$supersededApps = @() $supersededApps = @()
@@ -2872,6 +3010,37 @@ function Start-PostGetApplications {
$obj.Object | Add-Member -MemberType NoteProperty -Name "#CustomRefSupersedence" -Value ($supersededApps -join "|*|") $obj.Object | Add-Member -MemberType NoteProperty -Name "#CustomRefSupersedence" -Value ($supersededApps -join "|*|")
} }
} }
if($obj.Object.'@odata.type' -eq "#microsoft.graph.win32LobApp")
{
if($obj.Object.activeInstallScript.targetId -or $obj.Object.activeUninstallScript.targetId)
{
$scriptInfo = (Invoke-GraphRequest -Url "/deviceAppManagement/mobileApps/$($obj.Id)/microsoft.graph.win32LobApp/contentVersions/$($obj.Object.committedContentVersion)/scripts/").value
foreach($script in $scriptInfo) {
$scriptFullInfo = (Invoke-GraphRequest -Url "/deviceAppManagement/mobileApps/$($obj.Id)/microsoft.graph.win32LobApp/contentVersions/$($obj.Object.committedContentVersion)/scripts/$($script.id)?`$select=Id,Content")
if($scriptFullInfo.Content)
{
$script.content = $scriptFullInfo.Content
}
if($obj.Object.activeInstallScript.targetId -eq $script.id)
{
$tpObject = $obj.Object.activeInstallScript
}
elseif($obj.Object.activeUninstallScript.targetId -eq $script.id)
{
$tpObject = $obj.Object.activeUninstallScript
}
else
{
Write-Log "Script with id $($script.id) is not referenced by active install or uninstall script. Skipping." 2
continue
}
$tpObject | Add-Member -MemberType NoteProperty -Name "#ScriptInfo" -Value $script -Force
}
}
}
} }
function Start-PostImportApplications function Start-PostImportApplications
@@ -2934,9 +3103,9 @@ function local:Add-ApplicationReferences
Write-Log "No $appName application found with version $appVer" 2 Write-Log "No $appName application found with version $appVer" 2
continue continue
} }
elseif(-not ($tmpApp | measure).Count -gt 1) elseif(($tmpApp | measure).Count -gt 1)
{ {
Write-Log "Multiple $appName application found with version $appVer" 2 Write-Log "Multiple $appName applications found with version $appVer" 2
continue continue
} }
Write-Log "Add $appName ($appVer) to Dependency list" Write-Log "Add $appName ($appVer) to Dependency list"
@@ -2955,7 +3124,7 @@ function local:Add-ApplicationReferences
$appName, $appVer, $appId, $appType = $suppApp -split "[|][!][|]" $appName, $appVer, $appId, $appType = $suppApp -split "[|][!][|]"
if(-not $appName -or -not $appVer) if(-not $appName -or -not $appVer)
{ {
Write-Log "Could not get Name and Version from string: $appApp" 2 Write-Log "Could not get Name and Version from string: $suppApp" 2
continue continue
} }
$tmpApps = (Invoke-GraphRequest -Url "/deviceAppManagement/mobileApps?`$filter=displayName eq '$appName'").value $tmpApps = (Invoke-GraphRequest -Url "/deviceAppManagement/mobileApps?`$filter=displayName eq '$appName'").value
@@ -3499,17 +3668,38 @@ function Start-PostExportRoleDefinitions
function Start-PreImportRoleDefinitions function Start-PreImportRoleDefinitions
{ {
param($obj, $objectType) param($obj, $objectType, $file)
Remove-Property $obj "RoleAssignments" Remove-Property $obj "RoleAssignments"
Remove-Property $obj "RoleAssignments@odata.context" Remove-Property $obj "RoleAssignments@odata.context"
$tmpObj = Get-GraphObjectFromFile $file
if($tmpObj.isBuiltIn -eq $true -or $tmpObj.isBuiltInRoleDefinition -eq $true)
{
# Built-in roles cannot be created and have the same id in every tenant.
# Only recreate their assignments, and only when assignments are imported.
if($global:chkImportAssignments -and $global:chkImportAssignments.IsChecked -eq $true)
{
Import-RoleDefinitionAssignments $tmpObj.Id $tmpObj
}
else
{
Write-Log "Skipping built-in role '$($tmpObj.displayName)'. Enable 'Import assignments' to import its role assignments" 2
}
return @{ "Import" = $false }
}
} }
function Start-PostFileImportRoleDefinitions function Start-PostFileImportRoleDefinitions
{ {
param($obj, $objectType, $file) param($obj, $objectType, $file)
$tmpObj = Get-GraphObjectFromFile $file Import-RoleDefinitionAssignments $obj.Id (Get-GraphObjectFromFile $file)
}
function Import-RoleDefinitionAssignments
{
param($roleDefinitionId, $tmpObj)
$loadedScopeTags = $global:LoadedDependencyObjects["ScopeTags"] $loadedScopeTags = $global:LoadedDependencyObjects["ScopeTags"]
if(($tmpObj.RoleAssignments | measure).Count -gt 0 -and ($loadedScopeTags | measure).Count -gt 0) if(($tmpObj.RoleAssignments | measure).Count -gt 0 -and ($loadedScopeTags | measure).Count -gt 0)
@@ -3523,7 +3713,7 @@ function Start-PostFileImportRoleDefinitions
"displayName"= $roleAssignment.DisplayName "displayName"= $roleAssignment.DisplayName
"members" = $roleAssignment.members "members" = $roleAssignment.members
"resourceScopes" = $roleAssignment.resourceScopes "resourceScopes" = $roleAssignment.resourceScopes
"roleDefinition@odata.bind" = "https://graph.microsoft.com/beta/deviceManagement/roleDefinitions('$($obj.Id)')" "roleDefinition@odata.bind" = "https://graph.microsoft.com/beta/deviceManagement/roleDefinitions('$($roleDefinitionId)')"
"roleScopeTags@odata.bind" = @() "roleScopeTags@odata.bind" = @()
} }
+29 -17
View File
@@ -554,7 +554,12 @@ function Add-MSALPrereq
} }
} }
if (-not ("TokenCacheHelperEx" -as [type])) if (-not (Test-IsWindowsPlatform))
{
$global:SkipTokenCacheHelperEx = $true
Write-Log "Token cache serialization is only supported on Windows. Skipping TokenCacheHelperEx."
}
elseif (-not ("TokenCacheHelperEx" -as [type]))
{ {
[System.Collections.Generic.List[string]] $RequiredAssemblies = New-Object System.Collections.Generic.List[string] [System.Collections.Generic.List[string]] $RequiredAssemblies = New-Object System.Collections.Generic.List[string]
@@ -723,23 +728,31 @@ function Add-MSALPrereq_old
$script:msalFile = $msalPath $script:msalFile = $msalPath
} }
$RequiredAssemblies.Add('System.Security.dll') if (-not (Test-IsWindowsPlatform))
$RequiredAssemblies.Add('mscorlib.dll')
if($PSVersionTable.PSVersion.Major -ge 7)
{
$RequiredAssemblies.Add('System.Security.Cryptography.ProtectedData.dll')
}
$RequiredAssemblies.Add('System.Threading.dll')
try
{
Add-Type -Path ($global:AppRootFolder + "\CS\TokenCacheHelperEx.cs") -ReferencedAssemblies $RequiredAssemblies
}
catch
{ {
$global:SkipTokenCacheHelperEx = $true $global:SkipTokenCacheHelperEx = $true
Write-LogError "Failed to compile TokenCacheHelperEx. The access token will not be cached. Check write access to the CS folder and ASR policies" $_.Exception Write-Log "Token cache serialization is only supported on Windows. Skipping TokenCacheHelperEx."
}
else
{
$RequiredAssemblies.Add('System.Security.dll')
$RequiredAssemblies.Add('mscorlib.dll')
if($PSVersionTable.PSVersion.Major -ge 7)
{
$RequiredAssemblies.Add('System.Security.Cryptography.ProtectedData.dll')
}
$RequiredAssemblies.Add('System.Threading.dll')
try
{
Add-Type -Path ($global:AppRootFolder + "\CS\TokenCacheHelperEx.cs") -ReferencedAssemblies $RequiredAssemblies
}
catch
{
$global:SkipTokenCacheHelperEx = $true
Write-LogError "Failed to compile TokenCacheHelperEx. The access token will not be cached. Check write access to the CS folder and ASR policies" $_.Exception
}
} }
if(Test-IsWindowsPlatform) if(Test-IsWindowsPlatform)
{ {
@@ -1516,7 +1529,6 @@ public static class DeviceCodeHelper
$Headers = @{ $Headers = @{
'Content-Type' = 'application/json' 'Content-Type' = 'application/json'
'Authorization' = "Bearer " + $tmpResults.AccessToken 'Authorization' = "Bearer " + $tmpResults.AccessToken
'ExpiresOn' = $tmpResults.ExpiresOn
} }
$params = @{} $params = @{}
+279 -82
View File
@@ -200,6 +200,14 @@ function Invoke-InitializeModule
Description = "This will add object ID to the export file to support objects with the same name e.g. ObjectName_ObjectId.json" Description = "This will add object ID to the export file to support objects with the same name e.g. ObjectName_ObjectId.json"
}) "ImportExport" }) "ImportExport"
Add-SettingsObject (New-Object PSObject -Property @{
Title = "Sort Json Properties"
Key = "SortJsonProperties"
Type = "Boolean"
DefaultValue = $false
Description = "Write exported JSON with sorted properties so every export has the same property order (clean diffs, stable change tracking)"
}) "ImportExport"
Add-SettingsObject (New-Object PSObject -Property @{ Add-SettingsObject (New-Object PSObject -Property @{
Title = "Use Batch API (Preview)" Title = "Use Batch API (Preview)"
Key = "UseBatchAPI" Key = "UseBatchAPI"
@@ -431,7 +439,6 @@ function Invoke-GraphRequest
$Headers = @{ $Headers = @{
'Content-Type' = 'application/json; charset=utf-8' 'Content-Type' = 'application/json; charset=utf-8'
'Authorization' = "Bearer " + $global:MSALToken.AccessToken 'Authorization' = "Bearer " + $global:MSALToken.AccessToken
'ExpiresOn' = $global:MSALToken.ExpiresOn
'x-ms-client-request-id' = $requestId 'x-ms-client-request-id' = $requestId
} }
} }
@@ -1186,7 +1193,9 @@ function Get-GraphMetaData
# There also no other version information in response headers. Use file date to update every week # There also no other version information in response headers. Use file date to update every week
Write-Log "Load Graph MetaData file" Write-Log "Load Graph MetaData file"
$url = "https://graph.microsoft.com/beta/`$metadata" $url = "https://graph.microsoft.com/beta/`$metadata"
$fileFullPath = [Environment]::ExpandEnvironmentVariables("%LOCALAPPDATA%\CloudAPIPowerShellManagement\GraphMetaData.xml") $dataFolder = if(Get-Command Get-CloudApiDataFolder -ErrorAction SilentlyContinue) { Get-CloudApiDataFolder } else { [Environment]::ExpandEnvironmentVariables("%LOCALAPPDATA%\macOS_IntuneManagement") }
[void][IO.Directory]::CreateDirectory($dataFolder)
$fileFullPath = Join-Path $dataFolder "GraphMetaData.xml"
$fi = [IO.FileInfo]$fileFullPath $fi = [IO.FileInfo]$fileFullPath
$maxAge = (Get-Date).AddDays(-14) $maxAge = (Get-Date).AddDays(-14)
if($fi.Exists -and ($fi.LastWriteTime -gt $maxAge -or $fi.CreationTime -gt $maxAge)) if($fi.Exists -and ($fi.LastWriteTime -gt $maxAge -or $fi.CreationTime -gt $maxAge))
@@ -3162,91 +3171,92 @@ function Get-GraphMigrationObjectsFromFile
if($global:chkImportAssignments.IsChecked -eq $true) if($global:chkImportAssignments.IsChecked -eq $true)
{ {
# Only check groups if Assignments are imported # Register the groups only. They are looked up or created in the target tenant on demand
# This will CREATE the group if it doesn't exist in the target environment # (see Update-JsonForEnvironment), so only groups that an imported object really references are created.
foreach($migObj in $migFileObj.Objects) foreach($migObj in $migFileObj.Objects)
{ {
if($migObj.Type -like "*group*") if($migObj.Type -like "*group*")
{ {
$migTableGroupName = $migObj.DisplayName.Trim() $global:MigrationTableCache += (New-Object PSObject -Property @{
$originalGroupName = $migTableGroupName OriginalId = $migObj.Id
if($txtSearchPattern -and $migTableGroupName -match $txtSearchPattern) Id = $null
{ Type = $migObj.Type
$migTableGroupName = $migTableGroupName -replace $txtSearchPattern, $txtReplacePattern Pending = $true
} MigObj = $migObj
$obj = (Invoke-GraphRequest "/groups?`$filter=displayName eq '$($migTableGroupName)'").Value SearchPattern = $txtSearchPattern
if(-not $obj) ReplacePattern = $txtReplacePattern
{ })
$groupFi = $null
if($global:GraphMigrationTable)
{
$fi = [IO.FileInfo]$global:GraphMigrationTable
$groupFi = [IO.FileInfo](Join-Path (Join-Path $fi.DirectoryName "Groups") "$((Remove-InvalidFileNameChars $originalGroupName)).json")
}
if($groupFi.Exists -eq $true)
{
# ToDo: Create group from Json (could be a dynamic group)
# Warn if synched group
$groupObj = Get-GraphObjectFromFile $groupFi.FullName
#isAssignableToRole - For Role assignment groupd.
$keepProps = @("displayName","description","mailEnabled","mailNickname","securityEnabled","membershipRule","groupTypes", "membershipRuleProcessingState")
foreach($prop in $groupObj.PSObject.Properties)
{
if($prop.Name -in $keepProps) { continue }
Remove-Property $groupObj $prop.Name
}
$groupObj.displayName = $groupObj.displayName.Trim()
if($txtSearchPattern -and $groupObj.displayName -match $txtSearchPattern)
{
$groupObj.displayName = $groupObj.displayName -replace $txtSearchPattern, $txtReplacePattern
}
$groupJson = ConvertTo-Json $groupObj -Depth 50
}
else
{
$groupName = $migTableGroupName
Write-Log "No group object found for $groupName. Creating a cloud group with default settings" 2
$dateStr = ((Get-Date).ToString("yyMMddHHmmss"))
if(($groupName.Length + $dateStr.Length) -gt 64)
{
$nickName = $groupName.Substring(0,(64-$dateStr.Length))
}
else
{
$nickName = $groupName
}
$nickName = $nickName + $dateStr
$groupJson = @"
{
"displayName": "$($groupName)",
"mailEnabled": false,
"mailNickname": "$($nickName)",
"securityEnabled": true
}
"@
}
Write-Log "Create AAD Group $($migTableGroupName)"
$obj = Invoke-GraphRequest "/groups" -HttpMethod "POST" -Content $groupJson
}
if($obj)
{
$global:MigrationTableCache += (New-Object PSObject -Property @{
OriginalId = $migObj.Id
Id = $obj.Id
Type = $migObj.Type
})
}
} }
} }
} }
} }
# Find the group in the target tenant by name or create it. Returns the group object or $null
function Resolve-GraphMigrationGroup
{
param($migObj, $txtSearchPattern, $txtReplacePattern)
$migTableGroupName = $migObj.DisplayName.Trim()
$originalGroupName = $migTableGroupName
if($txtSearchPattern -and $migTableGroupName -match $txtSearchPattern)
{
$migTableGroupName = $migTableGroupName -replace $txtSearchPattern, $txtReplacePattern
}
$obj = (Invoke-GraphRequest "/groups?`$filter=displayName eq '$($migTableGroupName.Replace("'","''"))'").Value
if($obj)
{
return ($obj | Select-Object -First 1)
}
$groupFi = $null
if($global:GraphMigrationTable)
{
$fi = [IO.FileInfo]$global:GraphMigrationTable
$groupFi = [IO.FileInfo](Join-Path (Join-Path $fi.DirectoryName "Groups") "$((Remove-InvalidFileNameChars $originalGroupName)).json")
}
if($groupFi.Exists -eq $true)
{
# ToDo: Create group from Json (could be a dynamic group)
$groupObj = Get-GraphObjectFromFile $groupFi.FullName
if($groupObj.onPremisesSyncEnabled -eq $true)
{
Write-Log "Group '$originalGroupName' is synced from on-premises AD in the source tenant. Creating it as a cloud group" 2
}
#isAssignableToRole - For Role assignment groupd.
$keepProps = @("displayName","description","mailEnabled","mailNickname","securityEnabled","membershipRule","groupTypes", "membershipRuleProcessingState")
foreach($prop in $groupObj.PSObject.Properties)
{
if($prop.Name -in $keepProps) { continue }
Remove-Property $groupObj $prop.Name
}
$groupObj.displayName = $migTableGroupName
$groupJson = ConvertTo-Json $groupObj -Depth 50
}
else
{
Write-Log "No group object found for $migTableGroupName. Creating a cloud group with default settings" 2
# Random nickname like the Entra portal creates
$nickName = (New-Guid).Guid.SubString(0,10)
$groupJson = @"
{
"displayName": "$($migTableGroupName)",
"mailEnabled": false,
"mailNickname": "$($nickName)",
"securityEnabled": true
}
"@
}
Write-Log "Create AAD Group $($migTableGroupName)"
Invoke-GraphRequest "/groups" -HttpMethod "POST" -Content $groupJson
}
function Update-JsonForEnvironment function Update-JsonForEnvironment
{ {
param($json) param($json)
@@ -3260,8 +3270,19 @@ function Update-JsonForEnvironment
{ {
foreach($depObj in $global:LoadedDependencyObjects[$depObjType]) foreach($depObj in $global:LoadedDependencyObjects[$depObjType])
{ {
if(-not $depObj.Id -or -not $depObj.OriginalId) { continue } if(-not $depObj.OriginalId) { continue }
if($depObj.OriginalId.Length -lt 36) { continue } # Skip non-guid IDs # ToDo: Verify... if($depObj.OriginalId.Length -lt 36) { continue } # Skip non-guid IDs # ToDo: Verify...
if($json.IndexOf($depObj.OriginalId,[StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
if(-not $depObj.Id -and $depObj.Pending -and -not $depObj.Failed)
{
# Object exists in the export but not in the target tenant. Create it now that something uses it
Write-Log "Create $($depObj.Type) '$($depObj.Name)' in target tenant (referenced by imported object)"
$newDepObj = Import-GraphObject $depObj.FileObj.Object $depObj.ObjectType $depObj.FileObj.FileInfo.FullName
if($newDepObj -and $newDepObj.Id) { $depObj.Id = $newDepObj.Id } else { $depObj.Failed = $true }
}
if(-not $depObj.Id) { continue }
$json = $json -replace $depObj.OriginalId,$depObj.Id $json = $json -replace $depObj.OriginalId,$depObj.Id
} }
} }
@@ -3272,8 +3293,18 @@ function Update-JsonForEnvironment
# Enumerate all objects in the migration table and replace all exported Id's to Id's in the new environment # Enumerate all objects in the migration table and replace all exported Id's to Id's in the new environment
foreach($migInfo in ($global:MigrationTableCache | Where Type -like "*group*")) foreach($migInfo in ($global:MigrationTableCache | Where Type -like "*group*"))
{ {
if(-not $migInfo.Id -or -not $migInfo.OriginalId) { continue } if(-not $migInfo.OriginalId) { continue }
if($migInfo.OriginalId.Length -lt 36) { continue } # Skip non-guid IDs # ToDo: Verify... if($migInfo.OriginalId.Length -lt 36) { continue } # Skip non-guid IDs # ToDo: Verify...
if($json.IndexOf($migInfo.OriginalId,[StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
if(-not $migInfo.Id -and $migInfo.Pending -and -not $migInfo.Failed)
{
# Only look up or create the group in the target tenant when an imported object references it
$tmpGroup = Resolve-GraphMigrationGroup $migInfo.MigObj $migInfo.SearchPattern $migInfo.ReplacePattern
if($tmpGroup -and $tmpGroup.Id) { $migInfo.Id = $tmpGroup.Id } else { $migInfo.Failed = $true }
}
if(-not $migInfo.Id) { continue }
$json = $json -replace $migInfo.OriginalId,$migInfo.Id $json = $json -replace $migInfo.OriginalId,$migInfo.Id
} }
@@ -3387,6 +3418,27 @@ function Add-GraphDependencyObjects
} }
} }
if($depObjectType.Id -eq "AssignmentFilters")
{
# Exported filters that do not exist in the target tenant. Created on demand, only when an imported object references them
foreach($depFile in $depFiles)
{
$depFileName = Get-GraphObjectName $depFile.Object $depObjectType
if($depFile.Object.Id -and -not ($arrDepObjects | Where { $_.OriginalId -eq $depFile.Object.Id }) -and -not ($depObjects | Where { (Get-GraphObjectName $_ $depObjectType) -eq $depFileName }))
{
$arrDepObjects += New-Object PSObject -Property @{
OriginalId = $depFile.Object.Id
Name = $depFileName
Id = $null
Type = $depObjectType.Id
Pending = $true
FileObj = $depFile
ObjectType = $depObjectType
}
}
}
}
if($arrDepObjects.Count -gt 0) if($arrDepObjects.Count -gt 0)
{ {
$global:LoadedDependencyObjects.Add($depObjectType.Id,$arrDepObjects) $global:LoadedDependencyObjects.Add($depObjectType.Id,$arrDepObjects)
@@ -4673,7 +4725,14 @@ function Save-GraphObjectToFile
{ {
param($obj, $fileName) param($obj, $fileName)
$json = $obj | ConvertTo-Json -Depth 50 if((Get-SettingValue "SortJsonProperties") -eq $true)
{
$json = $obj | ConvertTo-JsonSortedGraph -Depth 50
}
else
{
$json = $obj | ConvertTo-Json -Depth 50
}
if($global:Organization.Id) if($global:Organization.Id)
{ {
@@ -4690,6 +4749,144 @@ function Save-GraphObjectToFile
} }
} }
function Invoke-SortJsonGraphObject {
param(
[Parameter(Mandatory)]
$InputObject
)
if ($null -eq $InputObject) { return $null }
if ($InputObject -is [System.Collections.IList]) {
$new = @()
foreach ($item in $InputObject) {
$new += Invoke-SortJsonGraphObject $item
}
return ,$new
}
if ($InputObject -is [System.Collections.IDictionary] -or
$InputObject -is [System.Management.Automation.PSCustomObject]) {
$props =
if ($InputObject -is [System.Collections.IDictionary]) {
$InputObject.Keys
} else {
$InputObject.PSObject.Properties.Name
}
$baseGroups = @{}
foreach ($p in $props) {
if ($p -match '^(.+?)@(.+)$') {
$base = $matches[1]
if (-not $baseGroups.ContainsKey($base)) {
$baseGroups[$base] = @{
Base = $null
Meta = New-Object System.Collections.ArrayList
}
}
[void]$baseGroups[$base].Meta.Add($p)
}
}
foreach ($p in $props) {
if ($baseGroups.ContainsKey($p)) {
$baseGroups[$p].Base = $p
}
}
$atProps = @() # starts with @
$hashProps = @() # starts with #
$normal = @() # everything else
foreach ($p in $props) {
if ($p.StartsWith('@')) {
$atProps += $p
continue
}
if ($p.StartsWith('#')) {
$hashProps += $p
continue
}
# If in a baseGroup, skip for now (added later)
if ($baseGroups.ContainsKey($p)) {
continue
}
$normal += $p
}
$atProps = $atProps | Sort-Object
$normal = $normal | Sort-Object
$hashProps = $hashProps | Sort-Object
$orderedNames = @()
$orderedNames += $atProps
foreach ($base in ($baseGroups.Keys | Sort-Object)) {
$meta = $baseGroups[$base].Meta | Sort-Object
foreach ($m in $meta) {
$orderedNames += $m
}
if ($null -ne $InputObject.$base) {
$orderedNames += $base
}
}
$orderedNames += $normal
$orderedNames += $hashProps
$result = [ordered]@{}
foreach ($p in $orderedNames) {
$value =
if ($InputObject -is [System.Collections.IDictionary]) {
$InputObject[$p]
} else {
$InputObject.$p
}
if($null -ne $value) {
$result[$p] = Invoke-SortJsonGraphObject $value
}
else {
$result[$p] = $null
}
if($InputObject.$p -is [Array] -and $result[$p] -isnot [Array]) {
if($result[$p] -eq $null) {
$result[$p] = @()
}
else {
$result[$p] = @($result[$p])
}
}
}
return [pscustomobject]$result
}
return $InputObject
}
function ConvertTo-JsonSortedGraph {
param(
[Parameter(ValueFromPipeline, Mandatory)]
$InputObject,
[int]$Depth = 50
)
$sorted = Invoke-SortJsonGraphObject $InputObject
return $sorted | ConvertTo-Json -Depth $Depth
}
function Get-GraphObjectFile function Get-GraphObjectFile
{ {
param($obj, $objectType, $path) param($obj, $objectType, $path)
+17 -5
View File
@@ -40,6 +40,7 @@ function Get-DefaultIntunePolicyObjectTypes
"UpdatePolicies", "UpdatePolicies",
"FeatureUpdates", "FeatureUpdates",
"QualityUpdates", "QualityUpdates",
"QualityUpdatePolicies",
"DriverUpdateProfiles", "DriverUpdateProfiles",
"HardwareConfigurations", "HardwareConfigurations",
"InventoryPolicies", "InventoryPolicies",
@@ -134,7 +135,9 @@ function Invoke-IntuneHeadlessBatch
[string]$SettingsFile, [string]$SettingsFile,
[string]$BatchFile [string]$BatchFile,
[hashtable]$SettingOverrides
) )
if(($AuthMode -eq "Browser" -or $AuthMode -eq "DeviceCode") -and -not $AppId) if(($AuthMode -eq "Browser" -or $AuthMode -eq "DeviceCode") -and -not $AppId)
@@ -226,11 +229,13 @@ function Invoke-IntuneHeadlessBatch
$invokeParams.Certificate = $Certificate $invokeParams.Certificate = $Certificate
} }
$global:SettingOverrides = $SettingOverrides
Import-Module $runtimeModule -Force Import-Module $runtimeModule -Force
Initialize-IntuneManagementRuntime -View "IntuneGraphAPI" @invokeParams Initialize-IntuneManagementRuntime -View "IntuneGraphAPI" @invokeParams
} }
finally finally
{ {
$global:SettingOverrides = $null
if($deleteBatchFile -and (Test-Path $BatchFile)) if($deleteBatchFile -and (Test-Path $BatchFile))
{ {
Remove-Item -LiteralPath $BatchFile -Force -ErrorAction SilentlyContinue Remove-Item -LiteralPath $BatchFile -Force -ErrorAction SilentlyContinue
@@ -273,7 +278,10 @@ function Export-IntunePolicies
[switch]$IncludeAssignments, [switch]$IncludeAssignments,
[switch]$AddCompanyName [switch]$AddCompanyName,
# Batch API (20 objects per call) is on for export; use this to fall back to one call per object
[switch]$NoBatchApi
) )
$batchConfig = [PSCustomObject]@{ $batchConfig = [PSCustomObject]@{
@@ -298,7 +306,8 @@ function Export-IntunePolicies
-RedirectUri $RedirectUri ` -RedirectUri $RedirectUri `
-BatchConfig $batchConfig ` -BatchConfig $batchConfig `
-SettingsFile $SettingsFile ` -SettingsFile $SettingsFile `
-BatchFile $BatchFile -BatchFile $BatchFile `
-SettingOverrides @{ UseBatchAPI = (-not $NoBatchApi); SortJsonProperties = $true }
} }
function Import-IntunePolicies function Import-IntunePolicies
@@ -418,7 +427,9 @@ function Invoke-IntunePolicyAction
[switch]$IncludeScopeTags, [switch]$IncludeScopeTags,
[switch]$ReplaceDependencyIds [switch]$ReplaceDependencyIds,
[switch]$NoBatchApi
) )
switch($Action) switch($Action)
@@ -441,7 +452,8 @@ function Invoke-IntunePolicyAction
-NameReplacePattern $NameReplacePattern ` -NameReplacePattern $NameReplacePattern `
-ObjectTypes $ObjectTypes ` -ObjectTypes $ObjectTypes `
-IncludeAssignments:$IncludeAssignments ` -IncludeAssignments:$IncludeAssignments `
-AddCompanyName:$AddCompanyName -AddCompanyName:$AddCompanyName `
-NoBatchApi:$NoBatchApi
} }
"Import" "Import"
{ {
+39 -3
View File
@@ -2,7 +2,7 @@
Cross-platform, headless Intune policy export/import with PowerShell. Cross-platform, headless Intune policy export/import with PowerShell.
**Current version:** `4.1.0` — see [`CHANGELOG_macOS_IntuneToolkit.md`](CHANGELOG_macOS_IntuneToolkit.md) for recent changes. **Current version:** `4.6.2` — see [`CHANGELOG_macOS_IntuneToolkit.md`](CHANGELOG_macOS_IntuneToolkit.md) for recent changes.
This repository is now CLI-first. The old WPF application surface has been removed from the repo. The supported workflow is: This repository is now CLI-first. The old WPF application surface has been removed from the repo. The supported workflow is:
@@ -24,6 +24,17 @@ If `fzf` is installed you get an interactive picker; otherwise you get a numbere
pwsh ./Start-IntuneToolkit.ps1 -TenantId "<tenant-id>" pwsh ./Start-IntuneToolkit.ps1 -TenantId "<tenant-id>"
``` ```
On macOS/Linux the `intune` wrapper starts the same launcher without typing `pwsh`, and runs any script by name:
```bash
./intune # launcher
./intune Export-Policies -TenantId <id> -ExportPath ~/out # Scripts/Export-Policies.ps1
./intune Compare-Tenants --root-a A --root-b B # Scripts/Compare-Tenants.py
ln -s "$PWD/intune" ~/.local/bin/intune # optional: use it from anywhere
```
Launcher menu (numbers are assigned automatically in this order): export/import (including **Full tenant export** into a dated folder with an optional drift check against the previous export), bulk operations (assignments, rename, delete, **scope tags**, devices), baselines and compliance, reporting (reports, Entra role membership, **offline tenant comparison**) and tenant/auth administration. Folder prompts use an fzf folder browser with "create new folder".
## Entry points ## Entry points
* [Start-IntuneToolkit.ps1](/Users/avedelphina/Local/IntuneManagement/Start-IntuneToolkit.ps1) — unified launcher (recommended) * [Start-IntuneToolkit.ps1](/Users/avedelphina/Local/IntuneManagement/Start-IntuneToolkit.ps1) — unified launcher (recommended)
@@ -32,6 +43,9 @@ pwsh ./Start-IntuneToolkit.ps1 -TenantId "<tenant-id>"
* [Scripts/Import-Policies.ps1](/Users/avedelphina/Local/IntuneManagement/Scripts/Import-Policies.ps1) * [Scripts/Import-Policies.ps1](/Users/avedelphina/Local/IntuneManagement/Scripts/Import-Policies.ps1)
* [Scripts/Initialize-IntuneAuth.ps1](/Users/avedelphina/Local/IntuneManagement/Scripts/Initialize-IntuneAuth.ps1) — one-time Entra app + secret + Keychain setup * [Scripts/Initialize-IntuneAuth.ps1](/Users/avedelphina/Local/IntuneManagement/Scripts/Initialize-IntuneAuth.ps1) — one-time Entra app + secret + Keychain setup
* [Scripts/Export-SettingsReport.py](/Users/avedelphina/Local/IntuneManagement/Scripts/Export-SettingsReport.py) — generate a flat CSV of policy settings/values * [Scripts/Export-SettingsReport.py](/Users/avedelphina/Local/IntuneManagement/Scripts/Export-SettingsReport.py) — generate a flat CSV of policy settings/values
* [Scripts/Compare-Tenants.py](Scripts/Compare-Tenants.py) — offline comparison of two export folders (see [Tenant comparison](#tenant-comparison))
* [Scripts/Bulk-ScopeTags.ps1](Scripts/Bulk-ScopeTags.ps1) — bulk add/replace/remove scope tags
* [Scripts/Export-EntraRoleMembership.ps1](/Users/avedelphina/Local/IntuneManagement/Scripts/Export-EntraRoleMembership.ps1) — export all active + PIM-eligible Entra directory role memberships (group assignments expanded) to CSV
* [Headless/IntuneManagement.Headless.psd1](/Users/avedelphina/Local/IntuneManagement/Headless/IntuneManagement.Headless.psd1) * [Headless/IntuneManagement.Headless.psd1](/Users/avedelphina/Local/IntuneManagement/Headless/IntuneManagement.Headless.psd1)
## Runtime ## Runtime
@@ -54,6 +68,7 @@ The default headless policy scope is:
* `CompliancePolicies` * `CompliancePolicies`
* `EndpointSecurity` * `EndpointSecurity`
* `PolicySets` * `PolicySets`
* ... and about 40 more (scripts, Autopilot, enrollment, app protection, update policies including *Quality Updates (Profiles/Policies)*, role definitions, scope tags, filters, Conditional Access, ...). The full list is `Get-DefaultIntunePolicyObjectTypes` in [`Headless/IntuneManagement.Headless.psm1`](Headless/IntuneManagement.Headless.psm1).
You can override that list with `-ObjectTypes`. You can override that list with `-ObjectTypes`.
@@ -76,6 +91,8 @@ pwsh ./Scripts/Export-Policies.ps1 `
-IncludeAssignments -IncludeAssignments
``` ```
Export uses the Graph batch API (20 objects per call) and writes JSON with sorted properties so repeated exports diff cleanly. Pass `-NoBatchApi` to fall back to one call per object. Role definitions are exported with their role assignments, including built-in roles; on import built-in roles are not created, their assignments are recreated only when assignments are imported.
## Export with browser auth ## Export with browser auth
```powershell ```powershell
@@ -144,17 +161,36 @@ pwsh ./Scripts/Start-HeadlessIntune.ps1 `
* **CIS M365 baseline** — [`Deploy-CISM365Baseline.ps1`](Scripts/Deploy-CISM365Baseline.ps1) applies the CIS Microsoft 365 v7 benchmark to a tenant. See [`Baselines/M365-CIS-Rapid/`](Baselines/M365-CIS-Rapid/) for a config-driven rapid baseline. * **CIS M365 baseline** — [`Deploy-CISM365Baseline.ps1`](Scripts/Deploy-CISM365Baseline.ps1) applies the CIS Microsoft 365 v7 benchmark to a tenant. See [`Baselines/M365-CIS-Rapid/`](Baselines/M365-CIS-Rapid/) for a config-driven rapid baseline.
* **Bulk assignments** — [`Bulk-AssignmentManager.ps1`](Scripts/Bulk-AssignmentManager.ps1) adds or removes assignments for any policy type using the bulk `/assign` endpoint. [`Bulk-AppAssignment.ps1`](Scripts/Bulk-AppAssignment.ps1) does the same for applications. * **Bulk assignments** — [`Bulk-AssignmentManager.ps1`](Scripts/Bulk-AssignmentManager.ps1) adds or removes assignments for any policy type using the bulk `/assign` endpoint. [`Bulk-AppAssignment.ps1`](Scripts/Bulk-AppAssignment.ps1) does the same for applications.
* **Backup / restore assignments** — [`Backup-Restore-Assignments.ps1`](Scripts/Backup-Restore-Assignments.ps1) saves assignments to JSON and can restore them with cross-tenant group name resolution. * **Backup / restore assignments** — [`Backup-Restore-Assignments.ps1`](Scripts/Backup-Restore-Assignments.ps1) saves assignments to JSON and can restore them with cross-tenant group name resolution.
* **Bulk scope tags** — [`Bulk-ScopeTags.ps1`](Scripts/Bulk-ScopeTags.ps1) adds, replaces or removes scope tags across object types (optionally filtered by name) or cleans up tag ids that no longer exist. Shows the plan first, supports `-WhatIf`, `-Force` and non-interactive parameters (`-Action`, `-ScopeTags`, `-ObjectTypes`, `-NameFilter`).
* **Bulk rename** — [`Bulk-RenamePolicies.ps1`](Scripts/Bulk-RenamePolicies.ps1) performs search/replace or prefix mutations across policy names and descriptions. * **Bulk rename** — [`Bulk-RenamePolicies.ps1`](Scripts/Bulk-RenamePolicies.ps1) performs search/replace or prefix mutations across policy names and descriptions.
* **Bulk delete** — [`Bulk-DeletePolicies.ps1`](Scripts/Bulk-DeletePolicies.ps1) deletes selected policies/apps by object type and name filter, requires typing `DELETE` to confirm, supports `-WhatIf`.
* **Device operations** — [`Bulk-DeviceOperations.ps1`](Scripts/Bulk-DeviceOperations.ps1) supports delete, retire, wipe, lock, and sync with `-WhatIf` safeguards. * **Device operations** — [`Bulk-DeviceOperations.ps1`](Scripts/Bulk-DeviceOperations.ps1) supports delete, retire, wipe, lock, and sync with `-WhatIf` safeguards.
* **Assignment documentation** — [`Export-AssignmentsToCsv.ps1`](Scripts/Export-AssignmentsToCsv.ps1) exports assignments to CSV and Markdown. * **Assignment documentation** — [`Export-AssignmentsToCsv.ps1`](Scripts/Export-AssignmentsToCsv.ps1) exports assignments to CSV and Markdown.
* **Reporting utilities** — [`Export-SettingsReport.py`](Scripts/Export-SettingsReport.py), [`Export-AssignmentReport.py`](Scripts/Export-AssignmentReport.py), and [`Export-ObjectInventoryReport.py`](Scripts/Export-ObjectInventoryReport.py) generate CSV/Markdown reports from local exports. * **Reporting utilities** — [`Export-SettingsReport.py`](Scripts/Export-SettingsReport.py), [`Export-AssignmentReport.py`](Scripts/Export-AssignmentReport.py), and [`Export-ObjectInventoryReport.py`](Scripts/Export-ObjectInventoryReport.py) generate CSV/Markdown reports from local exports.
* **Baseline batch runner** — [`Invoke-BaselineBatch.ps1`](Scripts/Invoke-BaselineBatch.ps1) run multiple baseline manifests in one pass. * **Baseline batch runner** — [`Invoke-BaselineBatch.ps1`](Scripts/Invoke-BaselineBatch.ps1) run multiple baseline manifests in one pass.
* **Conditional Access wizard** — [`Start-CAWizard.ps1`](Scripts/Start-CAWizard.ps1) / [`ca-wizard.py`](Scripts/ca-wizard.py) generate Conditional Access baseline skeletons. * **Conditional Access wizard** — [`Start-CAWizard.ps1`](Scripts/Start-CAWizard.ps1) / [`ca-wizard.py`](Scripts/ca-wizard.py) generate Conditional Access baseline skeletons.
## Tenant comparison
[`Compare-Tenants.py`](Scripts/Compare-Tenants.py) compares two export folders offline (no Graph calls): two tenants with different name prefixes and assignments, or two exports of one tenant to see drift.
```bash
./intune Compare-Tenants \
--root-a ~/Local/IntuneExports/SSD-261124 --label-a SSD --strip-a '^SSD\s*-\s*' \
--root-b ~/Local/IntuneExports/SSE-261124 --label-b SSE --strip-b '^SSE\s*-\s*' \
--output-dir ~/Local/IntuneExports/compare [--include-assignments]
```
* Works for every exported category (Settings Catalog, device configuration, compliance, Autopilot, ESP, roles, apps, ...). IDs, timestamps, scope tags, OData metadata and names are ignored; GUIDs are resolved to names through the exported groups and filters.
* Policies are matched by name after stripping the per-tenant prefix (`--strip-a/--strip-b`, regex), then by fuzzy name similarity (`--fuzzy-threshold`), then by near-identical content (`--content-threshold`). `--no-fuzzy` keeps exact matching only; every non-exact match is listed with its score.
* Output: `tenant-comparison.md` (summary per category, only-in-A/B, setting-level differences) and `tenant-comparison.csv`.
* Leave both prefixes blank to compare two exports of the same tenant. The **Full tenant export** menu entry offers this automatically after exporting.
## Notes ## Notes
* Export writes a migration table used during cross-tenant import. * Export writes a migration table used during cross-tenant import.
* Import can translate dependency IDs and recreate missing assignment groups. * Import can translate dependency IDs. With *Import assignments*, Entra groups (and, with *Replace dependency ids*, assignment filters) are looked up or created in the target tenant only when an imported object references them. Synced source groups are created as cloud groups.
* Win32 app install/uninstall scripts are exported and recreated on import.
* This repo intentionally does not preserve the old Windows UI launch flow. * This repo intentionally does not preserve the old Windows UI launch flow.
* Browser auth uses the system browser and a loopback redirect. * Browser auth uses the system browser and a loopback redirect.
* If you omit `-AppId` with `-AuthMode Browser`, the CLI defaults to the Microsoft Graph PowerShell public client app id `14d82eec-204b-4c2f-b7e8-296a70dab67e`. * If you omit `-AppId` with `-AuthMode Browser`, the CLI defaults to the Microsoft Graph PowerShell public client app id `14d82eec-204b-4c2f-b7e8-296a70dab67e`.
@@ -167,4 +203,4 @@ By default `Initialize-IntuneAuth.ps1` creates an **app-only** registration. Eve
* **Audit logs** show the app's display name (e.g., `IntuneManagement-tomas.kracmar@cqre.net`), not the admin's UPN. The initializer now automatically names the app after the **authenticated Entra user** to improve traceability. * **Audit logs** show the app's display name (e.g., `IntuneManagement-tomas.kracmar@cqre.net`), not the admin's UPN. The initializer now automatically names the app after the **authenticated Entra user** to improve traceability.
* **PIM is not enforced** for app-only secrets. The service principal has standing permissions, so write operations can occur outside an elevated PIM window. * **PIM is not enforced** for app-only secrets. The service principal has standing permissions, so write operations can occur outside an elevated PIM window.
* If you need strict PIM compliance, use **delegated authentication** (`-AuthMode Browser` or `-AuthMode DeviceCode`) so calls are made in the signed-in user's context. Note that `DeviceCode` may be blocked by Conditional Access policies. * If you need strict PIM compliance, use **delegated authentication** (`-AuthMode Browser` or `-AuthMode DeviceCode`) so calls are made in the signed-in user's context. Note that `DeviceCode` may be blocked by Conditional Access policies.
* To fully remove a tenant's local credentials **and** the Entra app registration, use menu item **15** in the TUI or run `./Scripts/Initialize-IntuneAuth.ps1 -TenantId "<id>" -DeleteApp`. * To fully remove a tenant's local credentials **and** the Entra app registration, use menu item **24** ("Delete tenant auth and app registration") in the TUI or run `./Scripts/Initialize-IntuneAuth.ps1 -TenantId "<id>" -DeleteApp`.
+354
View File
@@ -0,0 +1,354 @@
#requires -Version 5.1
<#
.SYNOPSIS
Bulk delete Intune policies/apps by object type and name filter.
.DESCRIPTION
Select an object type, optionally filter by name, multi-select objects,
and delete them from the tenant. Requires typing DELETE to confirm since
this is irreversible. Supports -WhatIf dry-run.
.EXAMPLE
./Scripts/Bulk-DeletePolicies.ps1 -TenantId "contoso.onmicrosoft.com" -WhatIf
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$TenantId,
[string]$AppId,
[string]$Secret,
[string]$Certificate,
[ValidateSet("AppOnly","Browser","DeviceCode")]
[string]$AuthMode = "AppOnly",
[string]$RedirectUri,
[string]$SettingsFile,
[switch]$WhatIf
)
$ErrorActionPreference = "Stop"
#region Helper functions
function Test-FzfAvailable
{
return [bool](Get-Command fzf -ErrorAction SilentlyContinue)
}
function Show-FzfMenu
{
param(
[Parameter(Mandatory)]
[string[]]$Items,
[string]$Header = "Select one",
[switch]$Multi
)
$argsList = @("--header=$Header")
if($Multi) { $argsList += "--multi" }
$selected = $Items | fzf @argsList
if(-not $selected) { return $null }
if($Multi) { return @($selected -split "`r?`n" | Where-Object { $_ }) }
return $selected
}
function Show-NumberedMenu
{
param(
[Parameter(Mandatory)]
[string[]]$Items,
[string]$Header = "Select one or more",
[switch]$Multi
)
Write-Host "`n$Header" -ForegroundColor Cyan
for($i=0; $i -lt $Items.Count; $i++)
{
Write-Host " $($i+1). $($Items[$i])"
}
if($Multi)
{
$prompt = "Enter numbers separated by commas (e.g. 1,3,5) or 'all'"
}
else
{
$prompt = "Enter a number"
}
$choice = Read-Host $prompt
if($choice -eq "all" -and $Multi) { return $Items }
$indices = $choice -split "," | ForEach-Object { $_.Trim() } | Where-Object { $_ -match "^\d+$" } | ForEach-Object { [int]$_ - 1 } | Where-Object { $_ -ge 0 -and $_ -lt $Items.Count }
if($Multi)
{
return $Items[$indices] | Select-Object -Unique
}
else
{
if($indices.Count -eq 0) { return $null }
return $Items[$indices[0]]
}
}
function Select-MenuItem
{
param(
[Parameter(Mandatory)]
[string[]]$Items,
[string]$Header = "Select one",
[switch]$Multi
)
if(Test-FzfAvailable)
{
return Show-FzfMenu -Items $Items -Header $Header -Multi:$Multi
}
return Show-NumberedMenu -Items $Items -Header $Header -Multi:$Multi
}
function Get-DefaultSettingsPath
{
if($IsWindows -or $env:OS -eq "Windows_NT")
{
if($env:LOCALAPPDATA) { return (Join-Path $env:LOCALAPPDATA "macOS_IntuneManagement\Settings.json") }
return (Join-Path $env:USERPROFILE "AppData\Local\macOS_IntuneManagement\Settings.json")
}
if($IsMacOS) { return (Join-Path $HOME "Library/Application Support/macOS_IntuneManagement/Settings.json") }
return (Join-Path $HOME ".local/share/macOS_IntuneManagement/Settings.json")
}
#endregion
#region Initialize Runtime
$projectRoot = Split-Path -Parent $PSScriptRoot
$runtimeModule = Join-Path $projectRoot "Runtime/IntuneManagement.Runtime.psd1"
if(-not (Test-Path $runtimeModule))
{
throw "Could not find IntuneManagement.Runtime.psd1 in $projectRoot"
}
$settingsPath = $SettingsFile
if(-not $settingsPath)
{
$settingsPath = Get-DefaultSettingsPath
}
# Pre-load auth from settings
if($AuthMode -eq "AppOnly" -and (Test-Path $settingsPath) -and (-not $AppId -or (-not $Secret -and -not $Certificate)))
{
try
{
$raw = Get-Content -Path $settingsPath -Raw -ErrorAction Stop
$settingsObj = ConvertFrom-Json $raw -AsHashtable -ErrorAction Stop
if($settingsObj -and $settingsObj.ContainsKey($TenantId))
{
$tenantNode = $settingsObj[$TenantId]
if(-not $AppId -and $tenantNode.ContainsKey("GraphAzureAppId"))
{
$AppId = $tenantNode["GraphAzureAppId"]
}
if(-not $Secret -and $tenantNode.ContainsKey("GraphAzureAppSecret"))
{
$Secret = $tenantNode["GraphAzureAppSecret"]
}
if(-not $Certificate -and $tenantNode.ContainsKey("GraphAzureAppCert"))
{
$Certificate = $tenantNode["GraphAzureAppCert"]
}
}
if(-not $Secret -and $IsMacOS -and $AppId)
{
try
{
$keychainSecret = security find-generic-password -a "IntuneManagement" -s "IntuneMgmt-$AppId" -w 2>$null
if($keychainSecret) { $Secret = $keychainSecret }
}
catch { }
}
}
catch { }
}
$invokeParams = @{
Silent = $true
JSonSettings = $true
JSonFile = $settingsPath
TenantId = $TenantId
AppId = $AppId
AuthMode = $AuthMode
}
if($RedirectUri) { $invokeParams.RedirectUri = $RedirectUri }
if($AuthMode -eq "AppOnly" -and $Secret) { $invokeParams.Secret = $Secret }
elseif($AuthMode -eq "AppOnly") { $invokeParams.Certificate = $Certificate }
Import-Module $runtimeModule -Force
Initialize-IntuneManagementRuntime -View "IntuneGraphAPI" @invokeParams
#endregion
#region Ensure Graph connectivity
if(-not (Get-Command Invoke-GraphRequest -ErrorAction SilentlyContinue))
{
throw "Graph runtime did not load Invoke-GraphRequest. Aborting."
}
Write-Host "`nConnecting to Microsoft Graph..." -ForegroundColor Cyan
try
{
$org = Invoke-GraphRequest "/organization"
Write-Host "Connected to tenant: $($org.value[0].displayName) ($($org.value[0].id))" -ForegroundColor Green
}
catch
{
throw "Failed to connect to Graph. Ensure auth parameters are correct. Error: $_"
}
#endregion
#region Object type registry (deletable types)
$deletableTypes = @(
[PSCustomObject]@{ Title = "Applications"; API = "/deviceAppManagement/mobileApps"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Device Configuration"; API = "/deviceManagement/deviceConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Settings Catalog"; API = "/deviceManagement/configurationPolicies"; NameProp = "name" },
[PSCustomObject]@{ Title = "Compliance Policies"; API = "/deviceManagement/deviceCompliancePolicies"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Administrative Templates"; API = "/deviceManagement/groupPolicyConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Endpoint Security"; API = "/deviceManagement/intents"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "App Protection"; API = "/deviceAppManagement/managedAppPolicies"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "App Configuration (Device)"; API = "/deviceAppManagement/mobileAppConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Platform Scripts"; API = "/deviceManagement/deviceManagementScripts"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "macOS Scripts"; API = "/deviceManagement/deviceShellScripts"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Device Health Scripts"; API = "/deviceManagement/deviceHealthScripts"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "macOS Custom Attributes"; API = "/deviceManagement/deviceCustomAttributeShellScripts"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Enrollment Restrictions"; API = "/deviceManagement/deviceEnrollmentConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Autopilot"; API = "/deviceManagement/windowsAutopilotDeploymentProfiles"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Terms and Conditions"; API = "/deviceManagement/termsAndConditions"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Policy Sets"; API = "/deviceAppManagement/policySets"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Update Policies"; API = "/deviceManagement/windowsUpdateForBusinessConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Feature Updates"; API = "/deviceManagement/windowsFeatureUpdateProfiles"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Quality Updates"; API = "/deviceManagement/windowsQualityUpdateProfiles"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Device Management Intents"; API = "/deviceManagement/intents"; NameProp = "displayName" }
)
#endregion
Clear-Host
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Intune Bulk Delete Tool" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
#region Select object type
$typeTitles = $deletableTypes | ForEach-Object { $_.Title }
$selectedTypeTitle = Select-MenuItem -Items $typeTitles -Header "Select object type"
if(-not $selectedTypeTitle) { Write-Host "Cancelled." -ForegroundColor Yellow; exit 0 }
$objectType = $deletableTypes | Where-Object { $_.Title -eq $selectedTypeTitle } | Select-Object -First 1
#endregion
#region Load objects
Write-Host "`nLoading $($objectType.Title) objects..." -ForegroundColor Cyan
$api = "$($objectType.API)?`$select=id,$($objectType.NameProp)&`$orderby=$($objectType.NameProp)"
$objectsResponse = Invoke-GraphRequest $api -AllPages
$objects = $objectsResponse.value | Where-Object { $_ } | Sort-Object $objectType.NameProp
Write-Host "Found $($objects.Count) objects." -ForegroundColor Green
$filter = Read-Host "`nFilter by current name (optional, press Enter to skip)"
if(-not [string]::IsNullOrWhiteSpace($filter))
{
$objects = $objects | Where-Object { $_."$($objectType.NameProp)" -like "*$filter*" }
Write-Host "Filtered to $($objects.Count) objects." -ForegroundColor Green
}
if($objects.Count -eq 0)
{
Write-Host "No objects found. Exiting." -ForegroundColor Yellow
exit 0
}
$objectDisplays = $objects | ForEach-Object { "$($_."$($objectType.NameProp)") [$($_.id)]" }
$selectedDisplays = Select-MenuItem -Items $objectDisplays -Header "Select objects to DELETE (multi-select)" -Multi
if(-not $selectedDisplays)
{
Write-Host "No objects selected. Exiting." -ForegroundColor Yellow
exit 0
}
$selectedObjects = @()
foreach($disp in $selectedDisplays)
{
$id = $disp -replace '.*\[(.*?)\]$', '$1'
$obj = $objects | Where-Object { $_.id -eq $id } | Select-Object -First 1
if($obj) { $selectedObjects += $obj }
}
#endregion
#region Confirm
Write-Host "`nThe following $($selectedObjects.Count) $($objectType.Title) object(s) will be PERMANENTLY DELETED:" -ForegroundColor Red
foreach($obj in $selectedObjects)
{
Write-Host " - $($obj."$($objectType.NameProp)") [$($obj.id)]" -ForegroundColor DarkGray
}
if(-not $WhatIf)
{
$typed = Read-Host "`nThis cannot be undone. Type DELETE to confirm"
if($typed -cne "DELETE")
{
Write-Host "Confirmation text did not match. Cancelled." -ForegroundColor Yellow
exit 0
}
}
#endregion
#region Execute
$success = 0
$failed = 0
foreach($obj in $selectedObjects)
{
$name = $obj."$($objectType.NameProp)"
try
{
if($WhatIf)
{
Write-Host " WHATIF: Would delete $name [$($obj.id)]" -ForegroundColor Magenta
$success++
}
else
{
$maxRetries = 3
$retryDelay = 2
$deleted = $false
for($r = 1; $r -le $maxRetries; $r++)
{
try
{
$null = Invoke-GraphRequest "$($objectType.API)/$($obj.id)" -HttpMethod DELETE
Write-Host " OK: Deleted '$name'" -ForegroundColor Green
$success++
$deleted = $true
break
}
catch
{
$statusCode = $_.Exception.Response.StatusCode
if($r -lt $maxRetries -and ($statusCode -ge 500 -or $statusCode -eq 429))
{
Write-Host " Retry $r/$maxRetries after $retryDelay`s (HTTP $statusCode)..." -ForegroundColor DarkYellow
Start-Sleep -Seconds $retryDelay
}
else
{
throw
}
}
}
if(-not $deleted) { throw "Delete failed after $maxRetries attempts." }
}
}
catch
{
Write-Host " ERROR: Failed to delete '$name'. $($_.Exception.Message)" -ForegroundColor Red
$failed++
}
}
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host " Bulk Delete Complete" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Success : $success"
Write-Host " Failed : $failed"
#endregion
+470
View File
@@ -0,0 +1,470 @@
#requires -Version 5.1
<#
.SYNOPSIS
Bulk add, replace or remove scope tags on Intune objects, or clean up orphaned tag references.
.DESCRIPTION
Pick an action, the scope tags and the object types (optionally filtered by name).
The script computes the new scope tag list per object, shows what would change and
applies it with PATCH requests (batched, 20 per call). Objects whose list would not
change are skipped. Supports -WhatIf.
Actions
Add add the selected tags to each object
Replace set each object's tags to exactly the selected tags
Remove remove the selected tags from each object
CleanupOrphans remove tag ids that no longer exist in the tenant (no tags needed)
-CleanupOrphans can also be combined with Add/Replace/Remove.
.EXAMPLE
./Scripts/Bulk-ScopeTags.ps1 -TenantId <id> -WhatIf
.EXAMPLE
./Scripts/Bulk-ScopeTags.ps1 -TenantId <id> -Action Add -ScopeTags "Helpdesk" -ObjectTypes "Settings Catalog","Compliance Policies" -NameFilter "Win - " -Force
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$TenantId,
[string]$AppId,
[string]$Secret,
[string]$Certificate,
[ValidateSet("AppOnly","Browser","DeviceCode")]
[string]$AuthMode = "AppOnly",
[string]$RedirectUri,
[string]$SettingsFile,
[ValidateSet("Add","Replace","Remove","CleanupOrphans")]
[string]$Action,
# Scope tag names or ids ("0" or "Default" for the default tag)
[string[]]$ScopeTags,
# Object type titles, e.g. "Settings Catalog". Default: ask (interactive) or all
[string[]]$ObjectTypes,
# Literal, case-insensitive substring of the object name
[string]$NameFilter,
# Also remove tag ids that no longer exist in the tenant
[switch]$CleanupOrphans,
# Skip the confirmation prompt
[switch]$Force,
[switch]$WhatIf
)
$ErrorActionPreference = "Stop"
#region Helper functions
function Test-FzfAvailable
{
return [bool](Get-Command fzf -ErrorAction SilentlyContinue)
}
function Show-FzfMenu
{
param(
[Parameter(Mandatory)]
[string[]]$Items,
[string]$Header = "Select one",
[switch]$Multi
)
$argsList = @("--header=$Header")
if($Multi) { $argsList += "--multi" }
$selected = $Items | fzf @argsList
if(-not $selected) { return $null }
if($Multi) { return @($selected -split "`r?`n" | Where-Object { $_ }) }
return $selected
}
function Show-NumberedMenu
{
param(
[Parameter(Mandatory)]
[string[]]$Items,
[string]$Header = "Select one or more",
[switch]$Multi
)
Write-Host "`n$Header" -ForegroundColor Cyan
for($i=0; $i -lt $Items.Count; $i++)
{
Write-Host " $($i+1). $($Items[$i])"
}
if($Multi)
{
$prompt = "Enter numbers separated by commas (e.g. 1,3,5) or 'all'"
}
else
{
$prompt = "Enter a number"
}
$choice = Read-Host $prompt
if($choice -eq "all" -and $Multi) { return $Items }
$indices = $choice -split "," | ForEach-Object { $_.Trim() } | Where-Object { $_ -match "^\d+$" } | ForEach-Object { [int]$_ - 1 } | Where-Object { $_ -ge 0 -and $_ -lt $Items.Count }
if($Multi)
{
return $Items[$indices] | Select-Object -Unique
}
else
{
if($indices.Count -eq 0) { return $null }
return $Items[$indices[0]]
}
}
function Select-MenuItem
{
param(
[Parameter(Mandatory)]
[string[]]$Items,
[string]$Header = "Select one",
[switch]$Multi
)
if(Test-FzfAvailable)
{
return Show-FzfMenu -Items $Items -Header $Header -Multi:$Multi
}
return Show-NumberedMenu -Items $Items -Header $Header -Multi:$Multi
}
function Get-DefaultSettingsPath
{
if($IsWindows -or $env:OS -eq "Windows_NT")
{
if($env:LOCALAPPDATA) { return (Join-Path $env:LOCALAPPDATA "macOS_IntuneManagement\Settings.json") }
return (Join-Path $env:USERPROFILE "AppData\Local\macOS_IntuneManagement\Settings.json")
}
if($IsMacOS) { return (Join-Path $HOME "Library/Application Support/macOS_IntuneManagement/Settings.json") }
return (Join-Path $HOME ".local/share/macOS_IntuneManagement/Settings.json")
}
#endregion
#region Initialize Runtime
$projectRoot = Split-Path -Parent $PSScriptRoot
$runtimeModule = Join-Path $projectRoot "Runtime/IntuneManagement.Runtime.psd1"
if(-not (Test-Path $runtimeModule))
{
throw "Could not find IntuneManagement.Runtime.psd1 in $projectRoot"
}
$settingsPath = $SettingsFile
if(-not $settingsPath)
{
$settingsPath = Get-DefaultSettingsPath
}
# Pre-load auth from settings
if($AuthMode -eq "AppOnly" -and (Test-Path $settingsPath) -and (-not $AppId -or (-not $Secret -and -not $Certificate)))
{
try
{
$raw = Get-Content -Path $settingsPath -Raw -ErrorAction Stop
$settingsObj = ConvertFrom-Json $raw -AsHashtable -ErrorAction Stop
if($settingsObj -and $settingsObj.ContainsKey($TenantId))
{
$tenantNode = $settingsObj[$TenantId]
if(-not $AppId -and $tenantNode.ContainsKey("GraphAzureAppId"))
{
$AppId = $tenantNode["GraphAzureAppId"]
}
if(-not $Secret -and $tenantNode.ContainsKey("GraphAzureAppSecret"))
{
$Secret = $tenantNode["GraphAzureAppSecret"]
}
if(-not $Certificate -and $tenantNode.ContainsKey("GraphAzureAppCert"))
{
$Certificate = $tenantNode["GraphAzureAppCert"]
}
}
if(-not $Secret -and $IsMacOS -and $AppId)
{
try
{
$keychainSecret = security find-generic-password -a "IntuneManagement" -s "IntuneMgmt-$AppId" -w 2>$null
if($keychainSecret) { $Secret = $keychainSecret }
}
catch { }
}
}
catch { }
}
$invokeParams = @{
Silent = $true
JSonSettings = $true
JSonFile = $settingsPath
TenantId = $TenantId
AppId = $AppId
AuthMode = $AuthMode
}
if($RedirectUri) { $invokeParams.RedirectUri = $RedirectUri }
if($AuthMode -eq "AppOnly" -and $Secret) { $invokeParams.Secret = $Secret }
elseif($AuthMode -eq "AppOnly") { $invokeParams.Certificate = $Certificate }
Import-Module $runtimeModule -Force
Initialize-IntuneManagementRuntime -View "IntuneGraphAPI" @invokeParams
#endregion
#region Ensure Graph connectivity
if(-not (Get-Command Invoke-GraphRequest -ErrorAction SilentlyContinue))
{
throw "Graph runtime did not load Invoke-GraphRequest. Aborting."
}
Write-Host "`nConnecting to Microsoft Graph..." -ForegroundColor Cyan
try
{
$org = Invoke-GraphRequest "/organization"
Write-Host "Connected to tenant: $($org.value[0].displayName) ($($org.value[0].id))" -ForegroundColor Green
}
catch
{
throw "Failed to connect to Graph. Ensure auth parameters are correct. Error: $_"
}
#endregion
#region Object types that support scope tags
# PATCH needs @odata.type for derived types; it is taken from the listed object.
$scopeTagTypes = @(
[PSCustomObject]@{ Title = "Applications"; API = "/deviceAppManagement/mobileApps"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Device Configuration"; API = "/deviceManagement/deviceConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Settings Catalog"; API = "/deviceManagement/configurationPolicies"; NameProp = "name" },
[PSCustomObject]@{ Title = "Compliance Policies"; API = "/deviceManagement/deviceCompliancePolicies"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Compliance Policies - V2"; API = "/deviceManagement/compliancePolicies"; NameProp = "name" },
[PSCustomObject]@{ Title = "Administrative Templates"; API = "/deviceManagement/groupPolicyConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Endpoint Security (Intents)"; API = "/deviceManagement/intents"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "App Configuration (Device)"; API = "/deviceAppManagement/mobileAppConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Platform Scripts"; API = "/deviceManagement/deviceManagementScripts"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "macOS Scripts"; API = "/deviceManagement/deviceShellScripts"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Device Health Scripts"; API = "/deviceManagement/deviceHealthScripts"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "macOS Custom Attributes"; API = "/deviceManagement/deviceCustomAttributeShellScripts"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Enrollment Configurations"; API = "/deviceManagement/deviceEnrollmentConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Autopilot"; API = "/deviceManagement/windowsAutopilotDeploymentProfiles"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Terms and Conditions"; API = "/deviceManagement/termsAndConditions"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Policy Sets"; API = "/deviceAppManagement/policySets"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Feature Updates"; API = "/deviceManagement/windowsFeatureUpdateProfiles"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Quality Updates (Profiles)"; API = "/deviceManagement/windowsQualityUpdateProfiles"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Driver Update Profiles"; API = "/deviceManagement/windowsDriverUpdateProfiles"; NameProp = "displayName" }
)
#endregion
#region Helpers
function Get-ScopeTagPlan
{
<# Returns the new tag id list for one object, or $null when nothing changes #>
param([string[]]$Current, [string]$Action, [string[]]$Selected, [string[]]$ValidIds, [bool]$Cleanup)
$new = [System.Collections.Generic.List[string]]::new()
switch($Action)
{
"Add" { $new.AddRange([string[]]@($Current + $Selected | Select-Object -Unique)) }
"Replace" { $new.AddRange([string[]]@($Selected | Select-Object -Unique)) }
"Remove" { $new.AddRange([string[]]@($Current | Where-Object { $_ -notin $Selected })) }
"CleanupOrphans" { $new.AddRange([string[]]@($Current)) }
}
if($Cleanup -or $Action -eq "CleanupOrphans")
{
$keep = @($new | Where-Object { $_ -in $ValidIds })
$new = [System.Collections.Generic.List[string]]::new()
if($keep.Count -gt 0) { $new.AddRange([string[]]$keep) }
}
# An object always needs at least the Default tag
if($new.Count -eq 0) { $new.Add("0") }
$same = ($new.Count -eq @($Current).Count) -and (@($new | Where-Object { $_ -notin $Current }).Count -eq 0)
if($same) { return $null }
return @($new)
}
# Self-check of the planning rules; runs on every start, costs nothing
$valid = @("0","a","b")
if((Get-ScopeTagPlan @("0") "Add" @("a") $valid $false) -join "," -ne "0,a") { throw "ScopeTag plan self-check failed: Add" }
if((Get-ScopeTagPlan @("0","a") "Remove" @("a") $valid $false) -join "," -ne "0") { throw "ScopeTag plan self-check failed: Remove" }
if((Get-ScopeTagPlan @("a") "Remove" @("a") $valid $false) -join "," -ne "0") { throw "ScopeTag plan self-check failed: Remove-last falls back to Default" }
if((Get-ScopeTagPlan @("0","x") "CleanupOrphans" @() $valid $false) -join "," -ne "0") { throw "ScopeTag plan self-check failed: Cleanup" }
if($null -ne (Get-ScopeTagPlan @("0","a") "Add" @("a") $valid $false)) { throw "ScopeTag plan self-check failed: no-op" }
#endregion
Clear-Host
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Intune Bulk Scope Tags" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
#region Scope tag catalog
$tagResponse = Invoke-GraphRequest "/deviceManagement/roleScopeTags" -AllPages
$tagCatalog = @([PSCustomObject]@{ id = "0"; displayName = "Default" }) + @($tagResponse.value | Where-Object { $_ -and "$($_.id)" -ne "0" } | ForEach-Object { [PSCustomObject]@{ id = "$($_.id)"; displayName = $_.displayName } })
$validTagIds = @($tagCatalog | ForEach-Object { $_.id })
#endregion
#region Action
if(-not $Action)
{
$Action = Select-MenuItem -Items @("Add","Replace","Remove","CleanupOrphans") -Header "Select action"
if(-not $Action) { Write-Host "Cancelled." -ForegroundColor Yellow; exit 0 }
}
#endregion
#region Scope tags
$selectedTagIds = @()
if($Action -ne "CleanupOrphans")
{
if($ScopeTags)
{
foreach($t in $ScopeTags)
{
$match = $tagCatalog | Where-Object { $_.id -eq $t -or $_.displayName -eq $t } | Select-Object -First 1
if(-not $match) { throw "Scope tag '$t' not found. Available: $(($tagCatalog | ForEach-Object { $_.displayName }) -join ', ')" }
$selectedTagIds += $match.id
}
}
else
{
$labels = $tagCatalog | ForEach-Object { "$($_.displayName) [$($_.id)]" }
$picked = Select-MenuItem -Items $labels -Header "Select scope tags (multi-select)" -Multi
if(-not $picked) { Write-Host "No scope tags selected. Exiting." -ForegroundColor Yellow; exit 0 }
$selectedTagIds = @($picked | ForEach-Object { $_ -replace '.*\[(.*?)\]$', '$1' })
}
}
#endregion
#region Object types
if($ObjectTypes)
{
$targetTypes = @($scopeTagTypes | Where-Object { $_.Title -in $ObjectTypes })
$unknown = @($ObjectTypes | Where-Object { $_ -notin $scopeTagTypes.Title })
if($unknown.Count -gt 0) { throw "Unknown object type(s): $($unknown -join ', '). Available: $(($scopeTagTypes.Title) -join ', ')" }
}
else
{
$picked = Select-MenuItem -Items (@("[All types]") + @($scopeTagTypes.Title)) -Header "Select object types (multi-select)" -Multi
if(-not $picked) { Write-Host "No object types selected. Exiting." -ForegroundColor Yellow; exit 0 }
$targetTypes = if($picked -contains "[All types]") { $scopeTagTypes } else { @($scopeTagTypes | Where-Object { $_.Title -in $picked }) }
}
if(-not $PSBoundParameters.ContainsKey("NameFilter") -and -not $ObjectTypes)
{
$NameFilter = Read-Host "`nFilter by name (literal text, Enter for all)"
}
#endregion
#region Plan
$plan = @()
foreach($type in $targetTypes)
{
Write-Host "Reading $($type.Title) ..." -ForegroundColor DarkGray
try
{
$resp = Invoke-GraphRequest "$($type.API)?`$select=id,$($type.NameProp),roleScopeTagIds" -AllPages
}
catch
{
Write-Host " Skipped $($type.Title): $($_.Exception.Message)" -ForegroundColor Yellow
continue
}
foreach($o in @($resp.value | Where-Object { $_ }))
{
$name = [string]$o."$($type.NameProp)"
if($NameFilter -and $name.IndexOf($NameFilter, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
if(-not ($o.PSObject.Properties | Where-Object Name -eq "roleScopeTagIds")) { continue }
$current = @($o.roleScopeTagIds | ForEach-Object { "$_" })
$newIds = Get-ScopeTagPlan -Current $current -Action $Action -Selected $selectedTagIds -ValidIds $validTagIds -Cleanup $CleanupOrphans.IsPresent
if($null -eq $newIds) { continue }
$plan += [PSCustomObject]@{ Type = $type; Id = $o.id; Name = $name; ODataType = $o.'@odata.type'; Old = $current; New = $newIds }
}
}
if($plan.Count -eq 0)
{
Write-Host "`nNothing to change." -ForegroundColor Green
exit 0
}
$tagName = @{}; foreach($t in $tagCatalog) { $tagName[$t.id] = $t.displayName }
function Format-Tags { param($ids) ($ids | ForEach-Object { if($tagName.ContainsKey($_)) { $tagName[$_] } else { "<missing $_>" } }) -join ", " }
Write-Host "`n$($plan.Count) object(s) will change ($Action):" -ForegroundColor Cyan
foreach($g in ($plan | Group-Object { $_.Type.Title }))
{
Write-Host " $($g.Name): $($g.Count)" -ForegroundColor White
foreach($p in ($g.Group | Select-Object -First 5))
{
Write-Host " $($p.Name): [$(Format-Tags $p.Old)] -> [$(Format-Tags $p.New)]" -ForegroundColor DarkGray
}
if($g.Count -gt 5) { Write-Host " ... $($g.Count - 5) more" -ForegroundColor DarkGray }
}
#endregion
if($WhatIf)
{
Write-Host "`nWHATIF: no changes made." -ForegroundColor Magenta
exit 0
}
if(-not $Force)
{
if((Read-Host "`nApply these changes? [y/N]") -notlike 'y*') { Write-Host "Cancelled." -ForegroundColor Yellow; exit 0 }
}
#region Apply
$updated = 0; $failed = 0
$canBatch = [bool](Get-Command Invoke-GraphBatchRequest -ErrorAction SilentlyContinue)
for($i = 0; $i -lt $plan.Count; $i += 20)
{
$chunk = @($plan[$i..([Math]::Min($i + 19, $plan.Count - 1))])
$requests = @(); $n = 1
foreach($p in $chunk)
{
$body = [ordered]@{ roleScopeTagIds = @($p.New) }
if($p.ODataType) { $body['@odata.type'] = $p.ODataType }
$requests += [PSCustomObject]@{
id = "$n"; method = "PATCH"; url = "$($p.Type.API)/$($p.Id)"
body = [PSCustomObject]$body
headers = @{ "Content-Type" = "application/json"; "If-Match" = "*" }
}
$n++
}
if($canBatch)
{
$results = @(Invoke-GraphBatchRequest $requests "BulkScopeTags" -IncludedFailed -SkipWarnings)
foreach($r in $results)
{
$p = $chunk[[int]$r.id - 1]
if([int]$r.status -ge 200 -and [int]$r.status -lt 300) { $updated++; Write-Host " OK: $($p.Name)" -ForegroundColor Green }
else
{
$failed++
$msg = if($r.body.error.message) { $r.body.error.message } else { "" }
Write-Host " ERROR: $($p.Name) - HTTP $($r.status) $msg" -ForegroundColor Red
}
}
$missing = $chunk.Count - $results.Count
if($missing -gt 0) { $failed += $missing; Write-Host " ERROR: $missing request(s) in this batch returned no response" -ForegroundColor Red }
}
else
{
foreach($rq in $requests)
{
$p = $chunk[[int]$rq.id - 1]
try
{
$null = Invoke-GraphRequest $rq.url -HttpMethod PATCH -Content ($rq.body | ConvertTo-Json -Depth 5)
$updated++; Write-Host " OK: $($p.Name)" -ForegroundColor Green
}
catch { $failed++; Write-Host " ERROR: $($p.Name) - $($_.Exception.Message)" -ForegroundColor Red }
}
}
}
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host " Bulk Scope Tags Complete" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Updated : $updated"
Write-Host " Failed : $failed"
#endregion
+337
View File
@@ -0,0 +1,337 @@
#!/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 resolve_root(root: Path) -> Path:
"""Accept either the export root or its parent (e.g. a dated folder holding a single 'Export' folder)."""
def has_categories(p: Path) -> bool:
return any(d.is_dir() and any(d.rglob("*.json")) for d in p.iterdir())
if not root.is_dir() or any(f.suffix == ".json" for f in root.glob("MigrationTable.json")) or \
any(d.name in LOOKUP_CATEGORIES or d.name == "SettingsCatalog" for d in root.iterdir() if d.is_dir()):
return root
inner = [d for d in root.iterdir() if d.is_dir() and has_categories(d)]
if len(inner) == 1:
print(f"Using {inner[0]} as export root")
return inner[0]
return root
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}")
args.root_a, args.root_b = resolve_root(args.root_a), resolve_root(args.root_b)
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()
+438
View File
@@ -0,0 +1,438 @@
#requires -Version 7.0
<#
.SYNOPSIS
Export all active and PIM-eligible memberships in Microsoft Entra directory
roles, including expansion of group-assigned roles to transitive group
members, and mark whether each role is privileged.
.DESCRIPTION
Uses Microsoft Graph PowerShell (Microsoft.Graph.Authentication) and the
beta roleManagement endpoints so the isPrivileged flag is available for
both built-in and custom roles. Follows this toolkit's standard
-AuthMode / -AppId / -Secret / -Certificate auth convention (see
Deploy-CISM365Baseline.ps1).
.REQUIREMENTS
Install-Module Microsoft.Graph.Authentication -Scope CurrentUser
Install-Module Microsoft.Graph.Identity.Governance -Scope CurrentUser
Install-Module Microsoft.Graph.DirectoryObjects -Scope CurrentUser
Install-Module Microsoft.Graph.Groups -Scope CurrentUser
.PERMISSIONS
Suggested Graph scopes / app roles:
RoleManagement.Read.Directory
Directory.Read.All
GroupMember.Read.All
.EXAMPLE
./Scripts/Export-EntraRoleMembership.ps1 -TenantId <tenant-id> -AuthMode Browser
.EXAMPLE
./Scripts/Export-EntraRoleMembership.ps1 -TenantId <tenant-id> -AuthMode AppOnly -AppId <app-id> -Secret <secret> -CsvPath ./reports/roles.csv
#>
[CmdletBinding()]
param(
[Parameter()]
[string]$TenantId,
[Parameter()]
[string]$AppId,
[Parameter()]
[string]$Secret,
[Parameter()]
[string]$Certificate,
[Parameter()]
[ValidateSet('AppOnly', 'Browser', 'DeviceCode')]
[string]$AuthMode = 'Browser',
[Parameter()]
[string]$SettingsFile,
[Parameter()]
[string]$CsvPath
)
$ErrorActionPreference = "Stop"
#region Helpers
function Get-ObjectType {
param([object]$Object)
if ($null -eq $Object.AdditionalProperties.'@odata.type') {
return $Object.GetType().Name
}
return ($Object.AdditionalProperties.'@odata.type' -replace '^#microsoft\.graph\.', '')
}
function Get-DisplayNameSafe {
param([object]$Object)
if ($Object.PSObject.Properties.Name -contains 'DisplayName' -and $Object.DisplayName) {
return $Object.DisplayName
}
if ($Object.AdditionalProperties -and $Object.AdditionalProperties.ContainsKey('displayName')) {
return $Object.AdditionalProperties['displayName']
}
return $null
}
function Get-UpnSafe {
param([object]$Object)
if ($Object.PSObject.Properties.Name -contains 'UserPrincipalName' -and $Object.UserPrincipalName) {
return $Object.UserPrincipalName
}
if ($Object.AdditionalProperties -and $Object.AdditionalProperties.ContainsKey('userPrincipalName')) {
return $Object.AdditionalProperties['userPrincipalName']
}
return $null
}
function Get-MailSafe {
param([object]$Object)
if ($Object.PSObject.Properties.Name -contains 'Mail' -and $Object.Mail) {
return $Object.Mail
}
if ($Object.AdditionalProperties -and $Object.AdditionalProperties.ContainsKey('mail')) {
return $Object.AdditionalProperties['mail']
}
return $null
}
function Invoke-GraphGetAllPages {
param(
[Parameter(Mandatory)]
[string]$Uri
)
$items = @()
$nextLink = $Uri
while ($nextLink) {
$response = Invoke-MgGraphRequest -Method GET -Uri $nextLink -OutputType PSObject
if ($response.value) {
$items += $response.value
}
else {
$items += $response
break
}
$nextLink = $response.'@odata.nextLink'
}
return $items
}
#endregion
#region Load saved AppId/Secret (same lookup as Invoke-IntuneHeadlessBatch)
if ($AuthMode -eq 'AppOnly' -and $TenantId -and (-not $AppId -or (-not $Secret -and -not $Certificate))) {
$coreModule = Join-Path (Split-Path -Parent $PSScriptRoot) "Core.psm1"
if (Test-Path $coreModule) {
Import-Module $coreModule -Force -Global
$settingsPath = if ($SettingsFile) { $SettingsFile } else { Join-Path (Get-CloudApiDataFolder) "Settings.json" }
if (Test-Path $settingsPath) {
try {
$raw = Get-Content -Path $settingsPath -Raw -ErrorAction Stop
$settingsObj = ConvertFrom-Json $raw -AsHashtable -ErrorAction Stop
if ($settingsObj -and $settingsObj.ContainsKey($TenantId)) {
$tenantNode = $settingsObj[$TenantId]
if (-not $AppId -and $tenantNode.ContainsKey("GraphAzureAppId")) {
$AppId = $tenantNode["GraphAzureAppId"]
}
if (-not $Secret -and $tenantNode.ContainsKey("GraphAzureAppSecret")) {
$Secret = $tenantNode["GraphAzureAppSecret"]
}
if (-not $Certificate -and $tenantNode.ContainsKey("GraphAzureAppCert")) {
$Certificate = $tenantNode["GraphAzureAppCert"]
}
}
if (-not $Secret -and $IsMacOS -and $AppId) {
try {
$keychainSecret = security find-generic-password -a "IntuneManagement" -s "IntuneMgmt-$AppId" -w 2>$null
if ($keychainSecret) { $Secret = $keychainSecret }
}
catch { }
}
}
catch { }
}
}
}
#endregion
#region Auth
$requiredModules = @(
"Microsoft.Graph.Authentication",
"Microsoft.Graph.Identity.Governance",
"Microsoft.Graph.DirectoryObjects",
"Microsoft.Graph.Groups"
)
foreach ($mod in $requiredModules) {
if (-not (Get-Module $mod -ListAvailable)) {
throw "Module '$mod' is not installed. Run: Install-Module $mod -Scope CurrentUser"
}
Import-Module $mod -Force
}
$GraphScopes = @("RoleManagement.Read.Directory", "Directory.Read.All", "GroupMember.Read.All")
Write-Host "Connecting to Microsoft Graph (mode: $AuthMode)..." -NoNewline
$connectParams = @{}
if ($TenantId) { $connectParams.TenantId = $TenantId }
switch ($AuthMode) {
'AppOnly' {
if (-not $AppId) { throw "AppId is required for AppOnly auth mode." }
if ($Secret) {
$secureSecret = ConvertTo-SecureString -String $Secret -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($AppId, $secureSecret)
$connectParams.ClientSecretCredential = $credential
}
elseif ($Certificate) {
$cert = Get-ChildItem Cert:\CurrentUser\My | Where-Object { $_.Thumbprint -eq $Certificate -or $_.Subject -eq $Certificate } | Select-Object -First 1
if (-not $cert) { throw "Certificate not found: $Certificate" }
$connectParams.ClientCertificateCredential = $cert
}
else {
throw "Secret or Certificate is required for AppOnly auth mode."
}
Connect-MgGraph @connectParams -NoWelcome
}
'DeviceCode' {
Connect-MgGraph -Scopes ($GraphScopes -join ',') @connectParams -UseDeviceCode -NoWelcome
}
default { # Browser / Interactive
Connect-MgGraph -Scopes ($GraphScopes -join ',') @connectParams -NoWelcome
}
}
$context = Get-MgContext
Write-Host " OK ($($context.Account))" -ForegroundColor Green
#endregion
Write-Host "Getting tenant information..." -ForegroundColor Cyan
$org = Invoke-GraphGetAllPages -Uri "https://graph.microsoft.com/v1.0/organization?`$select=displayName,id"
$tenantName = $org[0].displayName
$tenantId = $org[0].id
$invalidChars = [System.IO.Path]::GetInvalidFileNameChars() -join ''
$escaped = [regex]::Escape($invalidChars)
$safeTenantName = $tenantName -replace "[$escaped]", '_'
$defaultFileName = "$safeTenantName-Entra-AllRoleMemberships.csv"
if ([string]::IsNullOrWhiteSpace($CsvPath)) {
$CsvPath = ".\$defaultFileName"
}
elseif ((Test-Path -LiteralPath $CsvPath -PathType Container) -or ($CsvPath -match '[\\/]$')) {
$CsvPath = Join-Path $CsvPath $defaultFileName
}
$csvDir = Split-Path -Parent $CsvPath
if ($csvDir -and -not (Test-Path -LiteralPath $csvDir)) {
New-Item -ItemType Directory -Path $csvDir -Force | Out-Null
}
Write-Host "Tenant: $tenantName ($tenantId)" -ForegroundColor Cyan
Write-Host "Export path: $CsvPath" -ForegroundColor Cyan
Write-Host ""
Write-Host "Getting all role definitions from Graph beta endpoint..." -ForegroundColor Cyan
$roleDefsUri = "https://graph.microsoft.com/beta/roleManagement/directory/roleDefinitions"
$allRoles = Invoke-GraphGetAllPages -Uri $roleDefsUri
if (-not $allRoles) {
Write-Warning "No role definitions were returned."
return
}
Write-Host "Getting active role assignments from Graph beta endpoint..." -ForegroundColor Cyan
$assignmentsUri = "https://graph.microsoft.com/beta/roleManagement/directory/roleAssignments?`$expand=roleDefinition"
$assignments = Invoke-GraphGetAllPages -Uri $assignmentsUri
Write-Host "Getting PIM-eligible role assignments from Graph beta endpoint..." -ForegroundColor Cyan
$eligibilityUri = "https://graph.microsoft.com/beta/roleManagement/directory/roleEligibilitySchedules"
try {
$eligibleAssignments = Invoke-GraphGetAllPages -Uri $eligibilityUri
}
catch {
$errorText = "$($_.Exception.Message) $($_.ErrorDetails.Message)"
if ($errorText -match 'AadPremiumLicenseRequired') {
Write-Warning "PIM eligibility schedules require Entra ID P2 or Governance license. Skipping eligible assignments."
$eligibleAssignments = @()
}
elseif ($errorText -match 'PermissionScopeNotGranted|Authorization_RequestDenied|403') {
Write-Warning "Missing permission for PIM eligibility schedules (needs RoleManagement.Read.Directory app role granted to this app registration). Skipping eligible assignments."
$eligibleAssignments = @()
}
else {
throw
}
}
$activeWithState = foreach ($a in $assignments) { $a | Select-Object *, @{N = 'AssignmentState'; E = { 'Active' } } }
$eligibleWithState = foreach ($e in $eligibleAssignments) { $e | Select-Object *, @{N = 'AssignmentState'; E = { 'Eligible' } } }
$allAssignments = $activeWithState + $eligibleWithState
Write-Host "Discovered $($allRoles.Count) role definitions, $($assignments.Count) active assignments, and $($eligibleAssignments.Count) eligible assignments." -ForegroundColor DarkGray
$roleMap = @{}
$rolePrivilegedMap = @{}
foreach ($role in $allRoles) {
$roleMap[$role.id] = $role.displayName
$rolePrivilegedMap[$role.id] = [bool]$role.isPrivileged
}
$principalCache = @{}
$groupMemberCache = @{}
$results = New-Object System.Collections.Generic.List[object]
foreach ($assignment in $allAssignments) {
$roleId = $assignment.roleDefinitionId
$roleName = $roleMap[$roleId]
$isPrivileged = $rolePrivilegedMap[$roleId]
# Fallback to the inline expanded role definition if the role wasn't in the catalog
if (-not $roleName -and $assignment.roleDefinition) {
$roleName = $assignment.roleDefinition.displayName
$isPrivileged = [bool]$assignment.roleDefinition.isPrivileged
}
$principalId = $assignment.principalId
$directoryScopeId = $assignment.directoryScopeId
$assignmentState = $assignment.AssignmentState
# Skip assignments whose role definition could not be resolved
if (-not $roleName) {
Write-Warning "Skipping assignment for unknown role definition $roleId"
continue
}
if (-not $principalCache.ContainsKey($principalId)) {
try {
$principalCache[$principalId] = Get-MgDirectoryObjectById -Ids $principalId
}
catch {
Write-Warning "Failed to resolve principal $principalId"
continue
}
}
$principal = $principalCache[$principalId]
$principalType = Get-ObjectType -Object $principal
$principalName = Get-DisplayNameSafe -Object $principal
switch ($principalType.ToLower()) {
"group" {
if (-not $groupMemberCache.ContainsKey($principalId)) {
try {
$groupMemberCache[$principalId] = Get-MgGroupTransitiveMember -GroupId $principalId -All
}
catch {
Write-Warning "Failed to expand group members for group $principalName ($principalId)"
$groupMemberCache[$principalId] = @()
}
}
$members = $groupMemberCache[$principalId]
if (-not $members -or $members.Count -eq 0) {
$results.Add([pscustomobject]@{
IsPrivileged = $isPrivileged
AssignmentState = $assignmentState
RoleName = $roleName
RoleId = $roleId
AssignmentType = "GroupAssignment"
AssignmentPrincipalType = $principalType
AssignmentPrincipal = $principalName
AssignmentPrincipalId = $principalId
ExpandedMemberType = $null
ExpandedMemberName = $null
ExpandedMemberUPN = $null
ExpandedMemberMail = $null
ExpandedMemberId = $null
DirectoryScopeId = $directoryScopeId
Notes = "Group assigned, but no transitive members returned"
})
}
else {
foreach ($member in $members) {
$memberType = Get-ObjectType -Object $member
$memberName = Get-DisplayNameSafe -Object $member
$memberUpn = Get-UpnSafe -Object $member
$memberMail = Get-MailSafe -Object $member
$results.Add([pscustomobject]@{
IsPrivileged = $isPrivileged
AssignmentState = $assignmentState
RoleName = $roleName
RoleId = $roleId
AssignmentType = "GroupAssignmentExpanded"
AssignmentPrincipalType = $principalType
AssignmentPrincipal = $principalName
AssignmentPrincipalId = $principalId
ExpandedMemberType = $memberType
ExpandedMemberName = $memberName
ExpandedMemberUPN = $memberUpn
ExpandedMemberMail = $memberMail
ExpandedMemberId = $member.Id
DirectoryScopeId = $directoryScopeId
Notes = "Expanded from group assignment"
})
}
}
}
default {
$results.Add([pscustomobject]@{
IsPrivileged = $isPrivileged
AssignmentState = $assignmentState
RoleName = $roleName
RoleId = $roleId
AssignmentType = "DirectAssignment"
AssignmentPrincipalType = $principalType
AssignmentPrincipal = $principalName
AssignmentPrincipalId = $principalId
ExpandedMemberType = $principalType
ExpandedMemberName = $principalName
ExpandedMemberUPN = Get-UpnSafe -Object $principal
ExpandedMemberMail = Get-MailSafe -Object $principal
ExpandedMemberId = $principalId
DirectoryScopeId = $directoryScopeId
Notes = "Direct role assignment"
})
}
}
}
$results |
Sort-Object IsPrivileged, AssignmentState, RoleName, AssignmentType, ExpandedMemberName |
Export-Csv -Path $CsvPath -NoTypeInformation -Encoding UTF8
Write-Host ""
Write-Host "Exported $($results.Count) records to: $CsvPath" -ForegroundColor Green
Write-Host ""
$results |
Sort-Object IsPrivileged, AssignmentState, RoleName, ExpandedMemberName |
Format-Table IsPrivileged, AssignmentState, RoleName, AssignmentType, AssignmentPrincipal, ExpandedMemberName, ExpandedMemberUPN, ExpandedMemberType -AutoSize
Disconnect-MgGraph | Out-Null
+4 -1
View File
@@ -35,7 +35,10 @@ param(
[switch]$IncludeAssignments, [switch]$IncludeAssignments,
[switch]$AddCompanyName [switch]$AddCompanyName,
# Batch API is on by default; this falls back to one Graph call per object
[switch]$NoBatchApi
) )
$modulePath = Join-Path (Split-Path -Parent $PSScriptRoot) "Headless/IntuneManagement.Headless.psd1" $modulePath = Join-Path (Split-Path -Parent $PSScriptRoot) "Headless/IntuneManagement.Headless.psd1"
+409 -33
View File
@@ -1,11 +1,20 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Export a flat CSV of every Intune setting/value pair from a JSON backup. """Export a flat CSV of every Intune setting/value pair from a JSON backup.
Covers Settings Catalog policies (human-readable names resolved from Covers:
configurationSettings.json when present) and flat Device Configuration / - Settings Catalog + Compliance Policies V2 (settingInstance structure)
Compliance Policy objects. - Endpoint Security / Device Management Intents (companion _Settings.json,
old intent API with definitionId + value/valueJson)
- Administrative Templates (companion _Settings.json, definitionValues)
- Device Configuration + Compliance Policies V1 (flat, with OMA-URI expansion)
- Scripts: PowerShell, Shell, Custom Attributes, Health Scripts
(scriptContent / detectionScriptContent / remediationScriptContent decoded from base64)
- App Protection, App Configuration App/Device (flat + customSettings expansion)
- Update, Enrollment, Autopilot, W365, Filters, and other flat types
Output columns: Policy, Setting, Value Human-readable setting names resolved from configurationSettings.json when present.
Output columns: Policy, Platform, Setting, Value
With --include-assignments: adds AssignmentState, IncludeTargets, ExcludeTargets With --include-assignments: adds AssignmentState, IncludeTargets, ExcludeTargets
Group names resolved from MigrationTable.json (created by IntuneManagement export). Group names resolved from MigrationTable.json (created by IntuneManagement export).
""" """
@@ -13,6 +22,7 @@ With --include-assignments: adds AssignmentState, IncludeTargets, ExcludeTargets
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import base64
import csv import csv
import json import json
import re import re
@@ -20,10 +30,21 @@ from pathlib import Path
from typing import Any, Optional from typing import Any, Optional
OUTPUT_FILE = "settings-report.csv" OUTPUT_FILE = "settings-report.csv"
BASE_FIELDNAMES = ["Policy", "Platform", "Setting", "Value"]
BASE_FIELDNAMES = ["Policy", "Setting", "Value"]
ASSIGNMENT_FIELDNAMES = ["AssignmentState", "IncludeTargets", "ExcludeTargets"] ASSIGNMENT_FIELDNAMES = ["AssignmentState", "IncludeTargets", "ExcludeTargets"]
_PLATFORM_LABELS = {
"windows10": "Windows 10/11",
"windows10X": "Windows 10X",
"windows": "Windows",
"macOS": "macOS",
"iOS": "iOS",
"android": "Android",
"androidEnterprise": "Android Enterprise",
"linux": "Linux",
"chromeOS": "Chrome OS",
}
_SKIP_KEYS = { _SKIP_KEYS = {
"@odata.type", "id", "createdDateTime", "lastModifiedDateTime", "version", "@odata.type", "id", "createdDateTime", "lastModifiedDateTime", "version",
"displayName", "description", "roleScopeTagIds", "scheduledActionsForRule", "displayName", "description", "roleScopeTagIds", "scheduledActionsForRule",
@@ -32,8 +53,23 @@ _SKIP_KEYS = {
"deviceManagementApplicabilityRuleOsVersion", "deviceManagementApplicabilityRuleDeviceMode", "deviceManagementApplicabilityRuleOsVersion", "deviceManagementApplicabilityRuleDeviceMode",
"supportsScopeTags", "settingCount", "priorityMetaData", "creationSource", "supportsScopeTags", "settingCount", "priorityMetaData", "creationSource",
"templateReference", "name", "platforms", "technologies", "templateReference", "name", "platforms", "technologies",
# settings arrays are handled by dedicated processors; avoid JSON blobs in flat categories
"settings",
} }
# Expanded by dedicated helpers; excluded from generic flat key loop
_SPECIAL_KEYS = {"omaSettings", "customSettings"}
# Keys with base64-encoded text content
_B64_TEXT_KEYS = {"scriptContent", "detectionScriptContent", "remediationScriptContent", "payloadJson"}
_SCRIPT_PREVIEW_CHARS = 300
# ---------------------------------------------------------------------------
# Args
# ---------------------------------------------------------------------------
def parse_args() -> argparse.Namespace: def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__) p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--root", required=True, p.add_argument("--root", required=True,
@@ -83,12 +119,50 @@ def _choice_label(catalog: dict[str, Any], setting_id: str, value_id: str) -> st
return suffix.title() if suffix.islower() else suffix or value_id return suffix.title() if suffix.islower() else suffix or value_id
def _normalize_platforms(value: Any) -> str:
if value is None or value == "":
return ""
if isinstance(value, str):
items = [v.strip() for v in value.split(",")]
elif isinstance(value, list):
items = [str(v).strip() for v in value]
else:
items = [str(value).strip()]
labels = [_PLATFORM_LABELS.get(item, item) for item in items if item]
return "; ".join(labels)
def _platform_from_odata(odata_type: str) -> str:
lower = odata_type.lower()
if "macos" in lower:
return "macOS"
if "ios" in lower:
return "iOS"
if "android" in lower:
return "Android"
if "windows" in lower:
return "Windows"
if "linux" in lower:
return "Linux"
return ""
def _extract_platform(policy: dict, category: str = "") -> str:
platforms = policy.get("platforms")
if platforms:
return _normalize_platforms(platforms)
for key in ("platform", "platformType"):
val = policy.get(key)
if val:
return _normalize_platforms(val)
return _platform_from_odata(policy.get("@odata.type", ""))
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Assignment resolution # Assignment resolution
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def _load_groups(root: Path) -> dict[str, str]: def _load_groups(root: Path) -> dict[str, str]:
"""Return groupId → displayName from MigrationTable.json (created by IntuneManagement export)."""
path = root / "MigrationTable.json" path = root / "MigrationTable.json"
if not path.is_file(): if not path.is_file():
return {} return {}
@@ -104,7 +178,6 @@ def _load_groups(root: Path) -> dict[str, str]:
def _resolve_target(target: dict, groups: dict[str, str]) -> tuple[str, str]: def _resolve_target(target: dict, groups: dict[str, str]) -> tuple[str, str]:
"""Returns (intent, display_name)."""
ttype = target.get("@odata.type", "") ttype = target.get("@odata.type", "")
if ttype == "#microsoft.graph.allDevicesAssignmentTarget": if ttype == "#microsoft.graph.allDevicesAssignmentTarget":
return "include", "All devices" return "include", "All devices"
@@ -151,7 +224,7 @@ def _summarize_assignments(policy: dict, groups: dict[str, str]) -> dict[str, st
# Settings Catalog recursive walker # Settings Catalog recursive walker
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def _walk(si: dict, catalog: dict[str, Any], policy: str, def _walk(si: dict, catalog: dict[str, Any], policy: str, platform: str,
parent: str = "") -> list[dict]: parent: str = "") -> list[dict]:
rows: list[dict] = [] rows: list[dict] = []
otype = si.get("@odata.type", "") otype = si.get("@odata.type", "")
@@ -161,18 +234,19 @@ def _walk(si: dict, catalog: dict[str, Any], policy: str,
name = f"{parent} > {name}" name = f"{parent} > {name}"
children: list[dict] = [] children: list[dict] = []
base_row = {"Policy": policy, "Platform": platform}
if "ChoiceSettingInstance" in otype and "Collection" not in otype: if "ChoiceSettingInstance" in otype and "Collection" not in otype:
csv_val = si.get("choiceSettingValue", {}) csv_val = si.get("choiceSettingValue", {})
value = _choice_label(catalog, sid, csv_val.get("value", "")) value = _choice_label(catalog, sid, csv_val.get("value", ""))
rows.append({"Policy": policy, "Setting": name, "Value": value}) rows.append({**base_row, "Setting": name, "Value": value})
children = csv_val.get("children", []) children = csv_val.get("children", [])
elif "SimpleSettingInstance" in otype and "Collection" not in otype: elif "SimpleSettingInstance" in otype and "Collection" not in otype:
raw = si.get("simpleSettingValue", {}) raw = si.get("simpleSettingValue", {})
value = str(raw.get("value", "")) if isinstance(raw, dict) else str(raw) value = str(raw.get("value", "")) if isinstance(raw, dict) else str(raw)
if value: if value:
rows.append({"Policy": policy, "Setting": name, "Value": value}) rows.append({**base_row, "Setting": name, "Value": value})
elif "SimpleSettingCollectionInstance" in otype: elif "SimpleSettingCollectionInstance" in otype:
vals = [ vals = [
@@ -180,14 +254,14 @@ def _walk(si: dict, catalog: dict[str, Any], policy: str,
for v in si.get("simpleSettingCollectionValue", []) for v in si.get("simpleSettingCollectionValue", [])
] ]
if vals: if vals:
rows.append({"Policy": policy, "Setting": name, "Value": "; ".join(vals)}) rows.append({**base_row, "Setting": name, "Value": "; ".join(vals)})
elif "ChoiceSettingCollectionInstance" in otype: elif "ChoiceSettingCollectionInstance" in otype:
items = si.get("choiceSettingCollectionValue", []) items = si.get("choiceSettingCollectionValue", [])
vals = [_choice_label(catalog, sid, item.get("value", "")) vals = [_choice_label(catalog, sid, item.get("value", ""))
for item in items if isinstance(item, dict)] for item in items if isinstance(item, dict)]
if vals: if vals:
rows.append({"Policy": policy, "Setting": name, "Value": "; ".join(vals)}) rows.append({**base_row, "Setting": name, "Value": "; ".join(vals)})
elif "GroupSettingCollectionInstance" in otype: elif "GroupSettingCollectionInstance" in otype:
for group in si.get("groupSettingCollectionValue", []): for group in si.get("groupSettingCollectionValue", []):
@@ -195,13 +269,106 @@ def _walk(si: dict, catalog: dict[str, Any], policy: str,
for child in children: for child in children:
if isinstance(child, dict): if isinstance(child, dict):
rows.extend(_walk(child, catalog, policy, parent=name)) rows.extend(_walk(child, catalog, policy, platform, parent=name))
return rows return rows
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Processors # Intent settings walker (Endpoint Security / Device Management Intents)
# Old-style API: /deviceManagement/intents/{id}/settings
# Each item has definitionId + value/valueJson instead of settingInstance
# ---------------------------------------------------------------------------
def _intent_def_name(definition_id: str) -> str:
"""Human name from intent definitionId like 'category--type_settingName'."""
tail = definition_id.rsplit("_", 1)[-1]
return re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", " ", tail).title()
def _walk_intent(si: dict, policy: str, platform: str, parent: str = "") -> list[dict]:
rows: list[dict] = []
defid = si.get("definitionId", "")
name = _intent_def_name(defid)
if parent:
name = f"{parent} > {name}"
base = {"Policy": policy, "Platform": platform}
value = si.get("value")
value_json = si.get("valueJson", "")
def _emit(v: Any) -> None:
if isinstance(v, list):
dict_children = [c for c in v if isinstance(c, dict)]
primitives = [c for c in v if not isinstance(c, dict)]
for child in dict_children:
rows.extend(_walk_intent(child, policy, platform, parent=name))
if primitives:
rows.append({**base, "Setting": name,
"Value": "; ".join(str(x) for x in primitives)})
elif v is not None:
rows.append({**base, "Setting": name, "Value": str(v)})
if value is not None:
_emit(value)
elif value_json and value_json != "null":
try:
_emit(json.loads(value_json))
except json.JSONDecodeError:
rows.append({**base, "Setting": name, "Value": value_json})
return rows
# ---------------------------------------------------------------------------
# OMA-URI and customSettings helpers
# ---------------------------------------------------------------------------
def _expand_oma_settings(oma_list: list, base_row: dict) -> list[dict]:
rows = []
for oma in oma_list:
if not isinstance(oma, dict):
continue
uri = oma.get("omaUri", "")
display = oma.get("displayName", "")
setting_name = f"{uri} ({display})" if display else uri
raw = oma.get("value")
if raw is None:
raw = oma.get("secretReferenceValueId", "")
if isinstance(raw, (bool, int, float)):
value_str = str(raw)
elif isinstance(raw, str):
value_str = raw
else:
value_str = json.dumps(raw, ensure_ascii=False) if raw is not None else ""
rows.append({**base_row, "Setting": setting_name, "Value": value_str})
return rows
def _expand_custom_settings(cs_list: list, base_row: dict) -> list[dict]:
rows = []
for cs in cs_list:
if not isinstance(cs, dict):
continue
sname = cs.get("name") or cs.get("key") or ""
value = str(cs.get("value") or "")
if sname:
rows.append({**base_row, "Setting": f"customSettings/{sname}", "Value": value})
return rows
def _decode_b64_text(b64_str: str) -> str:
try:
text = base64.b64decode(b64_str).decode("utf-8", errors="replace").strip()
if len(text) > _SCRIPT_PREVIEW_CHARS:
return text[:_SCRIPT_PREVIEW_CHARS] + f"… [{len(text)} chars]"
return text
except Exception:
return f"[base64 {len(b64_str)} chars]"
# ---------------------------------------------------------------------------
# Folder resolution
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def _resolve_folder(root: Path, *candidates: str) -> Optional[Path]: def _resolve_folder(root: Path, *candidates: str) -> Optional[Path]:
@@ -212,23 +379,151 @@ def _resolve_folder(root: Path, *candidates: str) -> Optional[Path]:
return None return None
# ---------------------------------------------------------------------------
# Processors
# ---------------------------------------------------------------------------
def process_settings_catalog(root: Path, catalog: dict[str, Any], def process_settings_catalog(root: Path, catalog: dict[str, Any],
groups: dict[str, str], groups: dict[str, str],
include_assignments: bool) -> list[dict]: include_assignments: bool) -> list[dict]:
folder = _resolve_folder(root, "SettingsCatalog", "Settings Catalog") """Settings Catalog + Compliance Policies V2 — both use settings[].settingInstance."""
folder_groups = [
("SettingsCatalog", "Settings Catalog"),
("CompliancePoliciesV2", "Compliance Policies - V2"),
]
rows: list[dict] = []
seen: set[Path] = set()
for candidates in folder_groups:
folder = _resolve_folder(root, *candidates)
if folder is None or folder in seen:
continue
seen.add(folder)
for path in sorted(folder.glob("*.json")):
if path.stem.endswith("_Settings"):
continue
with path.open(encoding="utf-8") as f:
policy = json.load(f)
policy_name = policy.get("name") or policy.get("displayName") or path.stem
platform = _extract_platform(policy)
assignment_cols = _summarize_assignments(policy, groups) if include_assignments else {}
for setting in policy.get("settings", []):
si = setting.get("settingInstance", {})
for row in _walk(si, catalog, policy_name, platform):
row.update(assignment_cols)
rows.append(row)
return rows
def process_intent_settings(root: Path, groups: dict[str, str],
include_assignments: bool) -> list[dict]:
"""Endpoint Security + Device Management Intents.
IntuneManagement exports policy metadata to <Name>.json and settings to
<Name>_Settings.json via the /deviceManagement/intents/{id}/settings endpoint.
Settings use the old intent format: definitionId + value/valueJson.
"""
folder_groups = [
("EndpointSecurity", "Endpoint Security"),
("DeviceManagementIntents", "Device Management Intents"),
]
rows: list[dict] = []
seen: set[Path] = set()
for candidates in folder_groups:
folder = _resolve_folder(root, *candidates)
if folder is None or folder in seen:
continue
seen.add(folder)
for path in sorted(folder.glob("*.json")):
if path.stem.endswith("_Settings"):
continue
with path.open(encoding="utf-8") as f:
policy_obj = json.load(f)
if not isinstance(policy_obj, dict):
continue
policy_name = policy_obj.get("displayName") or policy_obj.get("name") or path.stem
platform = _extract_platform(policy_obj)
assignment_cols = _summarize_assignments(policy_obj, groups) if include_assignments else {}
settings_path = path.parent / f"{path.stem}_Settings.json"
settings_list: list = []
if settings_path.is_file():
with settings_path.open(encoding="utf-8") as f:
sd = json.load(f)
settings_list = sd.get("settings", sd) if isinstance(sd, dict) else sd
for si in settings_list:
if isinstance(si, dict):
for row in _walk_intent(si, policy_name, platform):
row.update(assignment_cols)
rows.append(row)
return rows
def process_admx(root: Path, groups: dict[str, str],
include_assignments: bool) -> list[dict]:
"""Administrative Templates — definitionValues in companion _Settings.json.
IntuneManagement removes definitionValues from the main export file
(PropertiesToRemove) and saves them separately via Start-PostExportAdministrativeTemplate.
Each definitionValue has definition.displayName/categoryPath and presentationValues.
"""
folder = _resolve_folder(root, "AdministrativeTemplates", "Administrative Templates")
rows: list[dict] = [] rows: list[dict] = []
if folder is None: if folder is None:
return rows return rows
for path in sorted(folder.glob("*.json")): for path in sorted(folder.glob("*.json")):
if path.stem.endswith("_Settings"):
continue
with path.open(encoding="utf-8") as f: with path.open(encoding="utf-8") as f:
policy = json.load(f) policy_obj = json.load(f)
policy_name = policy.get("name") or path.stem if not isinstance(policy_obj, dict):
assignment_cols = _summarize_assignments(policy, groups) if include_assignments else {} continue
for setting in policy.get("settings", []): policy_name = policy_obj.get("displayName") or policy_obj.get("name") or path.stem
si = setting.get("settingInstance", {}) assignment_cols = _summarize_assignments(policy_obj, groups) if include_assignments else {}
for row in _walk(si, catalog, policy_name):
row.update(assignment_cols) def_values: list = policy_obj.get("definitionValues", [])
rows.append(row) if not def_values:
settings_path = path.parent / f"{path.stem}_Settings.json"
if settings_path.is_file():
with settings_path.open(encoding="utf-8") as f:
sd = json.load(f)
def_values = (sd.get("definitionValues", sd)
if isinstance(sd, dict) else sd)
for dv in def_values:
if not isinstance(dv, dict):
continue
defn = dv.get("definition") or {}
raw_name = defn.get("displayName") or defn.get("id", "")
cat = defn.get("categoryPath", "").strip("\\").replace("\\", " > ")
setting_name = f"{cat} > {raw_name}" if cat else raw_name
enabled = dv.get("enabled", True)
pres_values = dv.get("presentationValues", [])
if not enabled:
value_str = "Disabled"
elif not pres_values:
value_str = "Enabled"
else:
parts = []
for pv in pres_values:
if not isinstance(pv, dict):
continue
label = (pv.get("presentation") or {}).get("label") or ""
val = pv.get("value")
if isinstance(val, list):
val = "; ".join(str(v) for v in val)
else:
val = str(val) if val is not None else ""
parts.append(f"{label}: {val}" if label else val)
value_str = " | ".join(parts) if parts else "Enabled"
row = {"Policy": policy_name, "Platform": "Windows",
"Setting": setting_name, "Value": value_str}
row.update(assignment_cols)
rows.append(row)
return rows return rows
@@ -243,22 +538,44 @@ def process_flat_category(root: Path, category: str,
folder = folder / "Policies" folder = folder / "Policies"
rows: list[dict] = [] rows: list[dict] = []
for path in sorted(folder.glob("*.json")): for path in sorted(folder.glob("*.json")):
if path.stem.endswith("_Settings"):
continue
with path.open(encoding="utf-8") as f: with path.open(encoding="utf-8") as f:
policy = json.load(f) policy = json.load(f)
if not isinstance(policy, dict): if not isinstance(policy, dict):
continue continue
policy_name = policy.get("displayName") or policy.get("name") or path.stem policy_name = policy.get("displayName") or policy.get("name") or path.stem
platform = _extract_platform(policy, category)
assignment_cols = _summarize_assignments(policy, groups) if include_assignments else {} assignment_cols = _summarize_assignments(policy, groups) if include_assignments else {}
base_row = {"Policy": policy_name, "Platform": platform}
# OMA-URI settings (Device Configuration custom profiles)
if isinstance(policy.get("omaSettings"), list):
for row in _expand_oma_settings(policy["omaSettings"], base_row):
row.update(assignment_cols)
rows.append(row)
# customSettings (App Configuration App, App Protection custom settings)
if isinstance(policy.get("customSettings"), list):
for row in _expand_custom_settings(policy["customSettings"], base_row):
row.update(assignment_cols)
rows.append(row)
for key, value in policy.items(): for key, value in policy.items():
if key in _SKIP_KEYS or value is None: if key in _SKIP_KEYS or key in _SPECIAL_KEYS or value is None:
continue continue
if isinstance(value, (dict, list)): if key in _B64_TEXT_KEYS:
if isinstance(value, str) and value:
value_str = _decode_b64_text(value)
else:
continue
elif isinstance(value, (dict, list)):
value_str = json.dumps(value, ensure_ascii=False) value_str = json.dumps(value, ensure_ascii=False)
if len(value_str) > 500: if len(value_str) > 500:
value_str = value_str[:497] + "..." value_str = value_str[:497] + "..."
else: else:
value_str = str(value) value_str = str(value)
row = {"Policy": policy_name, "Setting": key, "Value": value_str} row = {**base_row, "Setting": key, "Value": value_str}
row.update(assignment_cols) row.update(assignment_cols)
rows.append(row) rows.append(row)
return rows return rows
@@ -281,17 +598,76 @@ def main() -> None:
groups = _load_groups(root) if include_assignments else {} groups = _load_groups(root) if include_assignments else {}
rows: list[dict] = [] rows: list[dict] = []
# --- Dedicated structured processors ---
# Settings Catalog + Compliance Policies V2 (settingInstance)
rows.extend(process_settings_catalog(root, catalog, groups, include_assignments)) rows.extend(process_settings_catalog(root, catalog, groups, include_assignments))
# Endpoint Security + Device Management Intents (companion _Settings.json, intent format)
rows.extend(process_intent_settings(root, groups, include_assignments))
# Administrative Templates (companion _Settings.json, definitionValues)
rows.extend(process_admx(root, groups, include_assignments))
# --- Flat processors ---
# Device Configuration (flat + OMA-URI expansion for custom profiles)
rows.extend(process_flat_category(root, "DeviceConfiguration", groups, include_assignments, rows.extend(process_flat_category(root, "DeviceConfiguration", groups, include_assignments,
"Device Configuration", "Device Configurations")) "Device Configuration", "Device Configurations"))
# Compliance Policies V1
rows.extend(process_flat_category(root, "CompliancePolicies", groups, include_assignments, rows.extend(process_flat_category(root, "CompliancePolicies", groups, include_assignments,
"Compliance Policies")) "Compliance Policies"))
rows.extend(process_flat_category(root, "CompliancePoliciesV2", groups, include_assignments,
"Compliance Policies - V2")) # Scripts (scriptContent decoded from base64)
rows.extend(process_flat_category(root, "EndpointSecurity", groups, include_assignments, rows.extend(process_flat_category(root, "PowerShellScripts", groups, include_assignments,
"Endpoint Security")) "Scripts (PowerShell)"))
rows.extend(process_flat_category(root, "AdministrativeTemplates", groups, include_assignments, rows.extend(process_flat_category(root, "MacScripts", groups, include_assignments,
"Administrative Templates")) "Scripts (Shell)"))
rows.extend(process_flat_category(root, "MacCustomAttributes", groups, include_assignments,
"Custom Attributes"))
rows.extend(process_flat_category(root, "ComplianceScripts", groups, include_assignments,
"Compliance Scripts"))
rows.extend(process_flat_category(root, "DeviceHealthScripts", groups, include_assignments,
"Health Scripts"))
# App (customSettings expanded; payloadJson decoded)
rows.extend(process_flat_category(root, "AppProtection", groups, include_assignments,
"App Protection"))
rows.extend(process_flat_category(root, "AppConfigurationManagedApp", groups, include_assignments,
"App Configuration (App)"))
rows.extend(process_flat_category(root, "AppConfigurationManagedDevice", groups, include_assignments,
"App Configuration (Device)"))
# Enrollment
rows.extend(process_flat_category(root, "EnrollmentRestrictions", groups, include_assignments,
"Enrollment Restrictions"))
rows.extend(process_flat_category(root, "EnrollmentStatusPage", groups, include_assignments,
"Enrollment Status Page"))
rows.extend(process_flat_category(root, "AutoPilot", groups, include_assignments,
"Autopilot"))
# Updates
rows.extend(process_flat_category(root, "UpdatePolicies", groups, include_assignments,
"Update Policies"))
rows.extend(process_flat_category(root, "FeatureUpdates", groups, include_assignments,
"Feature Updates"))
rows.extend(process_flat_category(root, "WinFeatureUpdates", groups, include_assignments))
rows.extend(process_flat_category(root, "QualityUpdates", groups, include_assignments,
"Quality Updates"))
rows.extend(process_flat_category(root, "WinQualityUpdates", groups, include_assignments))
rows.extend(process_flat_category(root, "DriverUpdateProfiles", groups, include_assignments,
"Driver Update Profiles"))
rows.extend(process_flat_category(root, "WinDriverUpdatePolicies", groups, include_assignments))
# W365
rows.extend(process_flat_category(root, "W365ProvisioningPolicies", groups, include_assignments,
"W365 Provisioning Policies"))
rows.extend(process_flat_category(root, "W365UserSettings", groups, include_assignments,
"W365 User Settings"))
# Misc
rows.extend(process_flat_category(root, "AssignmentFilters", groups, include_assignments,
"Filters", "Assignment Filters"))
rows.extend(process_flat_category(root, "TermsAndConditions", groups, include_assignments,
"Terms and Conditions"))
rows.extend(process_flat_category(root, "Notifications", groups, include_assignments))
for row in rows: for row in rows:
for col in fieldnames: for col in fieldnames:
@@ -0,0 +1,728 @@
<#PSScriptInfo
.VERSION 1.9.0
.GUID 6c861af7-d12e-4ea2-b5dc-56fee16e0107
.AUTHOR Nicola Suter
.TAGS ConditionalAccess, AzureAD, Identity
.PROJECTURI https://git.cqre.net/vibecoding/CAExporter
.ICONURI https://raw.githubusercontent.com/microsoftgraph/g-raph/master/g-raph.png
.DESCRIPTION This script documents Azure AD Conditional Access Policies using the latest Microsoft.Graph PowerShell module.
.SYNOPSIS This script retrieves all Conditional Access Policies and translates Azure AD Object IDs to display names for users, groups, directory roles, locations...
.EXAMPLE
Connect-MgGraph -Scopes "Application.Read.All", "Group.Read.All", "Policy.Read.All", "RoleManagement.Read.Directory", "User.Read.All"
& .\Invoke-ConditionalAccessDocumentation.ps1
Generates the documentation and exports the csv to the script directory.
.NOTES
Author: Nicola Suter
Creation Date: 31.01.2022
Updated: 15.09.2025
#>
param(
[switch]$ExportExcel,
[string]$ExcelPath
)
# NOTE: Module requirements are handled programmatically below to allow auto-install.
$RequiredGraphVersion = '2.30.0'
$RequiredGraphModules = @(
'Microsoft.Graph.Authentication',
'Microsoft.Graph.Applications',
'Microsoft.Graph.Identity.SignIns',
'Microsoft.Graph.Groups',
'Microsoft.Graph.DirectoryObjects',
'Microsoft.Graph.Identity.DirectoryManagement',
'Microsoft.Graph.Identity.Governance'
)
function Ensure-NuGetProvider {
try {
if (-not (Get-PackageProvider -ListAvailable -Name 'NuGet' -ErrorAction SilentlyContinue)) {
Install-PackageProvider -Name 'NuGet' -Force -Scope CurrentUser | Out-Null
}
} catch { Write-Warning "NuGet provider installation failed: $($_.Exception.Message)" }
}
function Ensure-PSGalleryTrusted {
try {
$repo = Get-PSRepository -Name 'PSGallery' -ErrorAction Stop
if ($repo.InstallationPolicy -ne 'Trusted') {
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted -ErrorAction Stop
}
} catch { Write-Warning "Failed to set PSGallery trusted: $($_.Exception.Message)" }
}
function Ensure-Module {
param(
[Parameter(Mandatory)] [string] $Name,
[Parameter(Mandatory)] [string] $Version
)
$hasVersion = Get-Module -ListAvailable -Name $Name -ErrorAction SilentlyContinue |
Where-Object { $_.Version -eq [version]$Version }
if (-not $hasVersion) {
Write-Verbose "Installing $Name $Version for current user..."
Ensure-NuGetProvider
Ensure-PSGalleryTrusted
try {
Install-Module -Name $Name -RequiredVersion $Version -Scope CurrentUser -Force -ErrorAction Stop
} catch {
Write-Warning "Exact version $Version not available for $Name. Installing latest available version."
Install-Module -Name $Name -Scope CurrentUser -Force -ErrorAction Stop
}
}
Import-Module -Name $Name -ErrorAction Stop | Out-Null
}
foreach ($m in $RequiredGraphModules) { Ensure-Module -Name $m -Version $RequiredGraphVersion }
# If Excel export requested, ensure ImportExcel module is loaded/installed
if ($ExportExcel) {
try {
Import-Module ImportExcel -ErrorAction Stop | Out-Null
} catch {
Write-Host 'Installing ImportExcel module for Excel export...' -ForegroundColor Cyan
Ensure-PSGalleryTrusted
Install-Module -Name ImportExcel -Scope CurrentUser -Force -ErrorAction Stop
Import-Module ImportExcel -ErrorAction Stop | Out-Null
}
# --- Helpers for older ImportExcel versions ---
if (-not (Get-Command New-WorksheetName -ErrorAction SilentlyContinue)) {
function New-WorksheetName {
param([string]$Name)
if (-not $Name) { return 'Sheet' }
$san = ($Name -replace '[\\/:*?\[\]]','_')
if ($san.Length -gt 31) { $san = $san.Substring(0,31) }
if ($san -match '^\d+$') { $san = "_$san" }
return $san
}
}
if (-not (Get-Command Set-Cell -ErrorAction SilentlyContinue)) {
function Set-Cell {
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][string]$WorksheetName,
[Parameter(Mandatory)][int]$Row,
[Parameter(Mandatory)][int]$Column,
[string]$Value,
[string]$Hyperlink,
[switch]$Formula
)
# Fallback using EPPlus via ImportExcel helper cmdlets
$pkg = Open-ExcelPackage -Path $Path
try {
$ws = $pkg.Workbook.Worksheets[$WorksheetName]
if (-not $ws) { $ws = Add-WorkSheet -ExcelPackage $pkg -WorksheetName $WorksheetName }
$cell = $ws.Cells[$Row,$Column]
if ($Formula) {
try { $cell.Clear() } catch { }
if ($Value -and $Value.StartsWith('=')) { $cell.Formula = $Value.Substring(1) } else { $cell.Formula = $Value }
} else {
$cell.Value = $Value
}
if ($Hyperlink) { $cell.Hyperlink = $Hyperlink }
}
finally {
try { $pkg.Workbook.CalcMode = [OfficeOpenXml.ExcelCalcMode]::Automatic } catch { }
try { $ws.Calculate() } catch { }
try { $pkg.Save() } catch { }
try { $pkg.Dispose() } catch { }
}
}
}
function Try-AddConditionalFormatting {
param(
[string]$Path,
[string]$WorksheetName,
[string]$Range,
[string]$RuleType,
[string]$ConditionValue,
[string]$ForegroundColor,
[string]$BackgroundColor
)
try {
Add-ConditionalFormatting -Path $Path -WorksheetName $WorksheetName -Range $Range -RuleType $RuleType -ConditionValue $ConditionValue -ForegroundColor $ForegroundColor -BackgroundColor $BackgroundColor
} catch {
try {
$pkg = Open-ExcelPackage -Path $Path
$ws = $pkg.Workbook.Worksheets[$WorksheetName]
if ($ws) {
$cf = $ws.ConditionalFormatting.AddContainsText($Range)
$cf.Text = $ConditionValue
if ($BackgroundColor) { $cf.Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::$BackgroundColor) }
}
$pkg.Save(); $pkg.Dispose()
} catch { }
}
}
function Try-SetColumnWidth {
param(
[string]$Path,
[string]$WorksheetName,
[int]$Column,
[double]$Width
)
try {
Set-Column -Path $Path -WorksheetName $WorksheetName -Column $Column -Width $Width
} catch {
try {
$pkg = Open-ExcelPackage -Path $Path
$ws = $pkg.Workbook.Worksheets[$WorksheetName]
if ($ws) { $ws.Column($Column).Width = $Width }
$pkg.Save(); $pkg.Dispose()
} catch { }
}
}
function Try-SetFormat {
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][string]$WorksheetName,
[Parameter(Mandatory)][string]$Range,
[switch]$Bold,
[int]$FontSize,
[string]$BackgroundColor
)
$ok = $false
try {
Set-Format -Path $Path -WorksheetName $WorksheetName -Range $Range -Bold:$Bold -FontSize $FontSize -BackgroundColor $BackgroundColor
$ok = $true
} catch {}
if (-not $ok) {
try {
Set-Format -Address $Range -WorkSheetname $WorksheetName -Bold:$Bold -FontSize $FontSize -BackgroundColor $BackgroundColor -PassThru | Export-Excel -Path $Path -WorksheetName $WorksheetName -Append
$ok = $true
} catch {}
}
if (-not $ok) {
try {
$pkg = Open-ExcelPackage -Path $Path
$ws = $pkg.Workbook.Worksheets[$WorksheetName]
if ($ws) {
$addr = [OfficeOpenXml.ExcelAddress]::new($Range)
$cells = $ws.Cells[$addr.Address]
if ($Bold) { $cells.Style.Font.Bold = $true }
if ($FontSize -gt 0) { $cells.Style.Font.Size = $FontSize }
if ($BackgroundColor) { $cells.Style.Fill.PatternType = [OfficeOpenXml.Style.ExcelFillStyle]::Solid; $cells.Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::$BackgroundColor) }
}
$pkg.Save(); $pkg.Dispose()
} catch { }
}
}
function Add-PolicyNamesNamedRange {
param([Parameter(Mandatory)][string]$Path)
$pkg = Open-ExcelPackage -Path $Path
try {
$ws = $pkg.Workbook.Worksheets['Master']
if (-not $ws) { return }
$lastCol = $ws.Dimension.End.Column
$nameCol = $null
for ($c=1; $c -le $lastCol; $c++) {
if (($ws.Cells[1,$c].Text) -eq 'Name') { $nameCol = $c; break }
}
if ($null -eq $nameCol) { return }
$lastRow = $ws.Dimension.End.Row
if ($lastRow -lt 2) { return }
$rangeAddress = [OfficeOpenXml.ExcelAddress]::new(2, $nameCol, $lastRow, $nameCol)
$existing = $pkg.Workbook.Names['PolicyNames']
if ($existing) { $pkg.Workbook.Names.Remove($existing) | Out-Null }
[void]$pkg.Workbook.Names.Add('PolicyNames', $ws.Cells[$rangeAddress.Address])
$pkg.Save()
} finally { try { $pkg.Dispose() } catch { } }
}
function Add-PolicyNameValidation {
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][string]$WorksheetName
)
$pkg = Open-ExcelPackage -Path $Path
try {
$ws = $pkg.Workbook.Worksheets[$WorksheetName]
if (-not $ws) { return }
$dv = $ws.DataValidations.AddListValidation('B1')
$dv.Formula.ExcelFormula = 'PolicyNames'
$dv.ShowErrorMessage = $true
$dv.ErrorTitle = 'Invalid selection'
$dv.Error = 'Please pick a policy name from the list.'
$pkg.Save()
} finally { try { $pkg.Dispose() } catch { } }
}
}
# --- Ensure connection to Microsoft Graph with required scopes ---
$RequiredMgScopes = @(
'Application.Read.All',
'Group.Read.All',
'Policy.Read.All',
'RoleManagement.Read.Directory',
'User.Read.All',
'NetworkAccessPolicy.Read.All', # optional: for Global Secure Access profile names
'Agreement.Read.All' # optional: for Terms of Use display names
)
function Ensure-MgConnection {
try { $ctx = Get-MgContext -ErrorAction Stop } catch { $ctx = $null }
$needConnect = $true
if ($ctx) {
$currentScopes = @($ctx.Scopes)
if ($currentScopes -and ($RequiredMgScopes | Where-Object { $currentScopes -contains $_ }).Count -eq $RequiredMgScopes.Count) {
$needConnect = $false
}
}
if ($needConnect) {
Write-Host 'Connecting to Microsoft Graph...' -ForegroundColor Cyan
Connect-MgGraph -Scopes $RequiredMgScopes -NoWelcome
}
}
Ensure-MgConnection
function Test-Guid {
[Cmdletbinding()]
[OutputType([bool])]
param
(
[Parameter(Mandatory = $true, Position = 0, ValueFromPipelineByPropertyName = $true)]
[AllowEmptyString()]
[string]$InputObject
)
process {
return [guid]::TryParse($InputObject, $([ref][guid]::Empty))
}
}
function Resolve-MgObject {
[Cmdletbinding()]
[OutputType([string])]
param
(
[Parameter(Mandatory = $true, Position = 0, ValueFromPipelineByPropertyName = $true)]
[AllowEmptyString()]
[string]$InputObject
)
process {
if (Test-Guid -InputObject $InputObject) {
try {
if ($displayNameCache.ContainsKey($InputObject)) {
Write-Debug "Cached display name for `"$InputObject`""
return $displayNameCache[$InputObject]
} else {
$directoryObject = Get-MgDirectoryObject -DirectoryObjectId $InputObject -ErrorAction Stop
$displayName = $directoryObject.AdditionalProperties['displayName']
$displayNameCache[$InputObject] = $displayName
return $displayName
}
} catch {
Write-Warning "Unable to resolve directory object with ID $InputObject, might have been deleted!"
}
}
return $InputObject
}
}
# Add GetOrDefault to hashtables
$etd = @{
TypeName = 'System.Collections.Hashtable'
MemberType = 'Scriptmethod'
MemberName = 'GetOrDefault'
Value = {
param(
$key,
$defaultValue
)
if (-not [string]::IsNullOrEmpty($key)) {
if ($this.ContainsKey($key)) {
if ($this[$key].DisplayName) {
return $this[$key].DisplayName
} else {
return $this[$key]
}
} else {
return $defaultValue
}
}
}
}
Update-TypeData @etd -Force
Write-Progress -PercentComplete -1 -Activity 'Fetching conditional access policies and related data from Graph API'
try {
if (-not (Get-MgContext)) { Write-Warning "Not connected to Microsoft Graph. Run: Connect-MgGraph -Scopes \"Application.Read.All\",\"Group.Read.All\",\"Policy.Read.All\",\"RoleManagement.Read.Directory\",\"User.Read.All\",\"NetworkAccessPolicy.Read.All\",\"Agreement.Read.All\"" }
} catch { }
# Get Conditional Access Policies
$conditionalAccessPolicies = Get-MgIdentityConditionalAccessPolicy -ExpandProperty '*' -All -ErrorAction Stop
# Get Conditional Access Named / Trusted Locations
$namedLocations = Get-MgIdentityConditionalAccessNamedLocation -All -ErrorAction Stop | Group-Object -Property Id -AsHashTable
if (-not $namedLocations) { $namedLocations = @{} }
# Get Azure AD Directory Role Templates
try {
$directoryRoleTemplates = Get-MgDirectoryRoleTemplate -All -ErrorAction Stop | Group-Object -Property Id -AsHashTable
} catch {
Write-Warning "Directory role templates could not be retrieved (module missing or insufficient permissions). Role names will not be resolved."
$directoryRoleTemplates = @{}
}
# Service Principals
$servicePrincipals = Get-MgServicePrincipal -All -ErrorAction Stop | Group-Object -Property AppId -AsHashTable
# Terms of Use Agreements
try {
$termsOfUseAgreements = Get-MgIdentityGovernanceTermsOfUseAgreement -All -ErrorAction Stop | Group-Object -Property Id -AsHashTable
} catch {
Write-Warning "Terms of Use agreements could not be retrieved or permission missing (Agreement.Read.All)."
$termsOfUseAgreements = @{}
}
# Authentication context class references
try {
$authContextClassReferences = Get-MgIdentityConditionalAccessAuthenticationContextClassReference -All -ErrorAction Stop | Group-Object -Property Id -AsHashTable
} catch {
Write-Warning "Authentication context class references could not be retrieved. Context names will not be resolved."
$authContextClassReferences = @{}
}
# GSA network filtering profiles
try {
$networkFilteringProfiles = Invoke-MgGraphRequest -Uri 'https://graph.microsoft.com/beta/networkAccess/filteringProfiles' -Method GET -OutputType PSObject -ErrorAction Stop |
Select-Object -ExpandProperty value |
Group-Object -Property id -AsHashTable
} catch {
Write-Warning "Global Secure Access filtering profiles not available or insufficient permission. Skipping."
$networkFilteringProfiles = @{}
}
# Init report
$documentation = [System.Collections.Generic.List[Object]]::new()
# Cache for resolved display names
$displayNameCache = @{}
# Process all Conditional Access Policies
foreach ($policy in $conditionalAccessPolicies) {
$currentIndex = $conditionalAccessPolicies.indexOf($policy) + 1
$progress = @{
Activity = 'Generating Conditional Access Documentation...'
PercentComplete = [Decimal]::Divide($currentIndex, $conditionalAccessPolicies.Count) * 100
CurrentOperation = "Processing Policy `"$($policy.DisplayName)`""
}
if ($currentIndex -eq $conditionalAccessPolicies.Count) { $progress.Add('Completed', $true) }
Write-Progress @progress
Write-Output "Processing policy `"$($policy.DisplayName)`""
try {
$includeUsers = @($policy.Conditions?.Users?.IncludeUsers) | ForEach-Object { Resolve-MgObject -InputObject $_ }
$excludeUsers = @($policy.Conditions?.Users?.ExcludeUsers) | ForEach-Object { Resolve-MgObject -InputObject $_ }
$includeGroups = @($policy.Conditions?.Users?.IncludeGroups) | ForEach-Object { Resolve-MgObject -InputObject $_ }
$excludeGroups = @($policy.Conditions?.Users?.ExcludeGroups) | ForEach-Object { Resolve-MgObject -InputObject $_ }
$includeRoles = @($policy.Conditions?.Users?.IncludeRoles) | ForEach-Object { $directoryRoleTemplates.GetOrDefault($_, $_) }
$excludeRoles = @($policy.Conditions?.Users?.ExcludeRoles) | ForEach-Object { $directoryRoleTemplates.GetOrDefault($_, $_) }
$includeApps = @($policy.Conditions?.Applications?.IncludeApplications) | ForEach-Object { $servicePrincipals.GetOrDefault($_, $_) }
$excludeApps = @($policy.Conditions?.Applications?.ExcludeApplications) | ForEach-Object { $servicePrincipals.GetOrDefault($_, $_) }
$includeServicePrincipals = [System.Collections.Generic.List[Object]]::new()
$excludeServicePrincipals = [System.Collections.Generic.List[Object]]::new()
@($policy.Conditions?.ClientApplications?.IncludeServicePrincipals) | ForEach-Object { $includeServicePrincipals.Add($servicePrincipals.GetOrDefault($_, $_)) }
@($policy.Conditions?.ClientApplications?.ExcludeServicePrincipals) | ForEach-Object { $excludeServicePrincipals.Add($servicePrincipals.GetOrDefault($_, $_)) }
$includeAuthenticationContext = @($policy.Conditions?.Applications?.IncludeAuthenticationContextClassReferences) |
ForEach-Object { $authContextClassReferences.GetOrDefault($_, $_) }
$includeLocations = @($policy.Conditions?.Locations?.IncludeLocations) | ForEach-Object { $namedLocations.GetOrDefault($_, $_) }
$excludeLocations = @($policy.Conditions?.Locations?.ExcludeLocations) | ForEach-Object { $namedLocations.GetOrDefault($_, $_) }
$webFilteringProfile = $null
try {
$gsaProp = $policy.SessionControls?.AdditionalProperties?['globalSecureAccessFilteringProfile']
if ($gsaProp) {
$profileId = $gsaProp['profileId']
if ($profileId -and $networkFilteringProfiles.ContainsKey($profileId)) {
$webFilteringProfile = $networkFilteringProfiles[$profileId].name
}
}
} catch { }
$separator = "; "
$grantBuiltIn = @()
if ($policy.GrantControls?.BuiltInControls) { $grantBuiltIn += $policy.GrantControls.BuiltInControls }
if ($policy.GrantControls?.TermsOfUse) { $grantBuiltIn += 'termsOfUse' }
if ($policy.GrantControls?.AuthenticationStrength) { $grantBuiltIn += 'authenticationStrength' }
$grantControls = $grantBuiltIn | Where-Object { $_ -ne 'authenticationStrength' }
$authStrengthName = $policy.GrantControls?.AuthenticationStrength?.DisplayName
if ($authStrengthName) { $grantControls += 'authenticationStrength' }
$authStrengthAllowed = @($policy.GrantControls?.AuthenticationStrength?.AllowedCombinations) -join $separator
$signInFrequency = $null
if ($policy.SessionControls?.SignInFrequency?.Value) {
$signInFrequency = "{0} {1}" -f $policy.SessionControls.SignInFrequency.Value, $policy.SessionControls.SignInFrequency.Type
}
$secureSignInSession = $null
$ss = $policy.SessionControls?.AdditionalProperties?['secureSignInSession']
if ($ss) { $secureSignInSession = $ss.isEnabled }
$includeDeviceStates = @($policy.Conditions?.DeviceStates?.IncludeStates)
$excludeDeviceStates = @($policy.Conditions?.DeviceStates?.ExcludeStates)
$includeGuestsOrExternalUserTypes = $policy.Conditions?.Users?.IncludeGuestsOrExternalUsers?.guestOrExternalUserTypes
$includeGuestsOrExternalUserTenants = @($policy.Conditions?.Users?.IncludeGuestsOrExternalUsers?.externalTenants?.AdditionalProperties?['members'])
$authFlowsObj = $policy.Conditions?.AuthenticationFlows
$authenticationFlows = if ($authFlowsObj) {
$authFlowsObj.TransferMethods ?? $authFlowsObj.AdditionalProperties?['transferMethods']
}
$applicationsAdditional = $null
if ($policy.Conditions?.Applications?.AdditionalProperties) {
$applicationsAdditional = ($policy.Conditions.Applications.AdditionalProperties | ConvertTo-Json -Depth 6 -Compress)
}
$conditionsAdditional = $null
if ($policy.Conditions?.AdditionalProperties) {
$conditionsAdditional = ($policy.Conditions.AdditionalProperties | ConvertTo-Json -Depth 6 -Compress)
}
$termsOfUseNames = $null
if ($policy.GrantControls?.TermsOfUse) {
$termsOfUseNames = ($policy.GrantControls.TermsOfUse | ForEach-Object { $termsOfUseAgreements.GetOrDefault($_, $_) }) -join $separator
}
$grantControlsAdditional = $null
if ($policy.GrantControls?.AdditionalProperties) {
$grantControlsAdditional = ($policy.GrantControls.AdditionalProperties | ConvertTo-Json -Depth 6 -Compress)
}
$cloudAppSecurityMode = $policy.SessionControls?.CloudAppSecurity?.Mode
$sessionAdditional = $null
if ($policy.SessionControls?.AdditionalProperties) {
$sessionAdditional = ($policy.SessionControls.AdditionalProperties | ConvertTo-Json -Depth 6 -Compress)
}
$documentation.Add(
[PSCustomObject]@{
Name = $policy.DisplayName
IncludeUsers = ($includeUsers -join $separator)
IncludeGroups = ($includeGroups -join $separator)
IncludeRoles = ($includeRoles -join $separator)
ExcludeUsers = ($excludeUsers -join $separator)
ExcludeGuestOrExternalUserTypes = $policy.Conditions?.Users?.ExcludeGuestsOrExternalUsers?.guestOrExternalUserTypes
ExcludeGuestOrExternalUserTenants = (@($policy.Conditions?.Users?.ExcludeGuestsOrExternalUsers?.externalTenants?.AdditionalProperties?['members']) -join $separator)
ExcludeGroups = ($excludeGroups -join $separator)
ExcludeRoles = ($excludeRoles -join $separator)
IncludeApps = ($includeApps -join $separator)
ExcludeApps = ($excludeApps -join $separator)
ApplicationFilterMode = $policy.Conditions?.Applications?.ApplicationFilter?.mode
ApplicationFilterRule = $policy.Conditions?.Applications?.ApplicationFilter?.rule
IncludeAuthenticationContext = ($includeAuthenticationContext -join $separator)
IncludeUserActions = (@($policy.Conditions?.Applications?.IncludeUserActions) -join $separator)
ClientAppTypes = (@($policy.Conditions?.ClientAppTypes) -join $separator)
IncludePlatforms = (@($policy.Conditions?.Platforms?.IncludePlatforms) -join $separator)
ExcludePlatforms = (@($policy.Conditions?.Platforms?.ExcludePlatforms) -join $separator)
IncludeLocations = ($includeLocations -join $separator)
ExcludeLocations = ($excludeLocations -join $separator)
DeviceFilterMode = $policy.Conditions?.Devices?.DeviceFilter?.Mode
DeviceFilterRule = $policy.Conditions?.Devices?.DeviceFilter?.Rule
SignInRiskLevels = (@($policy.Conditions?.SignInRiskLevels) -join $separator)
UserRiskLevels = (@($policy.Conditions?.UserRiskLevels) -join $separator)
ServicePrincipalRiskLevels = (@($policy.Conditions?.servicePrincipalRiskLevels) -join $separator)
IncludeDeviceStates = (@($includeDeviceStates) -join $separator)
ExcludeDeviceStates = (@($excludeDeviceStates) -join $separator)
IncludeGuestsOrExternalUserTypes = $includeGuestsOrExternalUserTypes
IncludeGuestOrExternalUserTenants = (@($includeGuestsOrExternalUserTenants) -join $separator)
AuthenticationFlows = $authenticationFlows
ApplicationsAdditional = $applicationsAdditional
ConditionsAdditional = $conditionsAdditional
IncludeServicePrincipals = ($includeServicePrincipals -join $separator)
ExcludeServicePrincipals = ($excludeServicePrincipals -join $separator)
ServicePrincipalFilterMode = $policy.Conditions?.ClientApplications?.ServicePrincipalFilter?.mode
ServicePrincipalFilter = $policy.Conditions?.ClientApplications?.ServicePrincipalFilter?.rule
GrantControls = ($grantControls -join $separator)
GrantControlsOperator = $policy.GrantControls?.Operator
AuthenticationStrength = $authStrengthName
AuthenticationStrengthAllowedCombinations = $authStrengthAllowed
TermsOfUseNames = $termsOfUseNames
GrantControlsAdditional = $grantControlsAdditional
ApplicationEnforcedRestrictions = $policy.SessionControls?.ApplicationEnforcedRestrictions?.IsEnabled
CloudAppSecurity = $policy.SessionControls?.CloudAppSecurity?.IsEnabled
CloudAppSecurityMode = $cloudAppSecurityMode
DisableResilienceDefaults = $policy.SessionControls?.DisableResilienceDefaults
PersistentBrowser = $policy.SessionControls?.PersistentBrowser?.Mode
SignInFrequency = $signInFrequency
SecureSignInSession = $secureSignInSession
GlobalSecureAccessFilteringProfile = $webFilteringProfile
SessionControlsAdditional = $sessionAdditional
State = $policy.State
}
)
} catch {
Write-Error $PSItem
}
}
# Build export path (script directory)
$exportPath = Join-Path $PSScriptRoot 'ConditionalAccessDocumentation.csv'
$CsvDelimiter = ';'
$exportParams = @{ Path = $exportPath; NoTypeInformation = $true; Delimiter = $CsvDelimiter; Encoding = 'utf8BOM' }
try {
$exportParams['UseQuotes'] = 'AsNeeded'
} catch { }
try {
$documentation | Export-Csv @exportParams
} catch {
Write-Warning "Export-Csv with UTF-8 BOM failed on this PowerShell version. Retrying with UTF-8 (no BOM)."
$exportParams['Encoding'] = 'utf8'
$documentation | Export-Csv @exportParams
}
Write-Output "Exported Documentation to '$($exportPath)'"
if ($ExportExcel) {
Write-Host 'Building Excel workbook...' -ForegroundColor Cyan
if (-not $ExcelPath) {
$ExcelPath = Join-Path $PSScriptRoot 'ConditionalAccessDocumentation.xlsx'
}
if (Test-Path $ExcelPath) { Remove-Item $ExcelPath -Force }
$documentation | Export-Excel -Path $ExcelPath -WorksheetName 'Master' -TableName 'Master' -TableStyle 'Medium9' -ClearSheet -FreezeTopRow -AutoFilter
$summary = $documentation | Select-Object Name, State
$summary | Export-Excel -Path $ExcelPath -WorksheetName 'Summary' -TableName 'Policies' -TableStyle 'Medium6' -ClearSheet -FreezeTopRow -AutoFilter
Try-AddConditionalFormatting -Path $ExcelPath -WorksheetName 'Summary' -Range 'B2:B1048576' -RuleType ContainsText -ConditionValue 'enabled' -ForegroundColor 'Black' -BackgroundColor 'LightGreen'
Try-AddConditionalFormatting -Path $ExcelPath -WorksheetName 'Summary' -Range 'B2:B1048576' -RuleType ContainsText -ConditionValue 'disabled' -ForegroundColor 'Black' -BackgroundColor 'LightGray'
Try-AddConditionalFormatting -Path $ExcelPath -WorksheetName 'Summary' -Range 'B2:B1048576' -RuleType ContainsText -ConditionValue 'reportOnly' -ForegroundColor 'Black' -BackgroundColor 'Khaki'
Add-PolicyNamesNamedRange -Path $ExcelPath
$sections = @(
@{ Title = 'General'; Fields = @(
@{ Label = 'Policy name'; Col = 'Name' },
@{ Label = 'State'; Col = 'State' }
)},
@{ Title = 'Users and groups'; Fields = @(
@{ Label = 'Include users'; Col = 'IncludeUsers' },
@{ Label = 'Include groups'; Col = 'IncludeGroups' },
@{ Label = 'Include roles'; Col = 'IncludeRoles' },
@{ Label = 'Exclude users'; Col = 'ExcludeUsers' },
@{ Label = 'Exclude groups'; Col = 'ExcludeGroups' },
@{ Label = 'Exclude roles'; Col = 'ExcludeRoles' }
)},
@{ Title = 'Applications'; Fields = @(
@{ Label = 'Include apps'; Col = 'IncludeApps' },
@{ Label = 'Exclude apps'; Col = 'ExcludeApps' },
@{ Label = 'Client app types';Col = 'ClientAppTypes' },
@{ Label = 'AuthN context'; Col = 'IncludeAuthenticationContext' }
)},
@{ Title = 'Conditions'; Fields = @(
@{ Label = 'Platforms include'; Col = 'IncludePlatforms' },
@{ Label = 'Platforms exclude'; Col = 'ExcludePlatforms' },
@{ Label = 'Locations include'; Col = 'IncludeLocations' },
@{ Label = 'Locations exclude'; Col = 'ExcludeLocations' },
@{ Label = 'Device filter mode'; Col = 'DeviceFilterMode' },
@{ Label = 'Device filter rule'; Col = 'DeviceFilterRule' },
@{ Label = 'Sign-in risk'; Col = 'SignInRiskLevels' },
@{ Label = 'User risk'; Col = 'UserRiskLevels' },
@{ Label = 'Authentication flows'; Col = 'AuthenticationFlows' }
)},
@{ Title = 'Grant'; Fields = @(
@{ Label = 'Operator'; Col = 'GrantControlsOperator' },
@{ Label = 'Controls'; Col = 'GrantControls' },
@{ Label = 'Auth strength'; Col = 'AuthenticationStrength' },
@{ Label = 'Allowed combos'; Col = 'AuthenticationStrengthAllowedCombinations' },
@{ Label = 'Terms of Use'; Col = 'TermsOfUseNames' }
)},
@{ Title = 'Session'; Fields = @(
@{ Label = 'App enforced restrictions'; Col = 'ApplicationEnforcedRestrictions' },
@{ Label = 'Defender for Cloud Apps'; Col = 'CloudAppSecurity' },
@{ Label = 'CAS mode'; Col = 'CloudAppSecurityMode' },
@{ Label = 'Persistent browser'; Col = 'PersistentBrowser' },
@{ Label = 'Sign-in frequency'; Col = 'SignInFrequency' },
@{ Label = 'Secure sign-in session'; Col = 'SecureSignInSession' },
@{ Label = 'GSA filtering profile'; Col = 'GlobalSecureAccessFilteringProfile' }
)}
)
$first = $documentation | Select-Object -First 1
$masterHeaders = @()
if ($first) { $masterHeaders = @($first.PSObject.Properties.Name) }
$headerIndex = @{}
for ($i=0; $i -lt $masterHeaders.Count; $i++) { $headerIndex[$masterHeaders[$i]] = $i+1 }
foreach ($item in $documentation) {
$sheetName = New-WorksheetName -Name $item.Name
Export-Excel -Path $ExcelPath -WorksheetName $sheetName -ClearSheet | Out-Null
Set-Cell -Path $ExcelPath -WorksheetName $sheetName -Row 1 -Column 1 -Value 'Policy'
Set-Cell -Path $ExcelPath -WorksheetName $sheetName -Row 1 -Column 2 -Value $item.Name
Try-SetFormat -Path $ExcelPath -WorksheetName $sheetName -Range 'A1:B1' -Bold -FontSize 14
$rowPtr = 3
foreach ($section in $sections) {
Set-Cell -Path $ExcelPath -WorksheetName $sheetName -Row $rowPtr -Column 1 -Value $section.Title
Try-SetFormat -Path $ExcelPath -WorksheetName $sheetName -Range ("A$rowPtr:B$rowPtr") -Bold -BackgroundColor 'LightGray'
$rowPtr++
foreach ($f in $section.Fields) {
$label = $f.Label
$colName = $f.Col
Set-Cell -Path $ExcelPath -WorksheetName $sheetName -Row $rowPtr -Column 1 -Value $label
if ($headerIndex.ContainsKey($colName)) {
$formula = "=INDEX(Master[$colName], MATCH(`$B`$1, Master[Name], 0))"
Set-Cell -Path $ExcelPath -WorksheetName $sheetName -Row $rowPtr -Column 2 -Value $formula -Formula
} else {
Set-Cell -Path $ExcelPath -WorksheetName $sheetName -Row $rowPtr -Column 2 -Value ''
}
$rowPtr++
}
$rowPtr++
}
Try-SetColumnWidth -Path $ExcelPath -WorksheetName $sheetName -Column 1 -Width 34
Try-SetColumnWidth -Path $ExcelPath -WorksheetName $sheetName -Column 2 -Width 80
Try-AddConditionalFormatting -Path $ExcelPath -WorksheetName $sheetName -Range 'B1:B200' -RuleType ContainsText -ConditionValue 'enabled' -ForegroundColor 'Black' -BackgroundColor 'LightGreen'
Try-AddConditionalFormatting -Path $ExcelPath -WorksheetName $sheetName -Range 'B1:B200' -RuleType ContainsText -ConditionValue 'disabled' -ForegroundColor 'Black' -BackgroundColor 'LightGray'
Try-AddConditionalFormatting -Path $ExcelPath -WorksheetName $sheetName -Range 'B1:B200' -RuleType ContainsText -ConditionValue 'reportOnly' -ForegroundColor 'Black' -BackgroundColor 'Khaki'
}
# Hyperlinks from Summary -> policy sheets
$r = 2
foreach ($name in $documentation | Select-Object -ExpandProperty Name) {
$ws = New-WorksheetName -Name $name
Set-Cell -Path $ExcelPath -WorksheetName 'Summary' -Row $r -Column 1 -Value $name -Hyperlink ("#'" + $ws + "'!A1")
$r++
}
Write-Output "Exported Excel workbook to '$ExcelPath'"
}
+63
View File
@@ -0,0 +1,63 @@
# Interactive folder picker shared by the launcher and the TUI.
# With fzf: browse folders, create a new one, or type a path. Without fzf: plain prompt.
# Returns the chosen full path, or $null when cancelled (Esc / empty input and no default).
function ConvertTo-FullFolderPath
{
param([string]$Path)
if([string]::IsNullOrWhiteSpace($Path)) { return $null }
$p = $Path.Trim().Trim('"', "'") -replace '^~', $HOME
[IO.Path]::GetFullPath($p)
}
function Select-FolderPath
{
param(
[Parameter(Mandatory)]
[string]$Prompt,
[string]$StartPath = (Get-Location).Path,
# Used when the fallback prompt gets an empty answer
[string]$Default
)
if(-not (Get-Command fzf -ErrorAction SilentlyContinue))
{
$suffix = if($Default) { " (Enter = $Default)" } else { "" }
$typed = Read-Host "$Prompt$suffix"
if([string]::IsNullOrWhiteSpace($typed)) { $typed = $Default }
return (ConvertTo-FullFolderPath $typed)
}
# Start at the nearest folder that exists (the default root may not exist yet)
$current = ConvertTo-FullFolderPath $StartPath
while($current -and -not (Test-Path -LiteralPath $current -PathType Container)) { $current = Split-Path -Path $current -Parent }
if(-not $current) { $current = (Get-Location).Path }
while($true)
{
$entries = @("[Use this folder]", "[Create new folder]", "[Type path manually]")
$parent = Split-Path -Path $current -Parent
if($parent) { $entries += ".." }
$entries += Get-ChildItem -LiteralPath $current -Directory -ErrorAction SilentlyContinue | Sort-Object Name | ForEach-Object { "$($_.Name)/" }
$choice = $entries | fzf --header="$Prompt [current: $current]"
if(-not $choice) { return $null }
switch ($choice)
{
"[Use this folder]" { return $current }
"[Create new folder]" {
$name = (Read-Host "New folder name (inside $current)").Trim()
if([string]::IsNullOrWhiteSpace($name)) { continue }
if($name.IndexOfAny([IO.Path]::GetInvalidFileNameChars()) -ge 0) { Write-Host "Invalid folder name." -ForegroundColor Yellow; continue }
$newPath = Join-Path $current $name
try { New-Item -ItemType Directory -Path $newPath -Force -ErrorAction Stop | Out-Null; $current = $newPath }
catch { Write-Host "Could not create folder: $($_.Exception.Message)" -ForegroundColor Yellow }
continue
}
"[Type path manually]" { $typed = Read-Host "Enter path"; if(-not [string]::IsNullOrWhiteSpace($typed)) { return (ConvertTo-FullFolderPath $typed) }; continue }
".." { $current = $parent; continue }
default { $current = Join-Path $current ($choice.TrimEnd('/')); continue }
}
}
}
+60 -24
View File
@@ -8,7 +8,10 @@
Uses fzf on macOS/Linux when available; falls back to numbered menus. Uses fzf on macOS/Linux when available; falls back to numbered menus.
#> #>
[CmdletBinding()] [CmdletBinding()]
param() param(
[string]$TenantId,
[string]$Action
)
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Stop"
@@ -104,6 +107,8 @@ function Select-MenuItem
return Show-NumberedMenu -Items $Items -Header $Header -Multi:$Multi return Show-NumberedMenu -Items $Items -Header $Header -Multi:$Multi
} }
. (Join-Path $PSScriptRoot "Select-FolderPath.ps1")
function Read-YesNo function Read-YesNo
{ {
param( param(
@@ -157,18 +162,33 @@ while($true)
Write-Host " Press Esc to go back, Space to select" -ForegroundColor DarkGray Write-Host " Press Esc to go back, Space to select" -ForegroundColor DarkGray
# 1. Action # 1. Action
$action = Select-MenuItem -Items @("Export","Import","DeployCISBaseline","GenerateReports") -Header "Select action" if($Action)
if(-not $action) { continue } {
$action = $Action
}
else
{
$action = Select-MenuItem -Items @("Export","Import","DeployCISBaseline","GenerateReports") -Header "Select action"
if(-not $action) { continue }
}
# CIS M365 Baseline deployment flow # CIS M365 Baseline deployment flow
if($action -eq "DeployCISBaseline") if($action -eq "DeployCISBaseline")
{ {
# 2a. TenantId # 2a. TenantId
$tenantPrompt = "Enter Tenant ID" if($TenantId)
if($preloadedTenantId) { $tenantPrompt += " (default: $preloadedTenantId)" } {
$tenantId = Read-Host $tenantPrompt $tenantId = $TenantId
if([string]::IsNullOrWhiteSpace($tenantId)) { $tenantId = $preloadedTenantId } Write-Host "Tenant: $tenantId" -ForegroundColor DarkGray
if([string]::IsNullOrWhiteSpace($tenantId)) { Write-Host "Tenant ID is required." -ForegroundColor Red; continue } }
else
{
$tenantPrompt = "Enter Tenant ID"
if($preloadedTenantId) { $tenantPrompt += " (default: $preloadedTenantId)" }
$tenantId = Read-Host $tenantPrompt
if([string]::IsNullOrWhiteSpace($tenantId)) { $tenantId = $preloadedTenantId }
if([string]::IsNullOrWhiteSpace($tenantId)) { Write-Host "Tenant ID is required." -ForegroundColor Red; continue }
}
# 2b. Baseline path # 2b. Baseline path
$defaultBaseline = Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "Baselines/CISM365-v7-Generated.yaml" $defaultBaseline = Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "Baselines/CISM365-v7-Generated.yaml"
@@ -243,24 +263,32 @@ while($true)
if($dataSource -like "*fresh*") if($dataSource -like "*fresh*")
{ {
$tenantPrompt = "Enter Tenant ID" if($TenantId)
if($preloadedTenantId) { $tenantPrompt += " (default: $preloadedTenantId)" } {
$tenantIdForReport = Read-Host $tenantPrompt $tenantIdForReport = $TenantId
if([string]::IsNullOrWhiteSpace($tenantIdForReport)) { $tenantIdForReport = $preloadedTenantId } Write-Host "Tenant: $tenantIdForReport" -ForegroundColor DarkGray
if([string]::IsNullOrWhiteSpace($tenantIdForReport)) { Write-Host "Tenant ID is required." -ForegroundColor Red; continue } }
else
{
$tenantPrompt = "Enter Tenant ID"
if($preloadedTenantId) { $tenantPrompt += " (default: $preloadedTenantId)" }
$tenantIdForReport = Read-Host $tenantPrompt
if([string]::IsNullOrWhiteSpace($tenantIdForReport)) { $tenantIdForReport = $preloadedTenantId }
if([string]::IsNullOrWhiteSpace($tenantIdForReport)) { Write-Host "Tenant ID is required." -ForegroundColor Red; continue }
}
$exportPath = Read-Host "Export path (where to save fresh data)" $exportPath = Select-FolderPath -Prompt "Select export path (where to save fresh data)"
if([string]::IsNullOrWhiteSpace($exportPath)) { Write-Host "Export path is required." -ForegroundColor Red; continue } if([string]::IsNullOrWhiteSpace($exportPath)) { Write-Host "Export path is required." -ForegroundColor Red; continue }
$backupRoot = $exportPath $backupRoot = $exportPath
} }
else else
{ {
$backupRoot = Read-Host "Backup root path (folder containing 'Settings Catalog', etc.)" $backupRoot = Select-FolderPath -Prompt "Select backup root (folder containing 'Settings Catalog', etc.)"
if([string]::IsNullOrWhiteSpace($backupRoot)) { Write-Host "Backup root is required." -ForegroundColor Red; continue } if([string]::IsNullOrWhiteSpace($backupRoot)) { Write-Host "Backup root is required." -ForegroundColor Red; continue }
if(-not (Test-Path $backupRoot)) { Write-Host "Path not found: $backupRoot" -ForegroundColor Red; continue } if(-not (Test-Path $backupRoot)) { Write-Host "Path not found: $backupRoot" -ForegroundColor Red; continue }
} }
$outputDir = Read-Host "Enter output directory for reports" $outputDir = Select-FolderPath -Prompt "Select output directory for reports"
if([string]::IsNullOrWhiteSpace($outputDir)) { Write-Host "Output directory is required." -ForegroundColor Red; continue } if([string]::IsNullOrWhiteSpace($outputDir)) { Write-Host "Output directory is required." -ForegroundColor Red; continue }
$includeAssignmentsInSettings = $false $includeAssignmentsInSettings = $false
@@ -312,11 +340,19 @@ while($true)
} }
# 2. TenantId # 2. TenantId
$tenantPrompt = "Enter Tenant ID" if($TenantId)
if($preloadedTenantId) { $tenantPrompt += " (default: $preloadedTenantId)" } {
$tenantId = Read-Host $tenantPrompt $tenantId = $TenantId
if([string]::IsNullOrWhiteSpace($tenantId)) { $tenantId = $preloadedTenantId } Write-Host "`nTenant: $tenantId" -ForegroundColor DarkGray
if([string]::IsNullOrWhiteSpace($tenantId)) { Write-Host "Tenant ID is required." -ForegroundColor Red; continue } }
else
{
$tenantPrompt = "Enter Tenant ID"
if($preloadedTenantId) { $tenantPrompt += " (default: $preloadedTenantId)" }
$tenantId = Read-Host $tenantPrompt
if([string]::IsNullOrWhiteSpace($tenantId)) { $tenantId = $preloadedTenantId }
if([string]::IsNullOrWhiteSpace($tenantId)) { Write-Host "Tenant ID is required." -ForegroundColor Red; continue }
}
# 3. Object Types # 3. Object Types
Write-Host "`nObject type selection..." -ForegroundColor Cyan Write-Host "`nObject type selection..." -ForegroundColor Cyan
@@ -324,12 +360,12 @@ while($true)
if(-not $typeSelection) { continue } if(-not $typeSelection) { continue }
# 4. Path # 4. Path
$pathPrompt = if($action -eq "Export") { "Enter export root folder path" } else { "Enter import root folder path" } $pathPrompt = if($action -eq "Export") { "Select export root folder" } else { "Select import root folder" }
$path = Read-Host $pathPrompt $path = Select-FolderPath -Prompt $pathPrompt
if([string]::IsNullOrWhiteSpace($path)) { Write-Host "Path is required." -ForegroundColor Red; return $null } if([string]::IsNullOrWhiteSpace($path)) { Write-Host "Path is required." -ForegroundColor Red; return $null }
# 5. Name Filter # 5. Name Filter
$nameFilter = Read-Host "Name filter regex (optional, e.g. '^Win-OIB-')" $nameFilter = Read-Host "Name filter, text to match anywhere in name, case-insensitive (optional, e.g. 'Win-OIB-')"
# 6. Name Mutation # 6. Name Mutation
$nameSearchPattern = Read-Host "Name search regex for mutation (optional, e.g. '^Win-OIB-')" $nameSearchPattern = Read-Host "Name search regex for mutation (optional, e.g. '^Win-OIB-')"
+4 -1
View File
@@ -52,6 +52,8 @@ param(
[switch]$ReplaceDependencyIds, [switch]$ReplaceDependencyIds,
[switch]$NoBatchApi,
[switch]$Interactive, [switch]$Interactive,
# GenerateReports params # GenerateReports params
@@ -84,7 +86,7 @@ if($Interactive)
$tuiScript = Join-Path (Split-Path -Parent $PSScriptRoot) "Scripts/Private/Start-IntuneManagementTui.ps1" $tuiScript = Join-Path (Split-Path -Parent $PSScriptRoot) "Scripts/Private/Start-IntuneManagementTui.ps1"
if(Test-Path $tuiScript) if(Test-Path $tuiScript)
{ {
$tuiResult = & $tuiScript $tuiResult = & $tuiScript -TenantId $TenantId -Action $Action
if(-not $tuiResult) { Write-Host "No selection made. Exiting." -ForegroundColor Yellow; exit 0 } if(-not $tuiResult) { Write-Host "No selection made. Exiting." -ForegroundColor Yellow; exit 0 }
foreach($prop in $tuiResult.PSObject.Properties) foreach($prop in $tuiResult.PSObject.Properties)
{ {
@@ -237,6 +239,7 @@ $invokeParams = @{
AddCompanyName = $AddCompanyName AddCompanyName = $AddCompanyName
IncludeScopeTags = $IncludeScopeTags IncludeScopeTags = $IncludeScopeTags
ReplaceDependencyIds = $ReplaceDependencyIds ReplaceDependencyIds = $ReplaceDependencyIds
NoBatchApi = $NoBatchApi
} }
if($Interactive -and $Action) { $invokeParams.Action = $Action } if($Interactive -and $Action) { $invokeParams.Action = $Action }
+204 -27
View File
@@ -108,6 +108,7 @@ function Select-MenuItem
#endregion #endregion
$projectRoot = $PSScriptRoot $projectRoot = $PSScriptRoot
. (Join-Path $projectRoot "Scripts/Private/Select-FolderPath.ps1")
#region Tenant selection #region Tenant selection
function Get-DefaultSettingsPath function Get-DefaultSettingsPath
@@ -174,6 +175,25 @@ function Update-TenantNameCache
catch { } catch { }
} }
function Get-LauncherSetting
{
param([string]$SettingsPath, [string]$Name)
if(-not (Test-Path $SettingsPath)) { return $null }
try { (Get-Content $SettingsPath -Raw -ErrorAction Stop | ConvertFrom-Json -AsHashtable -ErrorAction Stop)[$Name] } catch { $null }
}
function Set-LauncherSetting
{
param([string]$SettingsPath, [string]$Name, $Value)
try
{
$raw = if(Test-Path $SettingsPath) { Get-Content $SettingsPath -Raw -ErrorAction Stop | ConvertFrom-Json -AsHashtable -ErrorAction Stop } else { @{} }
$raw[$Name] = $Value
$raw | ConvertTo-Json -Depth 10 | Set-Content -Path $SettingsPath -Force
}
catch { }
}
function Resolve-TenantName function Resolve-TenantName
{ {
param([string]$TenantId, [string]$SettingsPath) param([string]$TenantId, [string]$SettingsPath)
@@ -249,7 +269,7 @@ if(-not $TenantId)
$tenantOptions += "[Exit]" $tenantOptions += "[Exit]"
$selectedTenantDisplay = Select-MenuItem -Items $tenantOptions -Header "Select a tenant" $selectedTenantDisplay = Select-MenuItem -Items $tenantOptions -Header "Select a tenant"
if(-not $selectedTenantDisplay -or $selectedTenantDisplay -eq "[Exit]") if(-not $selectedTenantDisplay -or $selectedTenantDisplay -eq "[Exit]" -or $selectedTenantDisplay -eq "EXIT")
{ {
exit 0 exit 0
} }
@@ -307,27 +327,47 @@ $commonParams = @{
SettingsFile = $SettingsFile SettingsFile = $SettingsFile
} }
$menuItems = @( # Menu entries in display order. Id is the internal dispatch id used below; the number shown to the user
"18. Rotate app secret" # is assigned automatically, so entries can be added or moved without renumbering anything.
"17. Deploy CIS M365 baseline" $menuDefs = @(
"16. Generate reports" # Export / Import
"15. Delete tenant auth and app registration" @{ Id = 1; Label = "Export policies" }
"14. Delete local tenant auth only" @{ Id = 2; Label = "Import policies" }
"13. Refresh tenant names" @{ Id = 23; Label = "Full tenant export (all types + assignments, dated folder)" }
"12. Initialize auth (one-time setup)" @{ Id = 7; Label = "Export assignments to CSV/Markdown" }
"11. Deploy baseline (dry-run / WhatIf)" @{ Id = 5; Label = "Backup assignments" }
"10. Deploy baseline" @{ Id = 6; Label = "Restore assignments" }
"9. Bulk device operations" # Bulk operations
"8. Bulk rename policies" @{ Id = 3; Label = "Bulk app assignment" }
"7. Export assignments to CSV/Markdown" @{ Id = 4; Label = "Bulk assignment manager (policies)" }
"6. Restore assignments" @{ Id = 8; Label = "Bulk rename policies" }
"5. Backup assignments" @{ Id = 21; Label = "Bulk delete policies" }
"4. Bulk assignment manager (policies)" @{ Id = 24; Label = "Bulk scope tags (add / replace / remove / clean up)" }
"3. Bulk app assignment" @{ Id = 9; Label = "Bulk device operations" }
"2. Import policies" # Baselines & compliance
"1. Export policies" @{ Id = 10; Label = "Deploy baseline" }
"0. Exit" @{ Id = 11; Label = "Deploy baseline (dry-run / WhatIf)" }
@{ Id = 17; Label = "Deploy CIS M365 baseline" }
@{ Id = 19; Label = "Document Conditional Access policies" }
# Reporting
@{ Id = 16; Label = "Generate reports" }
@{ Id = 20; Label = "Export Entra role membership" }
@{ Id = 22; Label = "Compare two tenant exports (offline)" }
# Tenant & auth admin
@{ Id = 12; Label = "Initialize auth (one-time setup)" }
@{ Id = 13; Label = "Refresh tenant names" }
@{ Id = 18; Label = "Rotate app secret" }
@{ Id = 14; Label = "Delete local tenant auth only" }
@{ Id = 15; Label = "Delete tenant auth and app registration" }
) )
$menuIdByNumber = @{}
$menuItems = @()
for($i = 0; $i -lt $menuDefs.Count; $i++)
{
$menuIdByNumber[$i + 1] = $menuDefs[$i].Id
$menuItems += ("{0}." -f ($i + 1)).PadRight(4) + $menuDefs[$i].Label
}
$menuItems += "0.".PadRight(4) + "Exit"
while($true) while($true)
{ {
@@ -356,7 +396,8 @@ while($true)
exit 0 exit 0
} }
$choiceNumber = [int]($selection -replace "^(\d+)\..*$", '$1') $choiceNumber = $menuIdByNumber[[int]($selection -replace "^(\d+)\..*$", '$1')]
if($null -eq $choiceNumber) { continue }
$script = $null $script = $null
switch($choiceNumber) switch($choiceNumber)
@@ -369,6 +410,8 @@ while($true)
6 { $script = "Scripts/Backup-Restore-Assignments.ps1" } 6 { $script = "Scripts/Backup-Restore-Assignments.ps1" }
7 { $script = "Scripts/Export-AssignmentsToCsv.ps1" } 7 { $script = "Scripts/Export-AssignmentsToCsv.ps1" }
8 { $script = "Scripts/Bulk-RenamePolicies.ps1" } 8 { $script = "Scripts/Bulk-RenamePolicies.ps1" }
21 { $script = "Scripts/Bulk-DeletePolicies.ps1" }
24 { $script = "Scripts/Bulk-ScopeTags.ps1" }
9 { $script = "Scripts/Bulk-DeviceOperations.ps1" } 9 { $script = "Scripts/Bulk-DeviceOperations.ps1" }
10 { $script = "Scripts/Deploy-IntuneBaseline.ps1" } 10 { $script = "Scripts/Deploy-IntuneBaseline.ps1" }
11 { $script = "Scripts/Deploy-IntuneBaseline.ps1" } 11 { $script = "Scripts/Deploy-IntuneBaseline.ps1" }
@@ -381,13 +424,14 @@ while($true)
# Clear any mode-specific params from previous loop iteration # Clear any mode-specific params from previous loop iteration
$commonParams.Remove("Interactive") $commonParams.Remove("Interactive")
$commonParams.Remove("Action")
$commonParams.Remove("Mode") $commonParams.Remove("Mode")
$commonParams.Remove("WhatIf") $commonParams.Remove("WhatIf")
switch($choiceNumber) switch($choiceNumber)
{ {
1 { $commonParams.Interactive = $true } 1 { $commonParams.Interactive = $true; $commonParams.Action = "Export" }
2 { $commonParams.Interactive = $true } 2 { $commonParams.Interactive = $true; $commonParams.Action = "Import" }
5 { $commonParams.Mode = "Backup" } 5 { $commonParams.Mode = "Backup" }
6 { $commonParams.Mode = "Restore" } 6 { $commonParams.Mode = "Restore" }
11 { $commonParams.WhatIf = $true } 11 { $commonParams.WhatIf = $true }
@@ -438,18 +482,18 @@ while($true)
$exportPath = $null $exportPath = $null
if($dataSource -like "*fresh*") if($dataSource -like "*fresh*")
{ {
$exportPath = Read-Host "Export path (where to save fresh data)" $exportPath = Select-FolderPath -Prompt "Export path (where to save fresh data)"
if([string]::IsNullOrWhiteSpace($exportPath)) { Write-Host "Required." -ForegroundColor Red; continue } if([string]::IsNullOrWhiteSpace($exportPath)) { Write-Host "Required." -ForegroundColor Red; continue }
$backupRoot = $exportPath $backupRoot = $exportPath
} }
else else
{ {
$backupRoot = Read-Host "Backup root path" $backupRoot = Select-FolderPath -Prompt "Backup root path"
if([string]::IsNullOrWhiteSpace($backupRoot)) { Write-Host "Required." -ForegroundColor Red; continue } if([string]::IsNullOrWhiteSpace($backupRoot)) { Write-Host "Required." -ForegroundColor Red; continue }
if(-not (Test-Path $backupRoot)) { Write-Host "Path not found: $backupRoot" -ForegroundColor Red; continue } if(-not (Test-Path $backupRoot)) { Write-Host "Path not found: $backupRoot" -ForegroundColor Red; continue }
} }
$outputDir = Read-Host "Output directory for reports" $outputDir = Select-FolderPath -Prompt "Output directory for reports"
if([string]::IsNullOrWhiteSpace($outputDir)) { Write-Host "Required." -ForegroundColor Red; continue } if([string]::IsNullOrWhiteSpace($outputDir)) { Write-Host "Required." -ForegroundColor Red; continue }
$includeAssignments = $false $includeAssignments = $false
@@ -480,6 +524,105 @@ while($true)
continue continue
} }
if($choiceNumber -eq 23)
{
$defaultRoot = Get-LauncherSetting -SettingsPath $settingsPath -Name "FullExportRoot"
if([string]::IsNullOrWhiteSpace($defaultRoot)) { $defaultRoot = Join-Path $HOME "Local/IntuneExports" }
$root = Select-FolderPath -Prompt "Export root folder" -StartPath $defaultRoot -Default $defaultRoot
if(-not $root) { continue }
Set-LauncherSetting -SettingsPath $settingsPath -Name "FullExportRoot" -Value $root
$tenantLabel = if($currentTenant -and $currentTenant.TenantName) { $currentTenant.TenantName } else { $TenantId }
$safeName = ($tenantLabel -replace '[\\/:*?"<>|\s]+', '-').Trim('-')
$exportPath = Join-Path $root "$safeName-$(Get-Date -Format 'yyMMdd')"
if(Test-Path -LiteralPath $exportPath) { $exportPath = "$exportPath-$(Get-Date -Format 'HHmm')" }
Write-Host "`n Tenant : $tenantLabel ($TenantId)" -ForegroundColor Green
Write-Host " Export path : $exportPath"
Write-Host " Content : all object types, with assignments"
if((Read-Host "`nProceed? [Y/n]") -like 'n*') { continue }
$exportParams = @{ Action = "Export"; TenantId = $TenantId; ExportPath = $exportPath; IncludeAssignments = $true; AuthMode = $AuthMode }
if($AppId) { $exportParams.AppId = $AppId }
if($Secret) { $exportParams.Secret = $Secret }
elseif($Certificate) { $exportParams.Certificate = $Certificate }
if($SettingsFile) { $exportParams.SettingsFile = $SettingsFile }
& (Join-Path $projectRoot "Scripts/Start-HeadlessIntune.ps1") @exportParams
Write-Host "`nExport finished: $exportPath" -ForegroundColor Cyan
# Drift check against the newest earlier export of this tenant in the same root
$python = Get-Command python3 -ErrorAction SilentlyContinue
if(-not $python) { $python = Get-Command python -ErrorAction SilentlyContinue }
$prev = Get-ChildItem -LiteralPath $root -Directory -ErrorAction SilentlyContinue |
Where-Object { $_.Name -like "$safeName-*" -and $_.FullName -ne $exportPath } |
Sort-Object LastWriteTime -Descending | Select-Object -First 1
if($python -and (Test-Path -LiteralPath $exportPath -PathType Container))
{
$prevPath = if($prev) { $prev.FullName } else { $null }
$hint = if($prevPath) { "Enter = $($prev.Name)" } else { "path to an earlier export, Enter to skip" }
$ans = Read-Host "`nCompare with an earlier export to see drift? ($hint, n = skip, b = browse)"
if($ans -like 'n') { $prevPath = $null }
elseif($ans -like 'b') { $prevPath = Select-FolderPath -Prompt "Earlier export to compare with" -StartPath $root }
elseif(-not [string]::IsNullOrWhiteSpace($ans)) { $prevPath = ConvertTo-FullFolderPath $ans }
if($prevPath -and (Test-Path -LiteralPath $prevPath -PathType Container))
{
$prevName = Split-Path $prevPath -Leaf
$curName = Split-Path $exportPath -Leaf
$driftDir = Join-Path (Join-Path $root "_drift") "$prevName-to-$curName"
& $python.Source (Join-Path $projectRoot "Scripts/Compare-Tenants.py") `
--root-a $prevPath --label-a $prevName --root-b $exportPath --label-b $curName `
--include-assignments --output-dir $driftDir
Write-Host "Drift report: $(Join-Path $driftDir 'tenant-comparison.md')" -ForegroundColor Cyan
}
}
Write-Host "`nPress any key to return to the menu..." -ForegroundColor DarkGray
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
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")
{
$browseStart = Get-LauncherSetting -SettingsPath $settingsPath -Name "FullExportRoot"
if([string]::IsNullOrWhiteSpace($browseStart)) { $browseStart = Join-Path $HOME "Local/IntuneExports" }
$root = Select-FolderPath -Prompt "Export folder of tenant $side" -StartPath $browseStart
if([string]::IsNullOrWhiteSpace($root)) { Write-Host "Required." -ForegroundColor Red; $sides = $null; break }
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)"
$browseStart = Split-Path $root -Parent
$sides += ,@($root, $label, $strip)
}
if(-not $sides) { continue }
$outputDir = Select-FolderPath -Prompt "Output directory for the comparison report" -StartPath $browseStart
if([string]::IsNullOrWhiteSpace($outputDir)) { Write-Host "Required." -ForegroundColor Red; continue }
$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) if($choiceNumber -eq 17)
{ {
$defaultBaseline = Join-Path $projectRoot "Baselines/CISM365-v7-Generated.yaml" $defaultBaseline = Join-Path $projectRoot "Baselines/CISM365-v7-Generated.yaml"
@@ -513,6 +656,40 @@ while($true)
continue continue
} }
if($choiceNumber -eq 20)
{
$roleScript = Join-Path $projectRoot "Scripts/Export-EntraRoleMembership.ps1"
$roleParams = @{ TenantId = $TenantId; AuthMode = $AuthMode }
if($AppId) { $roleParams.AppId = $AppId }
if($Secret) { $roleParams.Secret = $Secret }
elseif($Certificate) { $roleParams.Certificate = $Certificate }
if($SettingsFile) { $roleParams.SettingsFile = $SettingsFile }
$csvOut = Read-Host "CSV output path (Enter for default: <TenantName>-Entra-AllRoleMemberships.csv)"
if(-not [string]::IsNullOrWhiteSpace($csvOut)) { $roleParams.CsvPath = $csvOut }
& $roleScript @roleParams
Write-Host "`nPress any key to return to the menu..." -ForegroundColor DarkGray
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
continue
}
if($choiceNumber -eq 19)
{
$caScript = Join-Path $projectRoot "Scripts/Invoke-ConditionalAccessDocumentation.ps1"
$ans = Read-Host "Export to Excel as well? [y/N]"
$doExcel = $ans -like 'y*'
$caParams = @{}
if($doExcel)
{
$caParams.ExportExcel = $true
$xlPath = Read-Host "Excel output path (Enter for default: Scripts/ConditionalAccessDocumentation.xlsx)"
if(-not [string]::IsNullOrWhiteSpace($xlPath)) { $caParams.ExcelPath = $xlPath }
}
& $caScript @caParams
Write-Host "`nPress any key to return to the menu..." -ForegroundColor DarkGray
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
continue
}
if(-not $script) if(-not $script)
{ {
continue continue
+1 -1
View File
@@ -1 +1 @@
4.1.0 4.6.2
Executable
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# Wrapper so the toolkit can be started from a shell without typing pwsh first.
# intune interactive launcher (Start-IntuneToolkit.ps1)
# intune -TenantId <id> ... launcher with parameters
# intune <Script> [args] run Scripts/<Script>.ps1 or .py, e.g.
# intune Export-Policies -TenantId <id> -ExportPath ~/out
# intune Compare-Tenants --root-a A --root-b B
# Symlink it onto your PATH: ln -s "$PWD/intune" ~/.local/bin/intune
set -euo pipefail
src="${BASH_SOURCE[0]}"
while [ -L "$src" ]; do
dir="$(cd -P "$(dirname "$src")" && pwd)"
src="$(readlink "$src")"
[[ "$src" != /* ]] && src="$dir/$src"
done
root="$(cd -P "$(dirname "$src")" && pwd)"
need() { command -v "$1" >/dev/null 2>&1 || { echo "intune: '$1' not found. $2" >&2; exit 127; }; }
if [ $# -gt 0 ] && [[ "$1" != -* ]]; then
name="${1%.ps1}"; name="${name%.py}"; shift
if [ -f "$root/Scripts/$name.py" ]; then
need python3 "Install Python 3."
exec python3 "$root/Scripts/$name.py" "$@"
elif [ -f "$root/Scripts/$name.ps1" ]; then
need pwsh "Install PowerShell 7: brew install powershell"
exec pwsh -NoProfile -File "$root/Scripts/$name.ps1" "$@"
fi
echo "intune: no script 'Scripts/$name.ps1' or '.py'. Available:" >&2
ls "$root/Scripts" | grep -E '\.(ps1|py)$' | grep -v '^_' | sed -E 's/\.(ps1|py)$//' | sort -u | sed 's/^/ /' >&2
exit 2
fi
need pwsh "Install PowerShell 7: brew install powershell"
exec pwsh -NoProfile -File "$root/Start-IntuneToolkit.ps1" "$@"