21 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
19 changed files with 2193 additions and 184 deletions
+15 -3
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,9 +126,11 @@ 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. Includes a `Platform` column and resolves Settings Catalog names 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-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. |
@@ -132,6 +138,7 @@ The launcher caches tenant display names in `Settings.json` so the TUI can show
| `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. |
@@ -230,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.
+112
View File
@@ -1,5 +1,117 @@
# 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 ## 2026-06-23 — v4.2.0 — Entra directory role membership export
### Added ### Added
+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)
{ {
+205 -15
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
if(-not $global:dgObjects.Columns)
{
Show-GraphObjects -FromGraphObjects $graphObjects
}
else
{
$graphObjects | Where-Object { $_ -ne $null } | ForEach-Object { $global:dgObjects.ItemsSource.AddNewItem($_) | Out-Null } $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
if(-not $global:dgObjects.Columns)
{
Show-GraphObjects -FromGraphObjects $graphObjects
}
else
{
$graphObjects | Where-Object { $_ -ne $null } | ForEach-Object { $global:dgObjects.ItemsSource.AddNewItem($_) | Out-Null } $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" = @()
} }
-1
View File
@@ -1529,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 = @{}
+237 -42
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
} }
} }
@@ -3164,21 +3171,44 @@ 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*")
{ {
$global:MigrationTableCache += (New-Object PSObject -Property @{
OriginalId = $migObj.Id
Id = $null
Type = $migObj.Type
Pending = $true
MigObj = $migObj
SearchPattern = $txtSearchPattern
ReplacePattern = $txtReplacePattern
})
}
}
}
}
# 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() $migTableGroupName = $migObj.DisplayName.Trim()
$originalGroupName = $migTableGroupName $originalGroupName = $migTableGroupName
if($txtSearchPattern -and $migTableGroupName -match $txtSearchPattern) if($txtSearchPattern -and $migTableGroupName -match $txtSearchPattern)
{ {
$migTableGroupName = $migTableGroupName -replace $txtSearchPattern, $txtReplacePattern $migTableGroupName = $migTableGroupName -replace $txtSearchPattern, $txtReplacePattern
} }
$obj = (Invoke-GraphRequest "/groups?`$filter=displayName eq '$($migTableGroupName)'").Value
if(-not $obj) $obj = (Invoke-GraphRequest "/groups?`$filter=displayName eq '$($migTableGroupName.Replace("'","''"))'").Value
if($obj)
{ {
return ($obj | Select-Object -First 1)
}
$groupFi = $null $groupFi = $null
if($global:GraphMigrationTable) if($global:GraphMigrationTable)
{ {
@@ -3189,9 +3219,13 @@ function Get-GraphMigrationObjectsFromFile
if($groupFi.Exists -eq $true) if($groupFi.Exists -eq $true)
{ {
# ToDo: Create group from Json (could be a dynamic group) # ToDo: Create group from Json (could be a dynamic group)
# Warn if synched group
$groupObj = Get-GraphObjectFromFile $groupFi.FullName $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. #isAssignableToRole - For Role assignment groupd.
$keepProps = @("displayName","description","mailEnabled","mailNickname","securityEnabled","membershipRule","groupTypes", "membershipRuleProcessingState") $keepProps = @("displayName","description","mailEnabled","mailNickname","securityEnabled","membershipRule","groupTypes", "membershipRuleProcessingState")
foreach($prop in $groupObj.PSObject.Properties) foreach($prop in $groupObj.PSObject.Properties)
@@ -3200,55 +3234,29 @@ function Get-GraphMigrationObjectsFromFile
Remove-Property $groupObj $prop.Name Remove-Property $groupObj $prop.Name
} }
$groupObj.displayName = $groupObj.displayName.Trim() $groupObj.displayName = $migTableGroupName
if($txtSearchPattern -and $groupObj.displayName -match $txtSearchPattern)
{
$groupObj.displayName = $groupObj.displayName -replace $txtSearchPattern, $txtReplacePattern
}
$groupJson = ConvertTo-Json $groupObj -Depth 50 $groupJson = ConvertTo-Json $groupObj -Depth 50
} }
else else
{ {
$groupName = $migTableGroupName Write-Log "No group object found for $migTableGroupName. Creating a cloud group with default settings" 2
Write-Log "No group object found for $groupName. Creating a cloud group with default settings" 2 # Random nickname like the Entra portal creates
$dateStr = ((Get-Date).ToString("yyMMddHHmmss")) $nickName = (New-Guid).Guid.SubString(0,10)
if(($groupName.Length + $dateStr.Length) -gt 64)
{
$nickName = $groupName.Substring(0,(64-$dateStr.Length))
}
else
{
$nickName = $groupName
}
$nickName = $nickName + $dateStr
$groupJson = @" $groupJson = @"
{ {
"displayName": "$($groupName)", "displayName": "$($migTableGroupName)",
"mailEnabled": false, "mailEnabled": false,
"mailNickname": "$($nickName)", "mailNickname": "$($nickName)",
"securityEnabled": true "securityEnabled": true
} }
"@ "@
} }
Write-Log "Create AAD Group $($migTableGroupName)" Write-Log "Create AAD Group $($migTableGroupName)"
Invoke-GraphRequest "/groups" -HttpMethod "POST" -Content $groupJson
$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
})
}
}
}
}
} }
function Update-JsonForEnvironment function Update-JsonForEnvironment
{ {
param($json) param($json)
@@ -3262,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
} }
} }
@@ -3274,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
} }
@@ -3389,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)
@@ -4675,7 +4725,14 @@ function Save-GraphObjectToFile
{ {
param($obj, $fileName) param($obj, $fileName)
if((Get-SettingValue "SortJsonProperties") -eq $true)
{
$json = $obj | ConvertTo-JsonSortedGraph -Depth 50
}
else
{
$json = $obj | ConvertTo-Json -Depth 50 $json = $obj | ConvertTo-Json -Depth 50
}
if($global:Organization.Id) if($global:Organization.Id)
{ {
@@ -4692,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"
{ {
+38 -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.2.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,8 @@ 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 * [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)
@@ -55,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`.
@@ -77,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
@@ -145,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`.
@@ -168,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()
+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"
@@ -393,6 +393,14 @@ try {
$termsOfUseAgreements = @{} $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 # GSA network filtering profiles
try { try {
$networkFilteringProfiles = Invoke-MgGraphRequest -Uri 'https://graph.microsoft.com/beta/networkAccess/filteringProfiles' -Method GET -OutputType PSObject -ErrorAction Stop | $networkFilteringProfiles = Invoke-MgGraphRequest -Uri 'https://graph.microsoft.com/beta/networkAccess/filteringProfiles' -Method GET -OutputType PSObject -ErrorAction Stop |
@@ -441,15 +449,8 @@ foreach ($policy in $conditionalAccessPolicies) {
@($policy.Conditions?.ClientApplications?.IncludeServicePrincipals) | ForEach-Object { $includeServicePrincipals.Add($servicePrincipals.GetOrDefault($_, $_)) } @($policy.Conditions?.ClientApplications?.IncludeServicePrincipals) | ForEach-Object { $includeServicePrincipals.Add($servicePrincipals.GetOrDefault($_, $_)) }
@($policy.Conditions?.ClientApplications?.ExcludeServicePrincipals) | ForEach-Object { $excludeServicePrincipals.Add($servicePrincipals.GetOrDefault($_, $_)) } @($policy.Conditions?.ClientApplications?.ExcludeServicePrincipals) | ForEach-Object { $excludeServicePrincipals.Add($servicePrincipals.GetOrDefault($_, $_)) }
$includeAuthenticationContext = [System.Collections.Generic.List[Object]]::new() $includeAuthenticationContext = @($policy.Conditions?.Applications?.IncludeAuthenticationContextClassReferences) |
@($policy.Conditions?.Applications?.IncludeAuthenticationContextClassReferences) | ForEach-Object { ForEach-Object { $authContextClassReferences.GetOrDefault($_, $_) }
try {
$context = Get-MgIdentityConditionalAccessAuthenticationContextClassReference -Filter "Id eq '$PSItem'" -ErrorAction Stop
if ($context.DisplayName) { $includeAuthenticationContext.Add($context.DisplayName) }
} catch {
$includeAuthenticationContext.Add($PSItem)
}
}
$includeLocations = @($policy.Conditions?.Locations?.IncludeLocations) | ForEach-Object { $namedLocations.GetOrDefault($_, $_) } $includeLocations = @($policy.Conditions?.Locations?.IncludeLocations) | ForEach-Object { $namedLocations.GetOrDefault($_, $_) }
$excludeLocations = @($policy.Conditions?.Locations?.ExcludeLocations) | ForEach-Object { $namedLocations.GetOrDefault($_, $_) } $excludeLocations = @($policy.Conditions?.Locations?.ExcludeLocations) | ForEach-Object { $namedLocations.GetOrDefault($_, $_) }
@@ -493,7 +494,10 @@ foreach ($policy in $conditionalAccessPolicies) {
$includeGuestsOrExternalUserTypes = $policy.Conditions?.Users?.IncludeGuestsOrExternalUsers?.guestOrExternalUserTypes $includeGuestsOrExternalUserTypes = $policy.Conditions?.Users?.IncludeGuestsOrExternalUsers?.guestOrExternalUserTypes
$includeGuestsOrExternalUserTenants = @($policy.Conditions?.Users?.IncludeGuestsOrExternalUsers?.externalTenants?.AdditionalProperties?['members']) $includeGuestsOrExternalUserTenants = @($policy.Conditions?.Users?.IncludeGuestsOrExternalUsers?.externalTenants?.AdditionalProperties?['members'])
$authenticationFlows = @($policy.Conditions?.AuthenticationFlows) $authFlowsObj = $policy.Conditions?.AuthenticationFlows
$authenticationFlows = if ($authFlowsObj) {
$authFlowsObj.TransferMethods ?? $authFlowsObj.AdditionalProperties?['transferMethods']
}
$applicationsAdditional = $null $applicationsAdditional = $null
if ($policy.Conditions?.Applications?.AdditionalProperties) { if ($policy.Conditions?.Applications?.AdditionalProperties) {
@@ -552,7 +556,7 @@ foreach ($policy in $conditionalAccessPolicies) {
ExcludeDeviceStates = (@($excludeDeviceStates) -join $separator) ExcludeDeviceStates = (@($excludeDeviceStates) -join $separator)
IncludeGuestsOrExternalUserTypes = $includeGuestsOrExternalUserTypes IncludeGuestsOrExternalUserTypes = $includeGuestsOrExternalUserTypes
IncludeGuestOrExternalUserTenants = (@($includeGuestsOrExternalUserTenants) -join $separator) IncludeGuestOrExternalUserTenants = (@($includeGuestsOrExternalUserTenants) -join $separator)
AuthenticationFlows = (@($authenticationFlows) -join $separator) AuthenticationFlows = $authenticationFlows
ApplicationsAdditional = $applicationsAdditional ApplicationsAdditional = $applicationsAdditional
ConditionsAdditional = $conditionsAdditional ConditionsAdditional = $conditionsAdditional
IncludeServicePrincipals = ($includeServicePrincipals -join $separator) IncludeServicePrincipals = ($includeServicePrincipals -join $separator)
@@ -647,7 +651,8 @@ if ($ExportExcel) {
@{ Label = 'Device filter mode'; Col = 'DeviceFilterMode' }, @{ Label = 'Device filter mode'; Col = 'DeviceFilterMode' },
@{ Label = 'Device filter rule'; Col = 'DeviceFilterRule' }, @{ Label = 'Device filter rule'; Col = 'DeviceFilterRule' },
@{ Label = 'Sign-in risk'; Col = 'SignInRiskLevels' }, @{ Label = 'Sign-in risk'; Col = 'SignInRiskLevels' },
@{ Label = 'User risk'; Col = 'UserRiskLevels' } @{ Label = 'User risk'; Col = 'UserRiskLevels' },
@{ Label = 'Authentication flows'; Col = 'AuthenticationFlows' }
)}, )},
@{ Title = 'Grant'; Fields = @( @{ Title = 'Grant'; Fields = @(
@{ Label = 'Operator'; Col = 'GrantControlsOperator' }, @{ Label = 'Operator'; Col = 'GrantControlsOperator' },
+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 }
}
}
}
+43 -7
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
if($Action)
{
$action = $Action
}
else
{
$action = Select-MenuItem -Items @("Export","Import","DeployCISBaseline","GenerateReports") -Header "Select action" $action = Select-MenuItem -Items @("Export","Import","DeployCISBaseline","GenerateReports") -Header "Select action"
if(-not $action) { continue } 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
if($TenantId)
{
$tenantId = $TenantId
Write-Host "Tenant: $tenantId" -ForegroundColor DarkGray
}
else
{
$tenantPrompt = "Enter Tenant ID" $tenantPrompt = "Enter Tenant ID"
if($preloadedTenantId) { $tenantPrompt += " (default: $preloadedTenantId)" } if($preloadedTenantId) { $tenantPrompt += " (default: $preloadedTenantId)" }
$tenantId = Read-Host $tenantPrompt $tenantId = Read-Host $tenantPrompt
if([string]::IsNullOrWhiteSpace($tenantId)) { $tenantId = $preloadedTenantId } if([string]::IsNullOrWhiteSpace($tenantId)) { $tenantId = $preloadedTenantId }
if([string]::IsNullOrWhiteSpace($tenantId)) { Write-Host "Tenant ID is required." -ForegroundColor Red; continue } 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"
@@ -242,25 +262,33 @@ while($true)
$exportPath = $null $exportPath = $null
if($dataSource -like "*fresh*") if($dataSource -like "*fresh*")
{
if($TenantId)
{
$tenantIdForReport = $TenantId
Write-Host "Tenant: $tenantIdForReport" -ForegroundColor DarkGray
}
else
{ {
$tenantPrompt = "Enter Tenant ID" $tenantPrompt = "Enter Tenant ID"
if($preloadedTenantId) { $tenantPrompt += " (default: $preloadedTenantId)" } if($preloadedTenantId) { $tenantPrompt += " (default: $preloadedTenantId)" }
$tenantIdForReport = Read-Host $tenantPrompt $tenantIdForReport = Read-Host $tenantPrompt
if([string]::IsNullOrWhiteSpace($tenantIdForReport)) { $tenantIdForReport = $preloadedTenantId } if([string]::IsNullOrWhiteSpace($tenantIdForReport)) { $tenantIdForReport = $preloadedTenantId }
if([string]::IsNullOrWhiteSpace($tenantIdForReport)) { Write-Host "Tenant ID is required." -ForegroundColor Red; continue } 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
if($TenantId)
{
$tenantId = $TenantId
Write-Host "`nTenant: $tenantId" -ForegroundColor DarkGray
}
else
{
$tenantPrompt = "Enter Tenant ID" $tenantPrompt = "Enter Tenant ID"
if($preloadedTenantId) { $tenantPrompt += " (default: $preloadedTenantId)" } if($preloadedTenantId) { $tenantPrompt += " (default: $preloadedTenantId)" }
$tenantId = Read-Host $tenantPrompt $tenantId = Read-Host $tenantPrompt
if([string]::IsNullOrWhiteSpace($tenantId)) { $tenantId = $preloadedTenantId } if([string]::IsNullOrWhiteSpace($tenantId)) { $tenantId = $preloadedTenantId }
if([string]::IsNullOrWhiteSpace($tenantId)) { Write-Host "Tenant ID is required." -ForegroundColor Red; continue } 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 }
+170 -29
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,29 +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
"20. Export Entra role membership" # is assigned automatically, so entries can be added or moved without renumbering anything.
"19. Document Conditional Access policies" $menuDefs = @(
"18. Rotate app secret" # Export / Import
"17. Deploy CIS M365 baseline" @{ Id = 1; Label = "Export policies" }
"16. Generate reports" @{ Id = 2; Label = "Import policies" }
"15. Delete tenant auth and app registration" @{ Id = 23; Label = "Full tenant export (all types + assignments, dated folder)" }
"14. Delete local tenant auth only" @{ Id = 7; Label = "Export assignments to CSV/Markdown" }
"13. Refresh tenant names" @{ Id = 5; Label = "Backup assignments" }
"12. Initialize auth (one-time setup)" @{ Id = 6; Label = "Restore assignments" }
"11. Deploy baseline (dry-run / WhatIf)" # Bulk operations
"10. Deploy baseline" @{ Id = 3; Label = "Bulk app assignment" }
"9. Bulk device operations" @{ Id = 4; Label = "Bulk assignment manager (policies)" }
"8. Bulk rename policies" @{ Id = 8; Label = "Bulk rename policies" }
"7. Export assignments to CSV/Markdown" @{ Id = 21; Label = "Bulk delete policies" }
"6. Restore assignments" @{ Id = 24; Label = "Bulk scope tags (add / replace / remove / clean up)" }
"5. Backup assignments" @{ Id = 9; Label = "Bulk device operations" }
"4. Bulk assignment manager (policies)" # Baselines & compliance
"3. Bulk app assignment" @{ Id = 10; Label = "Deploy baseline" }
"2. Import policies" @{ Id = 11; Label = "Deploy baseline (dry-run / WhatIf)" }
"1. Export policies" @{ Id = 17; Label = "Deploy CIS M365 baseline" }
"0. Exit" @{ 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)
{ {
@@ -358,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)
@@ -371,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" }
@@ -383,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 }
@@ -440,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
@@ -482,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"
+1 -1
View File
@@ -1 +1 @@
4.2.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" "$@"