Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad3b53026c | ||
|
|
cd0d516951 | ||
|
|
57917e9183 | ||
|
|
f2f200f904 | ||
|
|
e964813ffe | ||
|
|
d55908e975 | ||
|
|
df3cda9843 | ||
|
|
0302286505 | ||
|
|
523311700d | ||
|
|
77440ffe36 | ||
|
|
b8e333f92d | ||
|
|
1733c22c86 | ||
|
|
5d8e387288 | ||
|
|
7e1349f1c9 | ||
|
|
37ac448d94 |
@@ -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.
|
||||||
|
|||||||
@@ -1,5 +1,79 @@
|
|||||||
# 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
|
## 2026-08-07 — v4.4.1 — Reorder TUI menu into logical groups
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|||||||
@@ -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
@@ -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" = @()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
@@ -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)
|
||||||
|
|||||||
@@ -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"
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -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.4.1` — 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,6 +161,7 @@ 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`.
|
* **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.
|
||||||
@@ -153,10 +170,27 @@ pwsh ./Scripts/Start-HeadlessIntune.ps1 `
|
|||||||
* **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`.
|
||||||
@@ -169,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`.
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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()
|
||||||
@@ -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"
|
||||||
|
|||||||
@@ -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 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -107,40 +107,7 @@ function Select-MenuItem
|
|||||||
return Show-NumberedMenu -Items $Items -Header $Header -Multi:$Multi
|
return Show-NumberedMenu -Items $Items -Header $Header -Multi:$Multi
|
||||||
}
|
}
|
||||||
|
|
||||||
function Select-FolderPath
|
. (Join-Path $PSScriptRoot "Select-FolderPath.ps1")
|
||||||
{
|
|
||||||
param(
|
|
||||||
[Parameter(Mandatory)]
|
|
||||||
[string]$Prompt,
|
|
||||||
[string]$StartPath = (Get-Location).Path
|
|
||||||
)
|
|
||||||
if(-not (Test-FzfAvailable))
|
|
||||||
{
|
|
||||||
return Read-Host $Prompt
|
|
||||||
}
|
|
||||||
|
|
||||||
$current = if(Test-Path -LiteralPath $StartPath) { (Resolve-Path -LiteralPath $StartPath).Path } else { (Get-Location).Path }
|
|
||||||
|
|
||||||
while($true)
|
|
||||||
{
|
|
||||||
$entries = @("[Use this folder]", "[Type path manually]")
|
|
||||||
$parent = Split-Path -Path $current -Parent
|
|
||||||
if($parent) { $entries += ".." }
|
|
||||||
$subdirs = Get-ChildItem -LiteralPath $current -Directory -ErrorAction SilentlyContinue | Sort-Object Name | ForEach-Object { "$($_.Name)/" }
|
|
||||||
$entries += $subdirs
|
|
||||||
|
|
||||||
$choice = $entries | fzf --header="$Prompt [current: $current]"
|
|
||||||
if(-not $choice) { return $null }
|
|
||||||
|
|
||||||
switch ($choice)
|
|
||||||
{
|
|
||||||
"[Use this folder]" { return $current }
|
|
||||||
"[Type path manually]" { $typed = Read-Host "Enter path"; if(-not [string]::IsNullOrWhiteSpace($typed)) { return $typed }; continue }
|
|
||||||
".." { $current = $parent; continue }
|
|
||||||
default { $current = Join-Path $current ($choice.TrimEnd('/')); continue }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Read-YesNo
|
function Read-YesNo
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -52,6 +52,8 @@ param(
|
|||||||
|
|
||||||
[switch]$ReplaceDependencyIds,
|
[switch]$ReplaceDependencyIds,
|
||||||
|
|
||||||
|
[switch]$NoBatchApi,
|
||||||
|
|
||||||
[switch]$Interactive,
|
[switch]$Interactive,
|
||||||
|
|
||||||
# GenerateReports params
|
# GenerateReports params
|
||||||
@@ -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 }
|
||||||
|
|||||||
+160
-27
@@ -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)
|
||||||
@@ -307,35 +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
|
||||||
|
# is assigned automatically, so entries can be added or moved without renumbering anything.
|
||||||
|
$menuDefs = @(
|
||||||
# Export / Import
|
# Export / Import
|
||||||
"1. Export policies"
|
@{ Id = 1; Label = "Export policies" }
|
||||||
"2. Import policies"
|
@{ Id = 2; Label = "Import policies" }
|
||||||
"7. Export assignments to CSV/Markdown"
|
@{ Id = 23; Label = "Full tenant export (all types + assignments, dated folder)" }
|
||||||
"5. Backup assignments"
|
@{ Id = 7; Label = "Export assignments to CSV/Markdown" }
|
||||||
"6. Restore assignments"
|
@{ Id = 5; Label = "Backup assignments" }
|
||||||
|
@{ Id = 6; Label = "Restore assignments" }
|
||||||
# Bulk operations
|
# Bulk operations
|
||||||
"3. Bulk app assignment"
|
@{ Id = 3; Label = "Bulk app assignment" }
|
||||||
"4. Bulk assignment manager (policies)"
|
@{ Id = 4; Label = "Bulk assignment manager (policies)" }
|
||||||
"8. Bulk rename policies"
|
@{ Id = 8; Label = "Bulk rename policies" }
|
||||||
"21. Bulk delete policies"
|
@{ Id = 21; Label = "Bulk delete policies" }
|
||||||
"9. Bulk device operations"
|
@{ Id = 24; Label = "Bulk scope tags (add / replace / remove / clean up)" }
|
||||||
|
@{ Id = 9; Label = "Bulk device operations" }
|
||||||
# Baselines & compliance
|
# Baselines & compliance
|
||||||
"10. Deploy baseline"
|
@{ Id = 10; Label = "Deploy baseline" }
|
||||||
"11. Deploy baseline (dry-run / WhatIf)"
|
@{ Id = 11; Label = "Deploy baseline (dry-run / WhatIf)" }
|
||||||
"17. Deploy CIS M365 baseline"
|
@{ Id = 17; Label = "Deploy CIS M365 baseline" }
|
||||||
"19. Document Conditional Access policies"
|
@{ Id = 19; Label = "Document Conditional Access policies" }
|
||||||
# Reporting
|
# Reporting
|
||||||
"16. Generate reports"
|
@{ Id = 16; Label = "Generate reports" }
|
||||||
"20. Export Entra role membership"
|
@{ Id = 20; Label = "Export Entra role membership" }
|
||||||
|
@{ Id = 22; Label = "Compare two tenant exports (offline)" }
|
||||||
# Tenant & auth admin
|
# Tenant & auth admin
|
||||||
"12. Initialize auth (one-time setup)"
|
@{ Id = 12; Label = "Initialize auth (one-time setup)" }
|
||||||
"13. Refresh tenant names"
|
@{ Id = 13; Label = "Refresh tenant names" }
|
||||||
"18. Rotate app secret"
|
@{ Id = 18; Label = "Rotate app secret" }
|
||||||
"14. Delete local tenant auth only"
|
@{ Id = 14; Label = "Delete local tenant auth only" }
|
||||||
"15. Delete tenant auth and app registration"
|
@{ Id = 15; Label = "Delete tenant auth and app registration" }
|
||||||
"0. Exit"
|
|
||||||
)
|
)
|
||||||
|
$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)
|
||||||
{
|
{
|
||||||
@@ -364,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)
|
||||||
@@ -378,6 +411,7 @@ while($true)
|
|||||||
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" }
|
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" }
|
||||||
@@ -448,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
|
||||||
@@ -490,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"
|
||||||
|
|||||||
@@ -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" "$@"
|
||||||
Reference in New Issue
Block a user