-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathIntuneAssignmentChecker_v3.ps1
3953 lines (3535 loc) · 212 KB
/
IntuneAssignmentChecker_v3.ps1
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
<#
.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
.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)
#>
################################ Prerequisites #####################################################
# Fill in your App ID, Tenant ID, and Certificate Thumbprint
$appid = '<YourAppIdHere>' # App ID of the App Registration
$tenantid = '<YourTenantIdHere>' # Tenant ID of your EntraID
$certThumbprint = '<YourCertificateThumbprintHere>' # Thumbprint of the certificate associated with the App Registration
# $certName = '<YourCertificateNameHere>' # Name of the certificate associated with the App Registration
####################################################################################################
# Version of the local script
$localVersion = "3.0.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 "2025-01-04" -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
# 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"
}
)
# Check if any of the variables are not set or contain placeholder values
if (-not $appid -or $appid -eq '<YourAppIdHere>' -or
-not $tenantid -or $tenantid -eq '<YourTenantIdHere>' -or
-not $certThumbprint -or $certThumbprint -eq '<YourCertificateThumbprintHere>') {
Write-Host "App ID, Tenant ID, or Certificate Thumbprint 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') {
# Manual connection using interactive login
write-host "Attempting manual interactive connection (you need privileges to consent permissions)..." -ForegroundColor Yellow
$permissionsList = ($requiredPermissions | ForEach-Object { $_.Permission }) -join ', '
$connectionResult = Connect-MgGraph -Scopes $permissionsList -NoWelcome -ErrorAction Stop
}
else {
Write-Host "Script execution cancelled by user." -ForegroundColor Red
exit
}
}
else {
$connectionResult = Connect-MgGraph -ClientId $appid -TenantId $tenantid -CertificateThumbprint $certThumbprint -NoWelcome -ErrorAction Stop
}
Write-Host "Successfully connected to Microsoft Graph" -ForegroundColor Green
# Check and display the current permissions
$context = Get-MgContext
$currentPermissions = $context.Scopes
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
}
exit
}
# Common Functions
function Get-IntuneAssignments {
param (
[Parameter(Mandatory = $true)]
[string]$EntityType,
[Parameter(Mandatory = $true)]
[string]$EntityId,
[Parameter(Mandatory = $false)]
[string]$GroupId = $null
)
# Handle special cases for App Protection Policies
$assignmentsUri = if ($EntityType -eq "deviceAppManagement/managedAppPolicies") {
# For App Protection Policies, we need to determine the specific policy type first
$policyUri = "https://graph.microsoft.com/beta/deviceAppManagement/managedAppPolicies/$EntityId"
$policy = Invoke-MgGraphRequest -Uri $policyUri -Method Get
$policyType = switch ($policy.'@odata.type') {
"#microsoft.graph.androidManagedAppProtection" { "androidManagedAppProtections" }
"#microsoft.graph.iosManagedAppProtection" { "iosManagedAppProtections" }
"#microsoft.graph.windowsManagedAppProtection" { "windowsManagedAppProtections" }
default { return $null }
}
if ($policyType) {
"https://graph.microsoft.com/beta/deviceAppManagement/$policyType('$EntityId')/assignments"
}
else {
$null
}
}
else {
"https://graph.microsoft.com/beta/deviceManagement/$EntityType('$EntityId')/assignments"
}
# For App Protection Policies that use $expand, the response structure is different
$isAppProtectionPolicy = $EntityType -like "deviceAppManagement/*" -and ($EntityType -like "*ManagedAppProtections")
if ($isAppProtectionPolicy) {
$policyDetails = Invoke-MgGraphRequest -Uri $assignmentsUri -Method Get
$assignments = @()
foreach ($assignment in $policyDetails.assignments) {
$assignmentReason = $null
switch ($assignment.target.'@odata.type') {
'#microsoft.graph.allLicensedUsersAssignmentTarget' {
$assignmentReason = "All Users"
}
'#microsoft.graph.groupAssignmentTarget' {
if ($assignment.target.groupId -eq $GroupId) {
$assignmentReason = "Direct Assignment"
}
}
}
if ($assignmentReason) {
$assignments += @{
Reason = $assignmentReason
GroupId = $assignment.target.groupId
Apps = $policyDetails.apps
}
}
}
}
else {
$assignmentResponse = Invoke-MgGraphRequest -Uri $assignmentsUri -Method Get
$assignments = @()
$assignmentList = if ($EntityType -like "deviceAppManagement/*") { $assignmentResponse } else { $assignmentResponse.value }
foreach ($assignment in $assignmentList) {
$assignmentReason = $null
# Only process group assignments when GroupId is provided
if ($GroupId) {
if ($assignment.target.'@odata.type' -eq '#microsoft.graph.groupAssignmentTarget' -and
$assignment.target.groupId -eq $GroupId) {
$assignmentReason = "Direct Assignment"
}
}
else {
$assignmentReason = switch ($assignment.target.'@odata.type') {
'#microsoft.graph.allLicensedUsersAssignmentTarget' { "All Users" }
'#microsoft.graph.allDevicesAssignmentTarget' { "All Devices" }
'#microsoft.graph.groupAssignmentTarget' { "Group Assignment" }
}
}
if ($assignmentReason) {
$assignments += @{
Reason = $assignmentReason
GroupId = $assignment.target.groupId
Apps = if ($isAppProtectionPolicy) { $policyDetails.apps } else { $null }
}
}
}
}
return $assignments
}
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 endpoints
$baseUri = if ($EntityType -like "deviceAppManagement/*") {
"https://graph.microsoft.com/beta"
}
else {
"https://graph.microsoft.com/beta/deviceManagement"
}
# Extract the actual entity type from full path if needed
$actualEntityType = if ($EntityType -like "deviceAppManagement/*") {
$EntityType
}
else {
"$EntityType"
}
$uri = "$baseUri/$actualEntityType"
if ($Filter) { $uri += "?`$filter=$Filter" }
if ($Select) { $uri += $(if ($Filter) { "&" }else { "?" }) + "`$select=$Select" }
if ($Expand) { $uri += $(if ($Filter -or $Select) { "&" }else { "?" }) + "`$expand=$Expand" }
$response = Invoke-MgGraphRequest -Uri $uri -Method Get
$entities = $response.value
while ($response.'@odata.nextLink') {
$response = Invoke-MgGraphRequest -Uri $response.'@odata.nextLink' -Method Get
$entities += $response.value
}
return $entities
}
function Get-GroupInfo {
param (
[Parameter(Mandatory = $true)]
[string]$GroupId
)
try {
$groupUri = "https://graph.microsoft.com/v1.0/groups/$GroupId"
$group = Invoke-MgGraphRequest -Uri $groupUri -Method Get
return @{
Id = $group.id
DisplayName = $group.displayName
Success = $true
}
}
catch {
return @{
Id = $GroupId
DisplayName = "Unknown Group"
Success = $false
}
}
}
function Get-DeviceInfo {
param (
[Parameter(Mandatory = $true)]
[string]$DeviceName
)
$deviceUri = "https://graph.microsoft.com/v1.0/devices?`$filter=displayName eq '$DeviceName'"
$deviceResponse = Invoke-MgGraphRequest -Uri $deviceUri -Method Get
if ($deviceResponse.value) {
return @{
Id = $deviceResponse.value[0].id
DisplayName = $deviceResponse.value[0].displayName
Success = $true
}
}
return @{
Id = $null
DisplayName = $DeviceName
Success = $false
}
}
function Get-UserInfo {
param (
[Parameter(Mandatory = $true)]
[string]$UserPrincipalName
)
try {
$userUri = "https://graph.microsoft.com/v1.0/users/$UserPrincipalName"
$user = Invoke-MgGraphRequest -Uri $userUri -Method Get
return @{
Id = $user.id
UserPrincipalName = $user.userPrincipalName
Success = $true
}
}
catch {
return @{
Id = $null
UserPrincipalName = $UserPrincipalName
Success = $false
}
}
}
function Get-GroupMemberships {
param (
[Parameter(Mandatory = $true)]
[string]$ObjectId,
[Parameter(Mandatory = $true)]
[ValidateSet("User", "Device")]
[string]$ObjectType
)
$uri = "https://graph.microsoft.com/v1.0/$($ObjectType.ToLower())s/$ObjectId/transitiveMemberOf?`$select=id,displayName"
$response = Invoke-MgGraphRequest -Uri $uri -Method Get
return $response.value
}
function Get-AssignmentInfo {
param (
[Parameter(Mandatory = $true)]
[AllowNull()]
[array]$Assignments
)
if ($null -eq $Assignments -or $Assignments.Count -eq 0) {
return @{
Type = "None"
Target = "Not Assigned"
}
}
$assignment = $Assignments[0] # Take the first assignment
$type = switch ($assignment.Reason) {
"All Users" { "All Users"; break }
"All Devices" { "All Devices"; break }
"Group Assignment" { "Group"; break }
default { "None" }
}
$target = switch ($type) {
"All Users" { "All Users" }
"All Devices" { "All Devices" }
"Group" {
if ($assignment.GroupId) {
$groupInfo = Get-GroupInfo -GroupId $assignment.GroupId
$groupInfo.DisplayName
}
else {
"Unknown Group"
}
}
default { "Not Assigned" }
}
return @{
Type = $type
Target = $target
}
}
function Show-SaveFileDialog {
param (
[string]$DefaultFileName
)
Add-Type -AssemblyName System.Windows.Forms
$saveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx|CSV files (*.csv)|*.csv|All files (*.*)|*.*"
$saveFileDialog.FileName = $DefaultFileName
$saveFileDialog.Title = "Save Policy Report"
if ($saveFileDialog.ShowDialog() -eq 'OK') {
return $saveFileDialog.FileName
}
return $null
}
function Export-PolicyData {
param (
[Parameter(Mandatory = $true)]
[System.Collections.ArrayList]$ExportData,
[Parameter(Mandatory = $true)]
[string]$FilePath
)
$extension = [System.IO.Path]::GetExtension($FilePath).ToLower()
if ($extension -eq '.xlsx') {
# Check if ImportExcel module is installed
if (-not (Get-Module -ListAvailable -Name ImportExcel)) {
Write-Host "The ImportExcel module is required for Excel export. Would you like to install it? (y/n)" -ForegroundColor Yellow
$install = Read-Host
if ($install -eq 'y') {
try {
Install-Module -Name ImportExcel -Force -Scope CurrentUser
Write-Host "ImportExcel module installed successfully." -ForegroundColor Green
}
catch {
Write-Host "Failed to install ImportExcel module. Falling back to CSV export." -ForegroundColor Red
$FilePath = [System.IO.Path]::ChangeExtension($FilePath, '.csv')
$ExportData | Export-Csv -Path $FilePath -NoTypeInformation
Write-Host "Results exported to $FilePath" -ForegroundColor Green
return
}
}
else {
Write-Host "Falling back to CSV export." -ForegroundColor Yellow
$FilePath = [System.IO.Path]::ChangeExtension($FilePath, '.csv')
$ExportData | Export-Csv -Path $FilePath -NoTypeInformation
Write-Host "Results exported to $FilePath" -ForegroundColor Green
return
}
}
try {
$ExportData | Export-Excel -Path $FilePath -AutoSize -AutoFilter -WorksheetName "Intune Assignments" -TableName "IntuneAssignments"
Write-Host "Results exported to $FilePath" -ForegroundColor Green
}
catch {
Write-Host "Failed to export to Excel. Falling back to CSV export." -ForegroundColor Red
$FilePath = [System.IO.Path]::ChangeExtension($FilePath, '.csv')
$ExportData | Export-Csv -Path $FilePath -NoTypeInformation
Write-Host "Results exported to $FilePath" -ForegroundColor Green
}
}
else {
$ExportData | Export-Csv -Path $FilePath -NoTypeInformation
Write-Host "Results exported to $FilePath" -ForegroundColor Green
}
}
function Add-ExportData {
param (
[System.Collections.ArrayList]$ExportData,
[string]$Category,
[object[]]$Items,
[Parameter(Mandatory = $false)]
[object]$AssignmentReason = "N/A"
)
foreach ($item in $Items) {
$itemName = if ($item.displayName) { $item.displayName } else { $item.name }
# Handle different types of assignment reason input
$reason = if ($AssignmentReason -is [scriptblock]) {
& $AssignmentReason $item
}
elseif ($item.AssignmentReason) {
$item.AssignmentReason
}
elseif ($item.AssignmentSummary) {
$item.AssignmentSummary
}
else {
$AssignmentReason
}
$null = $ExportData.Add([PSCustomObject]@{
Category = $Category
Item = "$itemName (ID: $($item.id))"
AssignmentReason = $reason
})
}
}
function Add-AppExportData {
param (
[System.Collections.ArrayList]$ExportData,
[string]$Category,
[object[]]$Apps,
[string]$AssignmentReason = "N/A"
)
foreach ($app in $Apps) {
$appName = if ($app.displayName) { $app.displayName } else { $app.name }
$null = $ExportData.Add([PSCustomObject]@{
Category = $Category
Item = "$appName (ID: $($app.id))"
AssignmentReason = "$AssignmentReason - $($app.AssignmentIntent)"
})
}
}
function Show-Menu {
Write-Host "Assignment Checks:" -ForegroundColor Cyan
Write-Host " [1] Check User(s) Assignments" -ForegroundColor White
Write-Host " [2] Check Group(s) Assignments" -ForegroundColor White
Write-Host " [3] Check Device(s) Assignments" -ForegroundColor White
Write-Host ""
Write-Host "Policy Overview:" -ForegroundColor Cyan
Write-Host " [4] Show All Policies and Their Assignments" -ForegroundColor White
Write-Host " [5] Show All 'All Users' Assignments" -ForegroundColor White
Write-Host " [6] Show All 'All Devices' Assignments" -ForegroundColor White
Write-Host ""
Write-Host "Advanced Options:" -ForegroundColor Cyan
Write-Host " [7] Generate HTML Report" -ForegroundColor White
Write-Host " [8] Show Policies Without Assignments" -ForegroundColor White
Write-Host " [9] Check for Empty Groups in Assignments" -ForegroundColor White
Write-Host " [10] Show all Administrative Templates (deprecates in December 2024)" -ForegroundColor Yellow
Write-Host " [11] Compare Assignments Between Groups" -ForegroundColor White
Write-Host ""
Write-Host "System:" -ForegroundColor Cyan
Write-Host " [0] Exit" -ForegroundColor White
Write-Host " [98] Support the Project 💝" -ForegroundColor Magenta
Write-Host " [99] Report a Bug or Request a Feature" -ForegroundColor White
Write-Host ""
Write-Host "Select an option: " -ForegroundColor Yellow -NoNewline
}
# Main script logic
do {
Show-Menu
$selection = Read-Host
switch ($selection) {
'1' {
Write-Host "User selection chosen" -ForegroundColor Green
# Prompt for one or more User Principal Names
Write-Host "Please enter User Principal Name(s), separated by commas (,): " -ForegroundColor Cyan
$upnInput = Read-Host
# Validate input
if ([string]::IsNullOrWhiteSpace($upnInput)) {
Write-Host "No UPN provided. Please try again with a valid UPN." -ForegroundColor Red
continue
}
$upns = $upnInput -split ',' | ForEach-Object { $_.Trim() } | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
if ($upns.Count -eq 0) {
Write-Host "No valid UPNs provided. Please try again with at least one valid UPN." -ForegroundColor Red
continue
}
$exportData = [System.Collections.ArrayList]::new()
foreach ($upn in $upns) {
Write-Host "Checking following UPN: $upn" -ForegroundColor Yellow
# Get User Info
$userInfo = Get-UserInfo -UserPrincipalName $upn
if (-not $userInfo.Success) {
Write-Host "User not found: $upn" -ForegroundColor Red
Write-Host "Please verify the User Principal Name is correct." -ForegroundColor Yellow
continue
}
# Get User Group Memberships
try {
$groupMemberships = Get-GroupMemberships -ObjectId $userInfo.Id -ObjectType "User"
Write-Host "User Group Memberships: $($groupMemberships.displayName -join ', ')" -ForegroundColor Green
}
catch {
Write-Host "Error fetching group memberships for user: $upn" -ForegroundColor Red
Write-Host "Error details: $($_.Exception.Message)" -ForegroundColor Red
continue
}
Write-Host "Fetching Intune Profiles and Applications for the user ... (this takes a few seconds)" -ForegroundColor Yellow
# Initialize collections for relevant policies
$relevantPolicies = @{
DeviceConfigs = @()
SettingsCatalog = @()
AdminTemplates = @()
CompliancePolicies = @()
AppProtectionPolicies = @()
AppConfigurationPolicies = @()
AppsRequired = @()
AppsAvailable = @()
AppsUninstall = @()
PlatformScripts = @()
HealthScripts = @()
}
# Get Device Configurations
Write-Host "Fetching Device Configurations..." -ForegroundColor Yellow
$deviceConfigs = Get-IntuneEntities -EntityType "deviceConfigurations"
foreach ($config in $deviceConfigs) {
$assignments = Get-IntuneAssignments -EntityType "deviceConfigurations" -EntityId $config.id
foreach ($assignment in $assignments) {
if ($assignment.Reason -eq "All Users" -or
($assignment.Reason -eq "Group Assignment" -and $groupMemberships.id -contains $assignment.GroupId)) {
$config | Add-Member -NotePropertyName 'AssignmentReason' -NotePropertyValue $assignment.Reason -Force
$relevantPolicies.DeviceConfigs += $config
break
}
}
}
# Get Settings Catalog Policies
Write-Host "Fetching Settings Catalog Policies..." -ForegroundColor Yellow
$settingsCatalog = Get-IntuneEntities -EntityType "configurationPolicies"
foreach ($policy in $settingsCatalog) {
$assignments = Get-IntuneAssignments -EntityType "configurationPolicies" -EntityId $policy.id
foreach ($assignment in $assignments) {
if ($assignment.Reason -eq "All Users" -or
($assignment.Reason -eq "Group Assignment" -and $groupMemberships.id -contains $assignment.GroupId)) {
$policy | Add-Member -NotePropertyName 'AssignmentReason' -NotePropertyValue $assignment.Reason -Force
$relevantPolicies.SettingsCatalog += $policy
break
}
}
}
# Get Administrative Templates
Write-Host "Fetching Administrative Templates..." -ForegroundColor Yellow
$adminTemplates = Get-IntuneEntities -EntityType "groupPolicyConfigurations"
foreach ($template in $adminTemplates) {
$assignments = Get-IntuneAssignments -EntityType "groupPolicyConfigurations" -EntityId $template.id
foreach ($assignment in $assignments) {
if ($assignment.Reason -eq "All Users" -or
($assignment.Reason -eq "Group Assignment" -and $groupMemberships.id -contains $assignment.GroupId)) {
$template | Add-Member -NotePropertyName 'AssignmentReason' -NotePropertyValue $assignment.Reason -Force
$relevantPolicies.AdminTemplates += $template
break
}
}
}
# Get Compliance Policies
Write-Host "Fetching Compliance Policies..." -ForegroundColor Yellow
$compliancePolicies = Get-IntuneEntities -EntityType "deviceCompliancePolicies"
foreach ($policy in $compliancePolicies) {
$assignments = Get-IntuneAssignments -EntityType "deviceCompliancePolicies" -EntityId $policy.id
foreach ($assignment in $assignments) {
if ($assignment.Reason -eq "All Users" -or
($assignment.Reason -eq "Group Assignment" -and $groupMemberships.id -contains $assignment.GroupId)) {
$policy | Add-Member -NotePropertyName 'AssignmentReason' -NotePropertyValue $assignment.Reason -Force
$relevantPolicies.CompliancePolicies += $policy
break
}
}
}
# Get App Protection Policies
Write-Host "Fetching App Protection Policies..." -ForegroundColor Yellow
$appProtectionPolicies = Get-IntuneEntities -EntityType "deviceAppManagement/managedAppPolicies"
foreach ($policy in $appProtectionPolicies) {
$policyType = $policy.'@odata.type'
$assignmentsUri = switch ($policyType) {
"#microsoft.graph.androidManagedAppProtection" { "https://graph.microsoft.com/beta/deviceAppManagement/androidManagedAppProtections('$($policy.id)')/assignments" }
"#microsoft.graph.iosManagedAppProtection" { "https://graph.microsoft.com/beta/deviceAppManagement/iosManagedAppProtections('$($policy.id)')/assignments" }
"#microsoft.graph.windowsManagedAppProtection" { "https://graph.microsoft.com/beta/deviceAppManagement/windowsManagedAppProtections('$($policy.id)')/assignments" }
default { $null }
}
if ($assignmentsUri) {
try {
$assignmentResponse = Invoke-MgGraphRequest -Uri $assignmentsUri -Method Get
$assignments = @()
foreach ($assignment in $assignmentResponse.value) {
$assignmentReason = $null
switch ($assignment.target.'@odata.type') {
'#microsoft.graph.allLicensedUsersAssignmentTarget' {
$assignmentReason = "All Users"
}
'#microsoft.graph.groupAssignmentTarget' {
if (!$GroupId -or $assignment.target.groupId -eq $GroupId) {
$assignmentReason = "Group Assignment"
}
}
}
if ($assignmentReason) {
$assignments += @{
Reason = $assignmentReason
GroupId = $assignment.target.groupId
}
}
}
if ($assignments.Count -gt 0) {
$assignmentSummary = $assignments | ForEach-Object {
if ($_.Reason -eq "Group Assignment") {
$groupInfo = Get-GroupInfo -GroupId $_.GroupId
"$($_.Reason) - $($groupInfo.DisplayName)"
}
else {
$_.Reason
}
}
$policy | Add-Member -NotePropertyName 'AssignmentSummary' -NotePropertyValue ($assignmentSummary -join "; ") -Force
$relevantPolicies.AppProtectionPolicies += $policy
}
}
catch {
Write-Host "Error fetching assignments for policy $($policy.displayName): $($_.Exception.Message)" -ForegroundColor Red
}
}
}
# Get App Configuration Policies
Write-Host "Fetching App Configuration Policies..." -ForegroundColor Yellow
$appConfigPolicies = Get-IntuneEntities -EntityType "deviceAppManagement/mobileAppConfigurations"
foreach ($policy in $appConfigPolicies) {
$assignments = Get-IntuneAssignments -EntityType "mobileAppConfigurations" -EntityId $policy.id
foreach ($assignment in $assignments) {
if ($assignment.Reason -eq "All Users" -or
($assignment.Reason -eq "Group Assignment" -and $groupMemberships.id -contains $assignment.GroupId)) {
$policy | Add-Member -NotePropertyName 'AssignmentReason' -NotePropertyValue $assignment.Reason -Force
$relevantPolicies.AppConfigurationPolicies += $policy
break
}
}
}
# Fetch and process Applications
Write-Host "Fetching Applications..." -ForegroundColor Yellow
$appUri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps?`$filter=isAssigned eq true"
$appResponse = Invoke-MgGraphRequest -Uri $appUri -Method Get
$allApps = $appResponse.value
while ($appResponse.'@odata.nextLink') {
$appResponse = Invoke-MgGraphRequest -Uri $appResponse.'@odata.nextLink' -Method Get
$allApps += $appResponse.value
}
$totalApps = $allApps.Count
$currentApp = 0
foreach ($app in $allApps) {
# Filter out irrelevant apps
if ($app.isFeatured -or $app.isBuiltIn) {
continue
}
$currentApp++
Write-Host "`rFetching Application $currentApp of $totalApps" -NoNewline
$appId = $app.id
$assignmentsUri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps('$appId')/assignments"
$assignmentResponse = Invoke-MgGraphRequest -Uri $assignmentsUri -Method Get
foreach ($assignment in $assignmentResponse.value) {
if ($assignment.target.'@odata.type' -eq '#microsoft.graph.allLicensedUsersAssignmentTarget' -or
($assignment.target.'@odata.type' -eq '#microsoft.graph.groupAssignmentTarget' -and $groupMemberships.id -contains $assignment.target.groupId)) {
switch ($assignment.intent) {
"required" { $relevantPolicies.AppsRequired += $app; break }
"available" { $relevantPolicies.AppsAvailable += $app; break }
"uninstall" { $relevantPolicies.AppsUninstall += $app; break }
}
break
}
}
}
Write-Host "`rFetching Application $totalApps of $totalApps" -NoNewline
Start-Sleep -Milliseconds 100
Write-Host "" # Move to the next line after the loop
# Get Platform Scripts
Write-Host "Fetching Platform Scripts..." -ForegroundColor Yellow
$platformScripts = Get-IntuneEntities -EntityType "deviceManagementScripts"
foreach ($script in $platformScripts) {
$assignments = Get-IntuneAssignments -EntityType "deviceManagementScripts" -EntityId $script.id
foreach ($assignment in $assignments) {
if ($assignment.Reason -eq "All Users" -or
($assignment.Reason -eq "Group Assignment" -and $groupMemberships.id -contains $assignment.GroupId)) {
$script | Add-Member -NotePropertyName 'AssignmentReason' -NotePropertyValue $assignment.Reason -Force
$relevantPolicies.PlatformScripts += $script
break
}
}
}
# Get Proactive Remediation Scripts
Write-Host "Fetching Proactive Remediation Scripts..." -ForegroundColor Yellow
$healthScripts = Get-IntuneEntities -EntityType "deviceHealthScripts"
foreach ($script in $healthScripts) {
$assignments = Get-IntuneAssignments -EntityType "deviceHealthScripts" -EntityId $script.id
foreach ($assignment in $assignments) {
if ($assignment.Reason -eq "All Users" -or
($assignment.Reason -eq "Group Assignment" -and $groupMemberships.id -contains $assignment.GroupId)) {
$script | Add-Member -NotePropertyName 'AssignmentReason' -NotePropertyValue $assignment.Reason -Force
$relevantPolicies.HealthScripts += $script
break
}
}
}
# Display results
Write-Host "`nAssignments for User: $upn" -ForegroundColor Green
# Display Device Configurations
Write-Host "`n------- Device Configurations -------" -ForegroundColor Cyan
foreach ($config in $relevantPolicies.DeviceConfigs) {
$configName = if ([string]::IsNullOrWhiteSpace($config.name)) { $config.displayName } else { $config.name }
$assignmentInfo = if ($config.AssignmentReason) { ", Assignment Reason: $($config.AssignmentReason)" } else { "" }
Write-Host "Device Configuration Name: $configName, Configuration ID: $($config.id)$assignmentInfo" -ForegroundColor White
}
# Display Settings Catalog Policies
Write-Host "`n------- Settings Catalog Policies -------" -ForegroundColor Cyan
foreach ($policy in $relevantPolicies.SettingsCatalog) {
$policyName = if ([string]::IsNullOrWhiteSpace($policy.name)) { $policy.displayName } else { $policy.name }
$assignmentInfo = if ($policy.AssignmentReason) { ", Assignment Reason: $($policy.AssignmentReason)" } else { "" }
Write-Host "Settings Catalog Policy Name: $policyName, Policy ID: $($policy.id)$assignmentInfo" -ForegroundColor White
}
# Display Administrative Templates
Write-Host "`n------- Administrative Templates -------" -ForegroundColor Cyan
foreach ($template in $relevantPolicies.AdminTemplates) {
$templateName = if ([string]::IsNullOrWhiteSpace($template.name)) { $template.displayName } else { $template.name }
$assignmentInfo = if ($template.AssignmentReason) { ", Assignment Reason: $($template.AssignmentReason)" } else { "" }
Write-Host "Administrative Template Name: $templateName, Template ID: $($template.id)$assignmentInfo" -ForegroundColor White
}
# Display Compliance Policies
Write-Host "`n------- Compliance Policies -------" -ForegroundColor Cyan
foreach ($policy in $relevantPolicies.CompliancePolicies) {
$policyName = if ([string]::IsNullOrWhiteSpace($policy.name)) { $policy.displayName } else { $policy.name }
$assignmentInfo = if ($policy.AssignmentReason) { ", Assignment Reason: $($policy.AssignmentReason)" } else { "" }
Write-Host "Compliance Policy Name: $policyName, Policy ID: $($policy.id)$assignmentInfo" -ForegroundColor White
}
# Display App Protection Policies
Write-Host "`n------- App Protection Policies -------" -ForegroundColor Cyan
foreach ($policy in $relevantPolicies.AppProtectionPolicies) {
$policyName = $policy.displayName
$policyId = $policy.id
$policyType = switch ($policy.'@odata.type') {
"#microsoft.graph.androidManagedAppProtection" { "Android" }
"#microsoft.graph.iosManagedAppProtection" { "iOS" }
"#microsoft.graph.windowsManagedAppProtection" { "Windows" }
default { "Unknown" }
}
$assignmentInfo = if ($policy.AssignmentReason) { ", Assignment Reason: $($policy.AssignmentReason)" } else { "" }
Write-Host "App Protection Policy Name: $policyName, Policy ID: $policyId, Type: $policyType$assignmentInfo" -ForegroundColor White
}
# Display App Configuration Policies
Write-Host "`n------- App Configuration Policies -------" -ForegroundColor Cyan
foreach ($policy in $relevantPolicies.AppConfigurationPolicies) {
$policyName = if ([string]::IsNullOrWhiteSpace($policy.name)) { $policy.displayName } else { $policy.name }
$assignmentInfo = if ($policy.AssignmentReason) { ", Assignment Reason: $($policy.AssignmentReason)" } else { "" }
Write-Host "App Configuration Policy Name: $policyName, Policy ID: $($policy.id)$assignmentInfo" -ForegroundColor White
}
# Display Platform Scripts
Write-Host "`n------- Platform Scripts -------" -ForegroundColor Cyan
foreach ($script in $relevantPolicies.PlatformScripts) {
$scriptName = if ([string]::IsNullOrWhiteSpace($script.name)) { $script.displayName } else { $script.name }
$assignmentInfo = if ($script.AssignmentReason) { ", Assignment Reason: $($script.AssignmentReason)" } else { "" }
Write-Host "Script Name: $scriptName, Script ID: $($script.id)$assignmentInfo" -ForegroundColor White
}
# Display Proactive Remediation Scripts
Write-Host "`n------- Proactive Remediation Scripts -------" -ForegroundColor Cyan
foreach ($script in $relevantPolicies.HealthScripts) {