feat(bulk): add bulk scope tag tool

Scripts/Bulk-ScopeTags.ps1 (menu item 24) adds, replaces or removes scope
tags across object types, optionally filtered by name, or cleans up tag
ids that no longer exist. Shows the plan per type, supports -WhatIf and
-Force, applies changes with batched PATCH requests and skips objects
whose tag list would not change. Design follows upstream 4.0
Set-GraphBulkScopeTags.
This commit is contained in:
2026-11-24 12:27:17 +01:00
parent df3cda9843
commit d55908e975
3 changed files with 473 additions and 0 deletions
+1
View File
@@ -134,6 +134,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/ConvertTo-IntuneBaseline.ps1` | Convert an existing export into a baseline skeleton. |
| `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/Backup-Restore-Assignments.ps1` | Backup and restore assignments across tenants. |
| `Scripts/Bulk-RenamePolicies.ps1` | Search/replace or prefix policy names and descriptions. |
+470
View File
@@ -0,0 +1,470 @@
#requires -Version 5.1
<#
.SYNOPSIS
Bulk add, replace or remove scope tags on Intune objects, or clean up orphaned tag references.
.DESCRIPTION
Pick an action, the scope tags and the object types (optionally filtered by name).
The script computes the new scope tag list per object, shows what would change and
applies it with PATCH requests (batched, 20 per call). Objects whose list would not
change are skipped. Supports -WhatIf.
Actions
Add add the selected tags to each object
Replace set each object's tags to exactly the selected tags
Remove remove the selected tags from each object
CleanupOrphans remove tag ids that no longer exist in the tenant (no tags needed)
-CleanupOrphans can also be combined with Add/Replace/Remove.
.EXAMPLE
./Scripts/Bulk-ScopeTags.ps1 -TenantId <id> -WhatIf
.EXAMPLE
./Scripts/Bulk-ScopeTags.ps1 -TenantId <id> -Action Add -ScopeTags "Helpdesk" -ObjectTypes "Settings Catalog","Compliance Policies" -NameFilter "Win - " -Force
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$TenantId,
[string]$AppId,
[string]$Secret,
[string]$Certificate,
[ValidateSet("AppOnly","Browser","DeviceCode")]
[string]$AuthMode = "AppOnly",
[string]$RedirectUri,
[string]$SettingsFile,
[ValidateSet("Add","Replace","Remove","CleanupOrphans")]
[string]$Action,
# Scope tag names or ids ("0" or "Default" for the default tag)
[string[]]$ScopeTags,
# Object type titles, e.g. "Settings Catalog". Default: ask (interactive) or all
[string[]]$ObjectTypes,
# Literal, case-insensitive substring of the object name
[string]$NameFilter,
# Also remove tag ids that no longer exist in the tenant
[switch]$CleanupOrphans,
# Skip the confirmation prompt
[switch]$Force,
[switch]$WhatIf
)
$ErrorActionPreference = "Stop"
#region Helper functions
function Test-FzfAvailable
{
return [bool](Get-Command fzf -ErrorAction SilentlyContinue)
}
function Show-FzfMenu
{
param(
[Parameter(Mandatory)]
[string[]]$Items,
[string]$Header = "Select one",
[switch]$Multi
)
$argsList = @("--header=$Header")
if($Multi) { $argsList += "--multi" }
$selected = $Items | fzf @argsList
if(-not $selected) { return $null }
if($Multi) { return @($selected -split "`r?`n" | Where-Object { $_ }) }
return $selected
}
function Show-NumberedMenu
{
param(
[Parameter(Mandatory)]
[string[]]$Items,
[string]$Header = "Select one or more",
[switch]$Multi
)
Write-Host "`n$Header" -ForegroundColor Cyan
for($i=0; $i -lt $Items.Count; $i++)
{
Write-Host " $($i+1). $($Items[$i])"
}
if($Multi)
{
$prompt = "Enter numbers separated by commas (e.g. 1,3,5) or 'all'"
}
else
{
$prompt = "Enter a number"
}
$choice = Read-Host $prompt
if($choice -eq "all" -and $Multi) { return $Items }
$indices = $choice -split "," | ForEach-Object { $_.Trim() } | Where-Object { $_ -match "^\d+$" } | ForEach-Object { [int]$_ - 1 } | Where-Object { $_ -ge 0 -and $_ -lt $Items.Count }
if($Multi)
{
return $Items[$indices] | Select-Object -Unique
}
else
{
if($indices.Count -eq 0) { return $null }
return $Items[$indices[0]]
}
}
function Select-MenuItem
{
param(
[Parameter(Mandatory)]
[string[]]$Items,
[string]$Header = "Select one",
[switch]$Multi
)
if(Test-FzfAvailable)
{
return Show-FzfMenu -Items $Items -Header $Header -Multi:$Multi
}
return Show-NumberedMenu -Items $Items -Header $Header -Multi:$Multi
}
function Get-DefaultSettingsPath
{
if($IsWindows -or $env:OS -eq "Windows_NT")
{
if($env:LOCALAPPDATA) { return (Join-Path $env:LOCALAPPDATA "macOS_IntuneManagement\Settings.json") }
return (Join-Path $env:USERPROFILE "AppData\Local\macOS_IntuneManagement\Settings.json")
}
if($IsMacOS) { return (Join-Path $HOME "Library/Application Support/macOS_IntuneManagement/Settings.json") }
return (Join-Path $HOME ".local/share/macOS_IntuneManagement/Settings.json")
}
#endregion
#region Initialize Runtime
$projectRoot = Split-Path -Parent $PSScriptRoot
$runtimeModule = Join-Path $projectRoot "Runtime/IntuneManagement.Runtime.psd1"
if(-not (Test-Path $runtimeModule))
{
throw "Could not find IntuneManagement.Runtime.psd1 in $projectRoot"
}
$settingsPath = $SettingsFile
if(-not $settingsPath)
{
$settingsPath = Get-DefaultSettingsPath
}
# Pre-load auth from settings
if($AuthMode -eq "AppOnly" -and (Test-Path $settingsPath) -and (-not $AppId -or (-not $Secret -and -not $Certificate)))
{
try
{
$raw = Get-Content -Path $settingsPath -Raw -ErrorAction Stop
$settingsObj = ConvertFrom-Json $raw -AsHashtable -ErrorAction Stop
if($settingsObj -and $settingsObj.ContainsKey($TenantId))
{
$tenantNode = $settingsObj[$TenantId]
if(-not $AppId -and $tenantNode.ContainsKey("GraphAzureAppId"))
{
$AppId = $tenantNode["GraphAzureAppId"]
}
if(-not $Secret -and $tenantNode.ContainsKey("GraphAzureAppSecret"))
{
$Secret = $tenantNode["GraphAzureAppSecret"]
}
if(-not $Certificate -and $tenantNode.ContainsKey("GraphAzureAppCert"))
{
$Certificate = $tenantNode["GraphAzureAppCert"]
}
}
if(-not $Secret -and $IsMacOS -and $AppId)
{
try
{
$keychainSecret = security find-generic-password -a "IntuneManagement" -s "IntuneMgmt-$AppId" -w 2>$null
if($keychainSecret) { $Secret = $keychainSecret }
}
catch { }
}
}
catch { }
}
$invokeParams = @{
Silent = $true
JSonSettings = $true
JSonFile = $settingsPath
TenantId = $TenantId
AppId = $AppId
AuthMode = $AuthMode
}
if($RedirectUri) { $invokeParams.RedirectUri = $RedirectUri }
if($AuthMode -eq "AppOnly" -and $Secret) { $invokeParams.Secret = $Secret }
elseif($AuthMode -eq "AppOnly") { $invokeParams.Certificate = $Certificate }
Import-Module $runtimeModule -Force
Initialize-IntuneManagementRuntime -View "IntuneGraphAPI" @invokeParams
#endregion
#region Ensure Graph connectivity
if(-not (Get-Command Invoke-GraphRequest -ErrorAction SilentlyContinue))
{
throw "Graph runtime did not load Invoke-GraphRequest. Aborting."
}
Write-Host "`nConnecting to Microsoft Graph..." -ForegroundColor Cyan
try
{
$org = Invoke-GraphRequest "/organization"
Write-Host "Connected to tenant: $($org.value[0].displayName) ($($org.value[0].id))" -ForegroundColor Green
}
catch
{
throw "Failed to connect to Graph. Ensure auth parameters are correct. Error: $_"
}
#endregion
#region Object types that support scope tags
# PATCH needs @odata.type for derived types; it is taken from the listed object.
$scopeTagTypes = @(
[PSCustomObject]@{ Title = "Applications"; API = "/deviceAppManagement/mobileApps"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Device Configuration"; API = "/deviceManagement/deviceConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Settings Catalog"; API = "/deviceManagement/configurationPolicies"; NameProp = "name" },
[PSCustomObject]@{ Title = "Compliance Policies"; API = "/deviceManagement/deviceCompliancePolicies"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Compliance Policies - V2"; API = "/deviceManagement/compliancePolicies"; NameProp = "name" },
[PSCustomObject]@{ Title = "Administrative Templates"; API = "/deviceManagement/groupPolicyConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Endpoint Security (Intents)"; API = "/deviceManagement/intents"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "App Configuration (Device)"; API = "/deviceAppManagement/mobileAppConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Platform Scripts"; API = "/deviceManagement/deviceManagementScripts"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "macOS Scripts"; API = "/deviceManagement/deviceShellScripts"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Device Health Scripts"; API = "/deviceManagement/deviceHealthScripts"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "macOS Custom Attributes"; API = "/deviceManagement/deviceCustomAttributeShellScripts"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Enrollment Configurations"; API = "/deviceManagement/deviceEnrollmentConfigurations"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Autopilot"; API = "/deviceManagement/windowsAutopilotDeploymentProfiles"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Terms and Conditions"; API = "/deviceManagement/termsAndConditions"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Policy Sets"; API = "/deviceAppManagement/policySets"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Feature Updates"; API = "/deviceManagement/windowsFeatureUpdateProfiles"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Quality Updates (Profiles)"; API = "/deviceManagement/windowsQualityUpdateProfiles"; NameProp = "displayName" },
[PSCustomObject]@{ Title = "Driver Update Profiles"; API = "/deviceManagement/windowsDriverUpdateProfiles"; NameProp = "displayName" }
)
#endregion
#region Helpers
function Get-ScopeTagPlan
{
<# Returns the new tag id list for one object, or $null when nothing changes #>
param([string[]]$Current, [string]$Action, [string[]]$Selected, [string[]]$ValidIds, [bool]$Cleanup)
$new = [System.Collections.Generic.List[string]]::new()
switch($Action)
{
"Add" { $new.AddRange([string[]]@($Current + $Selected | Select-Object -Unique)) }
"Replace" { $new.AddRange([string[]]@($Selected | Select-Object -Unique)) }
"Remove" { $new.AddRange([string[]]@($Current | Where-Object { $_ -notin $Selected })) }
"CleanupOrphans" { $new.AddRange([string[]]@($Current)) }
}
if($Cleanup -or $Action -eq "CleanupOrphans")
{
$keep = @($new | Where-Object { $_ -in $ValidIds })
$new = [System.Collections.Generic.List[string]]::new()
if($keep.Count -gt 0) { $new.AddRange([string[]]$keep) }
}
# An object always needs at least the Default tag
if($new.Count -eq 0) { $new.Add("0") }
$same = ($new.Count -eq @($Current).Count) -and (@($new | Where-Object { $_ -notin $Current }).Count -eq 0)
if($same) { return $null }
return @($new)
}
# Self-check of the planning rules; runs on every start, costs nothing
$valid = @("0","a","b")
if((Get-ScopeTagPlan @("0") "Add" @("a") $valid $false) -join "," -ne "0,a") { throw "ScopeTag plan self-check failed: Add" }
if((Get-ScopeTagPlan @("0","a") "Remove" @("a") $valid $false) -join "," -ne "0") { throw "ScopeTag plan self-check failed: Remove" }
if((Get-ScopeTagPlan @("a") "Remove" @("a") $valid $false) -join "," -ne "0") { throw "ScopeTag plan self-check failed: Remove-last falls back to Default" }
if((Get-ScopeTagPlan @("0","x") "CleanupOrphans" @() $valid $false) -join "," -ne "0") { throw "ScopeTag plan self-check failed: Cleanup" }
if($null -ne (Get-ScopeTagPlan @("0","a") "Add" @("a") $valid $false)) { throw "ScopeTag plan self-check failed: no-op" }
#endregion
Clear-Host
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Intune Bulk Scope Tags" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
#region Scope tag catalog
$tagResponse = Invoke-GraphRequest "/deviceManagement/roleScopeTags" -AllPages
$tagCatalog = @([PSCustomObject]@{ id = "0"; displayName = "Default" }) + @($tagResponse.value | Where-Object { $_ -and "$($_.id)" -ne "0" } | ForEach-Object { [PSCustomObject]@{ id = "$($_.id)"; displayName = $_.displayName } })
$validTagIds = @($tagCatalog | ForEach-Object { $_.id })
#endregion
#region Action
if(-not $Action)
{
$Action = Select-MenuItem -Items @("Add","Replace","Remove","CleanupOrphans") -Header "Select action"
if(-not $Action) { Write-Host "Cancelled." -ForegroundColor Yellow; exit 0 }
}
#endregion
#region Scope tags
$selectedTagIds = @()
if($Action -ne "CleanupOrphans")
{
if($ScopeTags)
{
foreach($t in $ScopeTags)
{
$match = $tagCatalog | Where-Object { $_.id -eq $t -or $_.displayName -eq $t } | Select-Object -First 1
if(-not $match) { throw "Scope tag '$t' not found. Available: $(($tagCatalog | ForEach-Object { $_.displayName }) -join ', ')" }
$selectedTagIds += $match.id
}
}
else
{
$labels = $tagCatalog | ForEach-Object { "$($_.displayName) [$($_.id)]" }
$picked = Select-MenuItem -Items $labels -Header "Select scope tags (multi-select)" -Multi
if(-not $picked) { Write-Host "No scope tags selected. Exiting." -ForegroundColor Yellow; exit 0 }
$selectedTagIds = @($picked | ForEach-Object { $_ -replace '.*\[(.*?)\]$', '$1' })
}
}
#endregion
#region Object types
if($ObjectTypes)
{
$targetTypes = @($scopeTagTypes | Where-Object { $_.Title -in $ObjectTypes })
$unknown = @($ObjectTypes | Where-Object { $_ -notin $scopeTagTypes.Title })
if($unknown.Count -gt 0) { throw "Unknown object type(s): $($unknown -join ', '). Available: $(($scopeTagTypes.Title) -join ', ')" }
}
else
{
$picked = Select-MenuItem -Items (@("[All types]") + @($scopeTagTypes.Title)) -Header "Select object types (multi-select)" -Multi
if(-not $picked) { Write-Host "No object types selected. Exiting." -ForegroundColor Yellow; exit 0 }
$targetTypes = if($picked -contains "[All types]") { $scopeTagTypes } else { @($scopeTagTypes | Where-Object { $_.Title -in $picked }) }
}
if(-not $PSBoundParameters.ContainsKey("NameFilter") -and -not $ObjectTypes)
{
$NameFilter = Read-Host "`nFilter by name (literal text, Enter for all)"
}
#endregion
#region Plan
$plan = @()
foreach($type in $targetTypes)
{
Write-Host "Reading $($type.Title) ..." -ForegroundColor DarkGray
try
{
$resp = Invoke-GraphRequest "$($type.API)?`$select=id,$($type.NameProp),roleScopeTagIds" -AllPages
}
catch
{
Write-Host " Skipped $($type.Title): $($_.Exception.Message)" -ForegroundColor Yellow
continue
}
foreach($o in @($resp.value | Where-Object { $_ }))
{
$name = [string]$o."$($type.NameProp)"
if($NameFilter -and $name.IndexOf($NameFilter, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
if(-not ($o.PSObject.Properties | Where-Object Name -eq "roleScopeTagIds")) { continue }
$current = @($o.roleScopeTagIds | ForEach-Object { "$_" })
$newIds = Get-ScopeTagPlan -Current $current -Action $Action -Selected $selectedTagIds -ValidIds $validTagIds -Cleanup $CleanupOrphans.IsPresent
if($null -eq $newIds) { continue }
$plan += [PSCustomObject]@{ Type = $type; Id = $o.id; Name = $name; ODataType = $o.'@odata.type'; Old = $current; New = $newIds }
}
}
if($plan.Count -eq 0)
{
Write-Host "`nNothing to change." -ForegroundColor Green
exit 0
}
$tagName = @{}; foreach($t in $tagCatalog) { $tagName[$t.id] = $t.displayName }
function Format-Tags { param($ids) ($ids | ForEach-Object { if($tagName.ContainsKey($_)) { $tagName[$_] } else { "<missing $_>" } }) -join ", " }
Write-Host "`n$($plan.Count) object(s) will change ($Action):" -ForegroundColor Cyan
foreach($g in ($plan | Group-Object { $_.Type.Title }))
{
Write-Host " $($g.Name): $($g.Count)" -ForegroundColor White
foreach($p in ($g.Group | Select-Object -First 5))
{
Write-Host " $($p.Name): [$(Format-Tags $p.Old)] -> [$(Format-Tags $p.New)]" -ForegroundColor DarkGray
}
if($g.Count -gt 5) { Write-Host " ... $($g.Count - 5) more" -ForegroundColor DarkGray }
}
#endregion
if($WhatIf)
{
Write-Host "`nWHATIF: no changes made." -ForegroundColor Magenta
exit 0
}
if(-not $Force)
{
if((Read-Host "`nApply these changes? [y/N]") -notlike 'y*') { Write-Host "Cancelled." -ForegroundColor Yellow; exit 0 }
}
#region Apply
$updated = 0; $failed = 0
$canBatch = [bool](Get-Command Invoke-GraphBatchRequest -ErrorAction SilentlyContinue)
for($i = 0; $i -lt $plan.Count; $i += 20)
{
$chunk = @($plan[$i..([Math]::Min($i + 19, $plan.Count - 1))])
$requests = @(); $n = 1
foreach($p in $chunk)
{
$body = [ordered]@{ roleScopeTagIds = @($p.New) }
if($p.ODataType) { $body['@odata.type'] = $p.ODataType }
$requests += [PSCustomObject]@{
id = "$n"; method = "PATCH"; url = "$($p.Type.API)/$($p.Id)"
body = [PSCustomObject]$body
headers = @{ "Content-Type" = "application/json"; "If-Match" = "*" }
}
$n++
}
if($canBatch)
{
$results = @(Invoke-GraphBatchRequest $requests "BulkScopeTags" -IncludedFailed -SkipWarnings)
foreach($r in $results)
{
$p = $chunk[[int]$r.id - 1]
if([int]$r.status -ge 200 -and [int]$r.status -lt 300) { $updated++; Write-Host " OK: $($p.Name)" -ForegroundColor Green }
else
{
$failed++
$msg = if($r.body.error.message) { $r.body.error.message } else { "" }
Write-Host " ERROR: $($p.Name) - HTTP $($r.status) $msg" -ForegroundColor Red
}
}
$missing = $chunk.Count - $results.Count
if($missing -gt 0) { $failed += $missing; Write-Host " ERROR: $missing request(s) in this batch returned no response" -ForegroundColor Red }
}
else
{
foreach($rq in $requests)
{
$p = $chunk[[int]$rq.id - 1]
try
{
$null = Invoke-GraphRequest $rq.url -HttpMethod PATCH -Content ($rq.body | ConvertTo-Json -Depth 5)
$updated++; Write-Host " OK: $($p.Name)" -ForegroundColor Green
}
catch { $failed++; Write-Host " ERROR: $($p.Name) - $($_.Exception.Message)" -ForegroundColor Red }
}
}
}
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host " Bulk Scope Tags Complete" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Updated : $updated"
Write-Host " Failed : $failed"
#endregion
+2
View File
@@ -339,6 +339,7 @@ $menuItems = @(
"4. Bulk assignment manager (policies)"
"8. Bulk rename policies"
"21. Bulk delete policies"
"24. Bulk scope tags (add / replace / remove / clean up)"
"9. Bulk device operations"
# Baselines & compliance
"10. Deploy baseline"
@@ -399,6 +400,7 @@ while($true)
7 { $script = "Scripts/Export-AssignmentsToCsv.ps1" }
8 { $script = "Scripts/Bulk-RenamePolicies.ps1" }
21 { $script = "Scripts/Bulk-DeletePolicies.ps1" }
24 { $script = "Scripts/Bulk-ScopeTags.ps1" }
9 { $script = "Scripts/Bulk-DeviceOperations.ps1" }
10 { $script = "Scripts/Deploy-IntuneBaseline.ps1" }
11 { $script = "Scripts/Deploy-IntuneBaseline.ps1" }