-
-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathIntuneAssignmentChecker.ps1
More file actions
8729 lines (7817 loc) · 503 KB
/
IntuneAssignmentChecker.ps1
File metadata and controls
8729 lines (7817 loc) · 503 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Requires -Version 7.0
#Requires -Modules Microsoft.Graph.Authentication
<#PSScriptInfo
.VERSION 3.8.1
.GUID c6e25ec6-5787-45ef-95af-8abeb8a17daf
.AUTHOR ugurk
.PROJECTURI https://github.com/ugurkocde/IntuneAssignmentChecker
.DESCRIPTION
This script enables IT administrators to efficiently analyze and audit Intune assignments. It checks assignments for specific users, groups, or devices, displays all policies and their assignments, identifies unassigned policies, detects empty groups in assignments, and searches for specific settings across policies.
.RELEASENOTES
Version 3.8.1:
- Add Platform filter dropdown to HTML report (Fixes #103)
Version 3.8.0:
- Handle multiple Entra ID devices with the same display name with interactive selection (Fixes #94)
- Support device lookup by Object ID (GUID) to bypass display name ambiguity
- Add Scope Tag filter dropdown to HTML report (Fixes #85, #96)
- Add Platform column to "All Policies & Apps" tab in HTML report (Fixes #96)
- Fix Assignment Type filter targeting wrong column in HTML report
Version 3.7.1:
- Fixed macOS policies not being returned in group checks (Fixes #92)
- Added CloudPC.Read.All scope for Windows 365 provisioning policies (Fixes #89)
- Fixed Cloud PC provisioning policies URI format and suppressed W365 warnings for unlicensed tenants (Fixes #88)
- Fixed App Protection Policies not being reported (Fixes #69)
- Fixed CSV/Excel export to include app assignments (Required, Available, Uninstall) (Fixes #93)
- Fixed HTML export path issues on Windows (System32) and macOS (Fixes #83, #81)
- Fixed CSV export dialog hanging on macOS/Linux - now cross-platform (Fixes #43)
- Disk encryption profiles now work correctly (Fixes #77)
- Improved 403 permission error messages with specific scope guidance (Fixes #30)
Version 3.4.5:
- Added tenant switching capability - users can now disconnect and connect to a different tenant without restarting the script
- Menu now displays current connected tenant name and logged-in user
- New menu option [12] to switch between tenants mid-session
Version 3.4.4:
- Fix Permission Error for Health Scripts
Version 3.4.3:
- Fixed critical assignment accuracy issues affecting group policy checks (Fixes #79, #80)
- Resolved Settings Catalog policies not showing in group assignments (Fixes #80)
- Fixed Compare Groups to properly detect and display excluded assignments with [EXCLUDED] tag (Fixes #44)
- Improved assignment processing to handle ALL assignments instead of just first one
- Enhanced exclusion detection in group comparison feature
Version 3.4.2:
- Fixed Android policy detection - now properly identifies and displays Android platform policies (Fixes #86)
- Fixed assignment accuracy - now shows ALL assigned groups instead of just the first one (Fixes #87)
- Fixed exclusion group names - now displays actual group names instead of generic "Group Exclusion" (Fixes #63, #84)
- Added platform detection for all device configuration and compliance policies
- Improved assignment processing to handle multiple assignments correctly
- Enhanced group name resolution for all assignment types
Version 3.4.1:
- Updated release date
Version 3.4.0:
- NEW: Added "Show All Failed Assignments" feature (option 11) to display policy deployment failures
- Added support for Windows 365 Cloud PC Provisioning Policies and User Settings
- Updated HTML export to include these new policy types
- Enhanced assignment checking functionality
- Removed deprecated Administrative Templates option (was option 10)
- Renumbered menu options: Compare Groups is now option 10
Version 3.3.3:
- Fixed HTML Export bug (#70)
- Added display for Autopilot and Enrollment Status Page profiles
Version 3.3.2:
- Added support for Endpoint Security tab (Antivirus profiles, Disk Encryption, etc.)
- Added Autopilot deployment profiles and ESP assignment checks
#>
param(
[Parameter(Mandatory = $false, HelpMessage = "Check assignments for specific users")]
[switch]$CheckUser,
[Parameter(Mandatory = $false, HelpMessage = "User Principal Names to check, comma-separated")]
[string]$UserPrincipalNames,
[Parameter(Mandatory = $false, HelpMessage = "Check assignments for specific groups")]
[switch]$CheckGroup,
[Parameter(Mandatory = $false, HelpMessage = "Check assignments for specific devices")]
[switch]$CheckDevice,
[Parameter(Mandatory = $false, HelpMessage = "Device names to check, comma-separated")]
[string]$DeviceNames,
[Parameter(Mandatory = $false, HelpMessage = "Show all policies and their assignments")]
[switch]$ShowAllPolicies,
[Parameter(Mandatory = $false, HelpMessage = "Show all 'All Users' assignments")]
[switch]$ShowAllUsersAssignments,
[Parameter(Mandatory = $false, HelpMessage = "Show all 'All Devices' assignments")]
[switch]$ShowAllDevicesAssignments,
[Parameter(Mandatory = $false, HelpMessage = "Skip execution - used for testing")]
[switch]$SkipExecution,
[Parameter(Mandatory = $false, HelpMessage = "Generate HTML report")]
[switch]$GenerateHTMLReport,
[Parameter(Mandatory = $false, HelpMessage = "Show policies and apps without assignments")]
[switch]$ShowPoliciesWithoutAssignments,
[Parameter(Mandatory = $false, HelpMessage = "Check for empty groups in assignments")]
[switch]$CheckEmptyGroups,
[Parameter(Mandatory = $false, HelpMessage = "Show all failed assignments")]
[switch]$ShowFailedAssignments,
[Parameter(Mandatory = $false, HelpMessage = "Compare assignments between groups")]
[switch]$CompareGroups,
[Parameter(Mandatory = $false, HelpMessage = "Groups to compare assignments between, comma-separated")]
[string]$CompareGroupNames,
[Parameter(Mandatory = $false, HelpMessage = "Export results to CSV")]
[switch]$ExportToCSV,
[Parameter(Mandatory = $false, HelpMessage = "Path for the exported CSV file")]
[string]$ExportPath,
[Parameter(Mandatory = $false, HelpMessage = "App ID for authentication")]
[string]$AppId,
[Parameter(Mandatory = $false, HelpMessage = "Tenant ID for authentication")]
[string]$TenantId,
[Parameter(Mandatory = $false, HelpMessage = "Certificate Thumbprint for authentication")]
[string]$CertificateThumbprint,
[Parameter(Mandatory = $false, HelpMessage = "Client Secret for authentication")]
[string]$ClientSecret,
[Parameter(Mandatory = $false, HelpMessage = "Environment (Global, USGov, USGovDoD)")]
[ValidateSet("Global", "USGov", "USGovDoD")]
[string]$Environment = "Global",
[Parameter(Mandatory = $false, HelpMessage = "Include assignments inherited from parent groups")]
[switch]$IncludeNestedGroups,
[Parameter(Mandatory = $false, HelpMessage = "Filter results by scope tag name")]
[string]$ScopeTagFilter
)
# Check if any command-line parameters were provided
$parameterMode = $false
$selectedOption = $null
if ($CheckUser) { $parameterMode = $true; $selectedOption = '1' }
elseif ($CheckGroup) { $parameterMode = $true; $selectedOption = '2' }
elseif ($CheckDevice) { $parameterMode = $true; $selectedOption = '3' }
elseif ($ShowAllPolicies) { $parameterMode = $true; $selectedOption = '4' }
elseif ($ShowAllUsersAssignments) { $parameterMode = $true; $selectedOption = '5' }
elseif ($ShowAllDevicesAssignments) { $parameterMode = $true; $selectedOption = '6' }
elseif ($GenerateHTMLReport) { $parameterMode = $true; $selectedOption = '7' }
elseif ($ShowPoliciesWithoutAssignments) { $parameterMode = $true; $selectedOption = '8' }
elseif ($CheckEmptyGroups) { $parameterMode = $true; $selectedOption = '9' }
elseif ($CompareGroups) { $parameterMode = $true; $selectedOption = '10' }
elseif ($ShowFailedAssignments) { $parameterMode = $true; $selectedOption = '11' }
<#
.SYNOPSIS
Checks Intune policy and app assignments for users, groups, and devices.
.DESCRIPTION
This script helps IT administrators analyze and audit Intune assignments by:
- Checking assignments for specific users, groups, or devices
- Showing all policies and their assignments
- Finding policies without assignments
- Identifying empty groups in assignments
- Searching for specific settings across policies
.PARAMETER CheckUser
Check assignments for specific users.
.PARAMETER UserPrincipalNames
User Principal Names to check, comma-separated.
.PARAMETER CheckGroup
Check assignments for specific groups.
.PARAMETER GroupNames
Group names or IDs to check, comma-separated.
.PARAMETER CheckDevice
Check assignments for specific devices.
.PARAMETER DeviceNames
Device names to check, comma-separated.
.PARAMETER ShowAllPolicies
Show all policies and their assignments.
.PARAMETER ShowAllUsersAssignments
Show all 'All Users' assignments.
.PARAMETER ShowAllDevicesAssignments
Show all 'All Devices' assignments.
.PARAMETER GenerateHTMLReport
Generate HTML report.
.PARAMETER ShowPoliciesWithoutAssignments
Show policies and apps without assignments.
.PARAMETER CheckEmptyGroups
Check for empty groups in assignments.
.PARAMETER ShowAdminTemplates
Show all Administrative Templates.
.PARAMETER CompareGroups
Compare assignments between groups.
.PARAMETER CompareGroupNames
Groups to compare assignments between, comma-separated.
.PARAMETER ExportToCSV
Export results to CSV.
.PARAMETER ExportPath
Path for the exported CSV file.
.PARAMETER AppId
App ID for authentication.
.PARAMETER TenantId
Tenant ID for authentication.
.PARAMETER CertificateThumbprint
Certificate Thumbprint for authentication.
.PARAMETER ClientSecret
Client Secret for app registration authentication.
.PARAMETER Environment
Environment (Global, USGov, USGovDoD).
.EXAMPLE
.\IntuneAssignmentChecker_v3.ps1 -CheckUser -UserPrincipalNames "user1@contoso.com,user2@contoso.com"
Checks assignments for the specified users.
.EXAMPLE
.\IntuneAssignmentChecker_v3.ps1 -CheckGroup -GroupNames "Marketing Team"
Checks assignments for the specified group.
.EXAMPLE
.\IntuneAssignmentChecker_v3.ps1 -ShowAllPolicies -ExportToCSV -ExportPath "C:\Temp\AllPolicies.csv"
Shows all policies and exports the results to CSV.
.AUTHOR
Ugur Koc (@ugurkocde)
GitHub: https://github.com/ugurkocde/IntuneAssignmentChecker
Sponsor: https://github.com/sponsors/ugurkocde
Changelog: https://github.com/ugurkocde/IntuneAssignmentChecker/releases
.REQUIRED PERMISSIONS
- User.Read.All (Read user profiles)
- Group.Read.All (Read group information)
- Device.Read.All (Read device information)
- DeviceManagementApps.Read.All (Read app management data)
- DeviceManagementConfiguration.Read.All (Read device configurations)
- DeviceManagementManagedDevices.Read.All (Read device management data)
- DeviceManagementScripts.Read.All (Read device management and health scripts)
- CloudPC.Read.All (Read Windows 365 Cloud PC policies - optional)
#>
################################ Prerequisites #####################################################
# Fill in your App ID, Tenant ID, and Certificate Thumbprint
# Use parameter values if provided, otherwise use defaults
$appid = if ($AppId) { $AppId } else { '<YourAppIdHere>' } # App ID of the App Registration
$tenantid = if ($TenantId) { $TenantId } else { '<YourTenantIdHere>' } # Tenant ID of your EntraID
$certThumbprint = if ($CertificateThumbprint) { $CertificateThumbprint } else { '<YourCertificateThumbprintHere>' } # Thumbprint of the certificate associated with the App Registration
# $certName = '<YourCertificateNameHere>' # Name of the certificate associated with the App Registration
$clientSecret = if ($ClientSecret) { $ClientSecret } else { '' } # Client Secret for app registration authentication
####################################################################################################
# Version of the local script
$localVersion = "3.8.1"
Write-Host "🔍 INTUNE ASSIGNMENT CHECKER" -ForegroundColor Cyan
Write-Host "Made by Ugur Koc with" -NoNewline; Write-Host " ❤️ and ☕" -NoNewline
Write-Host " | Version" -NoNewline; Write-Host " $localVersion" -ForegroundColor Yellow -NoNewline
Write-Host " | Last updated: " -NoNewline; Write-Host "2026-03-02" -ForegroundColor Magenta
Write-Host ""
Write-Host "📢 Feedback & Issues: " -NoNewline -ForegroundColor Cyan
Write-Host "https://github.com/ugurkocde/IntuneAssignmentChecker/issues" -ForegroundColor White
Write-Host "📄 Changelog: " -NoNewline -ForegroundColor Cyan
Write-Host "https://github.com/ugurkocde/IntuneAssignmentChecker/releases" -ForegroundColor White
Write-Host ""
Write-Host "💝 Support this Project: " -NoNewline -ForegroundColor Cyan
Write-Host "https://github.com/sponsors/ugurkocde" -ForegroundColor White
Write-Host ""
Write-Host "⚠️ DISCLAIMER: This script is provided AS IS without warranty of any kind." -ForegroundColor Yellow
Write-Host ""
####################################################################################################
# Autoupdate function
# URL to the version file on GitHub
$versionUrl = "https://raw.githubusercontent.com/ugurkocde/IntuneAssignmentChecker/refs/heads/main/version_v3.txt"
# URL to the latest script on GitHub
$scriptUrl = "https://raw.githubusercontent.com/ugurkocde/IntuneAssignmentChecker/main/IntuneAssignmentChecker_v3.ps1"
# Determine the script path based on whether it's run as a file or from an IDE
if ($PSScriptRoot) {
$newScriptPath = Join-Path $PSScriptRoot "IntuneAssignmentChecker_v3.ps1"
}
else {
$currentDirectory = Get-Location
$newScriptPath = Join-Path $currentDirectory "IntuneAssignmentChecker_v3.ps1"
}
# Flag to control auto-update behavior
$autoUpdate = $true # Set to $false to disable auto-update
try {
# Fetch the latest version number from GitHub
$latestVersion = Invoke-RestMethod -Uri $versionUrl
# Compare versions using System.Version for proper semantic versioning
$local = [System.Version]::new($localVersion)
$latest = [System.Version]::new($latestVersion)
if ($local -lt $latest) {
Write-Host "A new version is available: $latestVersion (you are running $localVersion)" -ForegroundColor Yellow
if ($autoUpdate) {
Write-Host "AutoUpdate is enabled. Downloading the latest version..." -ForegroundColor Yellow
try {
# Download the latest version of the script
Invoke-WebRequest -Uri $scriptUrl -OutFile $newScriptPath
Write-Host "The latest version has been downloaded to $newScriptPath" -ForegroundColor Yellow
Write-Host "Please restart the script to use the updated version." -ForegroundColor Yellow
}
catch {
Write-Host "An error occurred while downloading the latest version. Please download it manually from: https://github.com/ugurkocde/IntuneAssignmentChecker" -ForegroundColor Red
}
}
else {
Write-Host "Auto-update is disabled. Get the latest version at:" -ForegroundColor Yellow
Write-Host "https://github.com/ugurkocde/IntuneAssignmentChecker" -ForegroundColor Cyan
Write-Host ""
}
}
elseif ($local -gt $latest) {
Write-Host "Note: You are running a pre-release version ($localVersion)" -ForegroundColor Magenta
Write-Host ""
}
}
catch {
Write-Host "Unable to check for updates. Continue with current version..." -ForegroundColor Gray
}
####################################################################################################
# Do not change the following code
# Script-level variables
$script:GraphEndpoint = $null
$script:GraphEnvironment = $null
$script:CurrentTenantId = $null
$script:CurrentTenantName = $null
$script:CurrentUserUPN = $null
# Mapping from template subtypes (used in deviceManagement/templates) to templateFamily values
# Note: 'endpointDetectionReponse' is a typo in the Microsoft Graph API (missing 's') - must match exactly
$script:IntentTemplateSubtypeToFamily = @{
'antivirus' = 'endpointSecurityAntivirus'
'diskEncryption' = 'endpointSecurityDiskEncryption'
'firewall' = 'endpointSecurityFirewall'
'endpointDetectionReponse' = 'endpointSecurityEndpointDetectionAndResponse'
'attackSurfaceReduction' = 'endpointSecurityAttackSurfaceReduction'
'accountProtection' = 'endpointSecurityAccountProtection'
}
$script:TemplateIdToFamilyCache = $null
# Ask user to select the Intune environment
function Set-Environment {
param (
[Parameter(Mandatory = $false)]
[string]$EnvironmentName
)
if ($EnvironmentName) {
switch ($EnvironmentName) {
'Global' {
$script:GraphEndpoint = "https://graph.microsoft.com"
$script:GraphEnvironment = "Global"
Write-Host "Environment set to Global" -ForegroundColor Green
return $script:GraphEnvironment
}
'USGov' {
$script:GraphEndpoint = "https://graph.microsoft.us"
$script:GraphEnvironment = "USGov"
Write-Host "Environment set to USGov" -ForegroundColor Green
return $script:GraphEnvironment
}
'USGovDoD' {
$script:GraphEndpoint = "https://dod-graph.microsoft.us"
$script:GraphEnvironment = "USGovDoD"
Write-Host "Environment set to USGovDoD" -ForegroundColor Green
return $script:GraphEnvironment
}
default {
Write-Host "Invalid environment name. Using interactive selection." -ForegroundColor Yellow
# Fall through to interactive selection
}
}
}
# Interactive selection if no valid environment name was provided
do {
Write-Host "Select Intune Tenant Environment:" -ForegroundColor Cyan
Write-Host " [1] Global" -ForegroundColor White
Write-Host " [2] USGov" -ForegroundColor White
Write-Host " [3] USGovDoD" -ForegroundColor White
Write-Host ""
Write-Host " [0] Exit" -ForegroundColor White
Write-Host ""
Write-Host "Select an option: " -ForegroundColor Yellow -NoNewline
$selection = Read-Host
switch ($selection) {
'1' {
$script:GraphEndpoint = "https://graph.microsoft.com"
$script:GraphEnvironment = "Global"
Write-Host "Environment set to Global" -ForegroundColor Green
return $script:GraphEnvironment
}
'2' {
$script:GraphEndpoint = "https://graph.microsoft.us"
$script:GraphEnvironment = "USGov"
Write-Host "Environment set to USGov" -ForegroundColor Green
return $script:GraphEnvironment
}
'3' {
$script:GraphEndpoint = "https://dod-graph.microsoft.us"
$script:GraphEnvironment = "USGovDoD"
Write-Host "Environment set to USGovDoD" -ForegroundColor Green
return $script:GraphEnvironment
}
'0' {
Write-Host "Thank you for using IntuneAssignmentChecker! 👋" -ForegroundColor Green
Write-Host "If you found this tool helpful, please consider:" -ForegroundColor Cyan
Write-Host "- Starring the repository: https://github.com/ugurkocde/IntuneAssignmentChecker" -ForegroundColor White
Write-Host "- Supporting the project: https://github.com/sponsors/ugurkocde" -ForegroundColor White
Write-Host ""
exit
}
default {
Write-Host "Invalid choice, please select 1,2,3, or 0" -ForegroundColor Red
}
}
} while ($selection -ne '0')
}
# Skip execution if SkipExecution flag is set (for testing)
if ($SkipExecution) {
return
}
# Connect to Microsoft Graph using certificate-based authentication
try {
# Define required permissions with reasons
$requiredPermissions = @(
@{
Permission = "User.Read.All"
Reason = "Required to read user profile information and check group memberships"
},
@{
Permission = "Group.Read.All"
Reason = "Needed to read group information and memberships"
},
@{
Permission = "DeviceManagementConfiguration.Read.All"
Reason = "Allows reading Intune device configuration policies and their assignments"
},
@{
Permission = "DeviceManagementApps.Read.All"
Reason = "Necessary to read mobile app management policies and app configurations"
},
@{
Permission = "DeviceManagementManagedDevices.Read.All"
Reason = "Required to read managed device information and compliance policies"
},
@{
Permission = "Device.Read.All"
Reason = "Needed to read device information from Entra ID"
},
@{
Permission = "DeviceManagementScripts.Read.All"
Reason = "Needed to read device management and health scripts"
},
@{
Permission = "CloudPC.Read.All"
Reason = "Required to read Windows 365 Cloud PC provisioning policies and settings (optional if W365 not licensed)"
},
@{
Permission = "DeviceManagementRBAC.Read.All"
Reason = "Required to read role scope tags for scope tag display and filtering"
}
)
# Check if Microsoft Graph is already connected
$graphContext = Get-MgContext -ErrorAction SilentlyContinue
if ($null -ne $graphContext) {
Write-Host "Microsoft Graph is already connected, continuing to check permissions." -ForegroundColor Green
}
else {
Write-Host "No existing Microsoft Graph connection found. Attempting connection..." -ForegroundColor Yellow
# Determine which authentication method to use
$hasAppId = $appid -and $appid -ne '<YourAppIdHere>'
$hasTenantId = $tenantid -and $tenantid -ne '<YourTenantIdHere>'
$hasClientSecret = $clientSecret -and $clientSecret -ne ''
$hasCertThumbprint = $certThumbprint -and $certThumbprint -ne '<YourCertificateThumbprintHere>'
if ($hasAppId -and $hasTenantId -and $hasClientSecret) {
# Client Secret authentication
Write-Host "Connecting using Client Secret authentication..." -ForegroundColor Yellow
if ($parameterMode) {
Set-Environment -EnvironmentName $Environment
}
else {
Set-Environment
}
$secureSecret = ConvertTo-SecureString $clientSecret -AsPlainText -Force
# PSCredential wraps the App ID as the username and the secret as the password
$credential = New-Object System.Management.Automation.PSCredential($appid, $secureSecret)
$null = Connect-MgGraph -TenantId $tenantid -ClientSecretCredential $credential -Environment $script:GraphEnvironment -NoWelcome -ErrorAction Stop
}
elseif ($hasAppId -and $hasTenantId -and $hasCertThumbprint) {
# Certificate-based authentication
Write-Host "Connecting using Certificate authentication..." -ForegroundColor Yellow
if ($parameterMode) {
Set-Environment -EnvironmentName $Environment
}
else {
Set-Environment
}
$null = Connect-MgGraph -ClientId $appid -TenantId $tenantid -Environment $script:GraphEnvironment -CertificateThumbprint $certThumbprint -NoWelcome -ErrorAction Stop
}
else {
# Interactive authentication fallback
Write-Host "App ID, Tenant ID, or authentication credential (Certificate/Client Secret) is missing or not set correctly." -ForegroundColor Red
$manualConnection = Read-Host "Would you like to attempt a manual interactive connection? (y/n)"
if ($manualConnection -eq 'y') {
Write-Host "Attempting manual interactive connection (you need privileges to consent permissions)..." -ForegroundColor Yellow
$permissionsList = ($requiredPermissions | ForEach-Object { $_.Permission }) -join ', '
if ($parameterMode) {
Set-Environment -EnvironmentName $Environment
}
else {
Set-Environment
}
$null = Connect-MgGraph -Scopes $permissionsList -Environment $script:GraphEnvironment -NoWelcome -ErrorAction Stop
}
else {
Write-Host "Script execution cancelled by user." -ForegroundColor Red
exit
}
}
Write-Host "Successfully connected to Microsoft Graph" -ForegroundColor Green
}
# Check and display the current permissions
$context = Get-MgContext
$currentPermissions = $context.Scopes
# Store tenant information
if ($context) {
$script:CurrentTenantId = $context.TenantId
$script:CurrentUserUPN = $context.Account
# Try to get tenant display name
try {
$org = Invoke-MgGraphRequest -Method GET -Uri "$script:GraphEndpoint/v1.0/organization" -ErrorAction SilentlyContinue
if ($org.value -and $org.value.Count -gt 0) {
$script:CurrentTenantName = $org.value[0].displayName
}
}
catch {
# If we can't get the display name, use tenant ID
$script:CurrentTenantName = $context.TenantId
}
}
# For app-only auth (client secret or certificate), Scopes is null because permissions
# are configured on the app registration, not returned via Get-MgContext. Skip the
# scope check in that case and rely on the app registration having the correct permissions.
if ($null -eq $currentPermissions -or $currentPermissions.Count -eq 0) {
Write-Host "App-only authentication detected. Permissions are managed via the app registration." -ForegroundColor Yellow
Write-Host "Ensure the required permissions are granted in the Azure Portal." -ForegroundColor Yellow
Write-Host ""
}
else {
Write-Host "Checking required permissions:" -ForegroundColor Cyan
$missingPermissions = @()
foreach ($permissionInfo in $requiredPermissions) {
$permission = $permissionInfo.Permission
$reason = $permissionInfo.Reason
# Check if either the exact permission or a "ReadWrite" version of it is granted
$hasPermission = $currentPermissions -contains $permission -or $currentPermissions -contains $permission.Replace(".Read", ".ReadWrite")
if ($hasPermission) {
Write-Host " [✓] $permission" -ForegroundColor Green
Write-Host " Reason: $reason" -ForegroundColor Gray
}
else {
Write-Host " [✗] $permission" -ForegroundColor Red
Write-Host " Reason: $reason" -ForegroundColor Gray
$missingPermissions += $permission
}
}
if ($missingPermissions.Count -eq 0) {
Write-Host "All required permissions are present." -ForegroundColor Green
Write-Host ""
}
else {
Write-Host "WARNING: The following permissions are missing:" -ForegroundColor Red
$missingPermissions | ForEach-Object {
$missingPermission = $_
$reason = ($requiredPermissions | Where-Object { $_.Permission -eq $missingPermission }).Reason
Write-Host " - $missingPermission" -ForegroundColor Yellow
Write-Host " Reason: $reason" -ForegroundColor Gray
}
Write-Host "The script will continue, but it may not function correctly without these permissions." -ForegroundColor Red
Write-Host "Please ensure these permissions are granted to the app registration for full functionality." -ForegroundColor Yellow
$continueChoice = Read-Host "Do you want to continue anyway? (y/n)"
if ($continueChoice -ne 'y') {
Write-Host "Script execution cancelled by user." -ForegroundColor Red
exit
}
}
}
}
catch {
Write-Host "Failed to connect to Microsoft Graph. Error: $_" -ForegroundColor Red
# Additional error handling for certificate issues
if ($_.Exception.Message -like "*Certificate with thumbprint*was not found*") {
Write-Host "The specified certificate was not found or has expired. Please check your certificate configuration." -ForegroundColor Yellow
}
# Additional error handling for client secret issues
if ($_.Exception.Message -like "*AADSTS7000215*" -or $_.Exception.Message -like "*Invalid client secret*") {
Write-Host "The provided client secret is invalid or has expired. Please check your client secret configuration." -ForegroundColor Yellow
}
exit
}
# Common Functions
function Get-IntuneAssignments {
param (
[Parameter(Mandatory = $true)]
[string]$EntityType,
[Parameter(Mandatory = $true)]
[string]$EntityId,
[Parameter(Mandatory = $false)]
[string]$GroupId = $null,
[Parameter(Mandatory = $false)]
[string[]]$GroupIds = @()
)
# Unify GroupId and GroupIds into a single effective list
$effectiveGroupIds = if ($GroupIds.Count -gt 0) { $GroupIds }
elseif ($GroupId) { @($GroupId) }
else { @() }
# Determine the correct assignments URI based on EntityType
$actualAssignmentsUri = $null
# $isResolvedAppProtectionPolicy = $false # Flag if we resolved a generic App Protection Policy. Not strictly needed with current logic.
if ($EntityType -eq "deviceAppManagement/managedAppPolicies") {
# For generic App Protection Policies, determine the specific policy type first
$policyDetailsUri = "$GraphEndpoint/beta/deviceAppManagement/managedAppPolicies/$EntityId"
try {
$policyDetailsResponse = Invoke-MgGraphRequest -Uri $policyDetailsUri -Method Get
$policyODataType = $policyDetailsResponse.'@odata.type'
$specificPolicyTypePath = switch ($policyODataType) {
"#microsoft.graph.androidManagedAppProtection" { "androidManagedAppProtections" }
"#microsoft.graph.iosManagedAppProtection" { "iosManagedAppProtections" }
"#microsoft.graph.windowsManagedAppProtection" { "windowsManagedAppProtections" }
default { $null }
}
if ($specificPolicyTypePath) {
$actualAssignmentsUri = "$GraphEndpoint/beta/deviceAppManagement/$specificPolicyTypePath('$EntityId')/assignments"
}
else {
Write-Warning "Could not determine specific App Protection Policy type for $EntityId from OData type '$policyODataType'."
return [System.Collections.ArrayList]::new() # Return empty ArrayList
}
}
catch {
Write-Warning "Error fetching details for App Protection Policy '$EntityId': $($_.Exception.Message)"
return [System.Collections.ArrayList]::new() # Return empty ArrayList
}
}
elseif ($EntityType -eq "mobileAppConfigurations") {
$actualAssignmentsUri = "$GraphEndpoint/beta/deviceAppManagement/mobileAppConfigurations('$EntityId')/assignments"
}
elseif ($EntityType -like "deviceAppManagement/*ManagedAppProtections") {
# Already specific App Protection Policy type
# Example: deviceAppManagement/iosManagedAppProtections
$actualAssignmentsUri = "$GraphEndpoint/beta/$EntityType('$EntityId')/assignments" # EntityType already includes deviceAppManagement
}
elseif ($EntityType -like "virtualEndpoint/*") {
# Windows 365 Cloud PC policies use forward slash format instead of OData parentheses
# Example: virtualEndpoint/provisioningPolicies or virtualEndpoint/userSettings
$actualAssignmentsUri = "$GraphEndpoint/beta/deviceManagement/$EntityType/$EntityId/assignments"
}
else {
# General device management entities
$actualAssignmentsUri = "$GraphEndpoint/beta/deviceManagement/$EntityType('$EntityId')/assignments"
}
if (-not $actualAssignmentsUri) {
# This case should ideally be covered by the logic above, but as a fallback:
Write-Warning "Could not determine a valid assignments URI for EntityType '$EntityType' and EntityId '$EntityId'."
return [System.Collections.ArrayList]::new() # Return empty ArrayList
}
$assignmentsToReturn = [System.Collections.ArrayList]::new()
try {
$allAssignmentsForEntity = [System.Collections.ArrayList]::new()
$currentAssignmentsPageUri = $actualAssignmentsUri
do {
$pagedAssignmentResponse = Invoke-MgGraphRequest -Uri $currentAssignmentsPageUri -Method Get
if ($pagedAssignmentResponse -and $null -ne $pagedAssignmentResponse.value) {
$allAssignmentsForEntity.AddRange($pagedAssignmentResponse.value)
}
$currentAssignmentsPageUri = $pagedAssignmentResponse.'@odata.nextLink'
} while (![string]::IsNullOrEmpty($currentAssignmentsPageUri))
# Ensure $allAssignmentsForEntity is not null before trying to iterate
$assignmentList = if ($allAssignmentsForEntity) { $allAssignmentsForEntity } else { @() }
foreach ($assignment in $assignmentList) {
$currentAssignmentReason = $null
$currentTargetGroupId = $null # Initialize to null
if ($assignment.target -and $assignment.target.'@odata.type') {
$odataType = $assignment.target.'@odata.type'
if ($odataType -eq '#microsoft.graph.groupAssignmentTarget') {
$currentTargetGroupId = $assignment.target.groupId
if ($effectiveGroupIds.Count -gt 0) {
# Specific group check requested
if ($effectiveGroupIds -contains $currentTargetGroupId) {
$currentAssignmentReason = "Direct Assignment"
}
}
else {
# No specific group, list all group assignments
$currentAssignmentReason = "Group Assignment"
}
}
elseif ($odataType -eq '#microsoft.graph.exclusionGroupAssignmentTarget') {
$currentTargetGroupId = $assignment.target.groupId
if ($effectiveGroupIds.Count -gt 0) {
# Specific group check requested
if ($effectiveGroupIds -contains $currentTargetGroupId) {
$currentAssignmentReason = "Direct Exclusion"
}
}
else {
# No specific group, list all group exclusions
$currentAssignmentReason = "Group Exclusion"
}
}
elseif ($effectiveGroupIds.Count -eq 0) {
# Only consider non-group assignments if NOT querying for a specific group
$currentAssignmentReason = switch ($odataType) {
'#microsoft.graph.allLicensedUsersAssignmentTarget' { "All Users" }
'#microsoft.graph.allDevicesAssignmentTarget' { "All Devices" }
default { $null }
}
}
}
else {
Write-Warning "Assignment item for EntityId '$EntityId' (URI: $actualAssignmentsUri) is missing 'target' or 'target.@odata.type' property. Assignment data: $($assignment | ConvertTo-Json -Depth 3)"
}
if ($currentAssignmentReason) {
$null = $assignmentsToReturn.Add([PSCustomObject]@{
Reason = $currentAssignmentReason
GroupId = $currentTargetGroupId
Apps = $null # 'Apps' property is not directly available from general assignments endpoint
})
}
}
}
catch {
$errorMessage = $_.Exception.Message
$statusCode = $_.Exception.Response.StatusCode.value__
if ($statusCode -eq 403 -or $errorMessage -match "403|Forbidden|Authorization_RequestDenied") {
Write-Warning "Permission denied (403) for '$actualAssignmentsUri'. Ensure admin consent has been granted for the required Graph API permissions: DeviceManagementConfiguration.Read.All, DeviceManagementApps.Read.All, DeviceManagementManagedDevices.Read.All"
}
else {
Write-Warning "Error fetching assignments from '$actualAssignmentsUri': $errorMessage"
}
}
return $assignmentsToReturn
}
function Get-IntuneEntities {
param (
[Parameter(Mandatory = $true)]
[string]$EntityType,
[Parameter(Mandatory = $false)]
[string]$Filter = "",
[Parameter(Mandatory = $false)]
[string]$Select = "",
[Parameter(Mandatory = $false)]
[string]$Expand = ""
)
# Handle special cases for app management and specific deviceManagement endpoints
if ($EntityType -like "deviceAppManagement/*" -or $EntityType -eq "deviceManagement/templates" -or $EntityType -eq "deviceManagement/intents") {
$baseUri = "$GraphEndpoint/beta"
$actualEntityType = $EntityType
}
else {
$baseUri = "$GraphEndpoint/beta/deviceManagement"
$actualEntityType = "$EntityType"
}
$currentUri = "$baseUri/$actualEntityType"
if ($Filter) { $currentUri += "?`$filter=$Filter" }
if ($Select) { $currentUri += $(if ($Filter) { "&" }else { "?" }) + "`$select=$Select" }
if ($Expand) { $currentUri += $(if ($Filter -or $Select) { "&" }else { "?" }) + "`$expand=$Expand" }
$entities = [System.Collections.ArrayList]::new() # Initialize as ArrayList
do {
try {
$response = Invoke-MgGraphRequest -Uri $currentUri -Method Get -ErrorAction Stop
if ($null -ne $response -and $null -ne $response.value) {
if ($response.value -is [array]) {
$entities.AddRange($response.value)
}
else {
$entities.Add($response.value)
}
}
$currentUri = $response.'@odata.nextLink'
}
catch {
$errorMessage = $_.Exception.Message
$statusCode = $_.Exception.Response.StatusCode.value__
if ($statusCode -eq 403 -or $errorMessage -match "403|Forbidden|Authorization_RequestDenied") {
Write-Warning "Permission denied (403) for '$EntityType'. Ensure admin consent has been granted for the required Graph API permissions. Run 'Connect-MgGraph -Scopes ...' with the necessary scopes or grant admin consent in Azure AD."
}
else {
Write-Warning "Error fetching entities for $EntityType from $currentUri : $errorMessage"
}
$currentUri = $null # Stop pagination on error
}
} while ($currentUri)
return $entities
}
function Get-IntentTemplateFamilyLookup {
if ($null -ne $script:TemplateIdToFamilyCache) {
return $script:TemplateIdToFamilyCache
}
$script:TemplateIdToFamilyCache = @{}
try {
$templates = Get-IntuneEntities -EntityType "deviceManagement/templates"
foreach ($template in $templates) {
$subtype = $template.templateSubtype
if ($subtype -and $script:IntentTemplateSubtypeToFamily.ContainsKey($subtype)) {
$script:TemplateIdToFamilyCache[$template.id] = $script:IntentTemplateSubtypeToFamily[$subtype]
}
}
}
catch {
Write-Warning "Unable to fetch deviceManagement/templates for intent enrichment: $($_.Exception.Message)"
}
return $script:TemplateIdToFamilyCache
}
function Add-IntentTemplateFamilyInfo {
param (
[Parameter(Mandatory = $true)]
[System.Collections.ArrayList]$IntentPolicies
)
$lookup = Get-IntentTemplateFamilyLookup
foreach ($intent in $IntentPolicies) {
if ($intent.templateId -and $lookup.ContainsKey($intent.templateId)) {
if (-not $intent.templateReference) {
$intent | Add-Member -NotePropertyName 'templateReference' -NotePropertyValue @{
templateFamily = $lookup[$intent.templateId]
}
}
}
}
}
function Resolve-AssignmentReason {
param (
[object[]]$Assignments,
[object[]]$GroupMembershipIds,
[string[]]$IncludeReasons = @("All Users")
)
$isExcluded = $false
$inclusionReason = $null
foreach ($a in $Assignments) {
if ($a.Reason -eq "Group Exclusion" -and $GroupMembershipIds -contains $a.GroupId) {
$isExcluded = $true
}
elseif (-not $inclusionReason) {
if ($IncludeReasons -contains $a.Reason) {
$inclusionReason = $a.Reason
}
elseif ($a.Reason -eq "Group Assignment" -and $GroupMembershipIds -contains $a.GroupId) {
$inclusionReason = $a.Reason
}
}
}
if ($isExcluded) { return "Excluded" }
return $inclusionReason
}
function Get-PolicyPlatform {
param (
[Parameter(Mandatory = $true)]
[PSObject]$Policy
)
# Get the platform based on the @odata.type
$odataType = $Policy.'@odata.type'
if ($null -eq $odataType) {
return "Unknown"
}
switch -Regex ($odataType) {
"android" {
if ($odataType -like "*WorkProfile*") {
return "Android Work Profile"
}
elseif ($odataType -like "*DeviceOwner*") {
return "Android Enterprise"
}
else {
return "Android"
}
}
"ios|iPad|iPhone" {
if ($odataType -like "*macOS*") {
return "macOS"
}
else {
return "iOS/iPadOS"
}
}
"windows" {
if ($odataType -like "*windows10*" -or $odataType -like "*windows81*") {
return "Windows"
}
elseif ($odataType -like "*windowsPhone*") {
return "Windows Phone"
}
else {
return "Windows"
}
}
"macOS|mac" {