/
Export-MSIntuneAssignments.ps1
1401 lines (1358 loc) · 64.6 KB
/
Export-MSIntuneAssignments.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
###########################################################################
## Azure automation runbook PowerShell script to export assignments in ##
## Microsoft Intune to Azure Blob storage where they can be used as a ##
## datasource for Power BI. ##
###########################################################################
<# Notes:
Conditional access not included
May not include features of the Intune Suite
May not include Autopatch
#>
<# Required API permissions for the service principal
DeviceManagementApps.Read.All
DeviceManagementConfiguration.Read.All
DeviceManagementServiceConfig.Read.All
CloudPC.Read.All
DeviceManagementRBAC.Read.All
GroupMember.Read.All
#>
#region ------------------------------------------------ Variables ------------------------------------------------
$ProgressPreference = 'SilentlyContinue' # Speeds up web requests
$429RetryCount = 5 # How many times to retry a request if a 429 status code is received
$ResourceGroup = "<ResourceGroupName>" # Reource group that hosts the Azure storage account
$StorageAccount = "<StorageAccountName>" # Storage account name
$Container = "intune-assignments" # Container name
$Destination = "$env:Temp" # Temp location to export the the CSV file to
#endregion --------------------------------------------------------------------------------------------------------
#region ---------------------------------------------- API endpoints ----------------------------------------------
# Hash table of MS Graph endpoints to query. Add any new endpoints here, after testing them with the tester code
$ResourceTable = [ordered]@{
MobileApps = @{
Url = "deviceAppManagement/mobileApps"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
CompliancePolicies = @{
Url = "deviceManagement/deviceCompliancePolicies"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
DeviceConfigurations = @{
Url = "deviceManagement/deviceConfigurations"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
AutopilotProfiles = @{
Url = "deviceManagement/windowsAutopilotDeploymentProfiles"
SelectProperties = "id,displayName"
RequiresExpand = $true
}
DeviceEnrollmentConfigurations = @{
Url = "deviceManagement/deviceEnrollmentConfigurations"
SelectProperties = "id,displayName"
RequiresExpand = $true
}
DeviceEnrollmentNotificationsConfigurations = @{
Url = "deviceManagement/deviceEnrollmentConfigurations"
FilterUrl = "deviceManagement/deviceEnrollmentConfigurations?`$filter=deviceEnrollmentConfigurationType%20eq%20%27EnrollmentNotificationsConfiguration%27"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
IntuneBrandingProfiles = @{
Url = "deviceManagement/intuneBrandingProfiles"
SelectProperties = "id,profileName"
RequiresExpand = $false
}
AppleUserInitiatedEnrollmentProfiles = @{
Url = "deviceManagement/appleUserInitiatedEnrollmentProfiles"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
ConfigurationPolicies = @{
Url = "deviceManagement/configurationPolicies"
SelectProperties = "id,name,templateReference"
RequiresExpand = $false
}
HardwareConfigurations = @{
Url = "deviceManagement/hardwareConfigurations"
SelectProperties = "id,displayName"
RequiresExpand = $true
}
GroupPolicyConfigurations = @{
Url = "deviceManagement/groupPolicyConfigurations"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
TargetedManagedAppConfigurations = @{
Url = "deviceAppManagement/targetedManagedAppConfigurations"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
AndroidManagedAppProtections = @{
Url = "deviceAppManagement/androidManagedAppProtections"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
IosManagedAppProtections = @{
Url = "deviceAppManagement/iosManagedAppProtections"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
WindowsInformationProtectionPolicies = @{
Url = "deviceAppManagement/windowsInformationProtectionPolicies"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
MdmWindowsInformationProtectionPolicies = @{
Url = "deviceAppManagement/mdmWindowsInformationProtectionPolicies"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
ManagedMobileAppConfigurations = @{
Url = "deviceAppManagement/mobileAppConfigurations"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
#ManagedAppPolicies = @{
# Url = "deviceAppManagement/managedAppPolicies"
# SelectProperties = "id,displayName"
# RequiresExpand = $false
#}
IosLobAppProvisioningConfigurations = @{
Url = "deviceAppManagement/iosLobAppProvisioningConfigurations"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
WdacSupplementalPolicies = @{
Url = "deviceAppManagement/wdacSupplementalPolicies"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
PolicySets = @{
Url = "deviceAppManagement/policySets"
SelectProperties = "id,displayName"
RequiresExpand = $true
}
ManagedEBooks = @{
Url = "deviceAppManagement/managedEBooks"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
ProvisioningPolicies = @{
Url = "deviceManagement/virtualEndpoint/provisioningPolicies"
SelectProperties = "id,displayName"
RequiresExpand = $true
}
UserSettings = @{
Url = "deviceManagement/virtualEndpoint/userSettings"
SelectProperties = "id,displayName"
RequiresExpand = $true
}
DeviceHealthScripts = @{
Url = "deviceManagement/deviceHealthScripts"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
DeviceManagementScripts = @{
Url = "deviceManagement/deviceManagementScripts"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
DeviceShellScripts = @{
Url = "deviceManagement/deviceShellScripts"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
WindowsFeatureUpdateProfiles = @{
Url = "deviceManagement/windowsFeatureUpdateProfiles"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
WindowsQualityUpdateProfiles = @{
Url = "deviceManagement/windowsQualityUpdateProfiles"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
WindowsDriverUpdateProfiles = @{
Url = "deviceManagement/windowsDriverUpdateProfiles"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
EmbeddedSIMActivationCodePools = @{
Url = "deviceManagement/embeddedSIMActivationCodePools"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
DeviceManagementIntents = @{
Url = "deviceManagement/intents"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
RoleAssignments = @{
Url = "deviceManagement/roleDefinitions"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
CloudPCRoleAssignments = @{
Url = "roleManagement/cloudPC/roleDefinitions"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
RoleScopeTags = @{
Url = "deviceManagement/roleScopeTags"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
TermsAndConditions = @{
Url = "deviceManagement/termsAndConditions"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
OperationApprovalPolicies = @{
Url = "deviceManagement/operationApprovalPolicies"
SelectProperties = "id,displayName"
RequiresExpand = $false
}
<# - not generally available yet?
OrganizationalMessages = @{
Url = "deviceManagement/organizationalMessageDetails"
#SelectProperties = "id,displayName"
RequiresExpand = $false
}
#>
}
#endregion --------------------------------------------------------------------------------------------------------
#region ----------------------------------------------- Functions -------------------------------------------------
# Function to send a web request and handle exceptions
Function script:Invoke-WebRequestPro {
Param ($URL,$Headers,$Method,$Body)
If ($Method -eq "POST")
{
try
{
$WebRequest = Invoke-WebRequest -Uri $URL -Method $Method -Headers $Headers -ContentType "application/json" -Body $Body -UseBasicParsing
}
catch
{
$Response = $_
$WebRequest = [PSCustomObject]@{
Message = $response.Exception.Message
StatusCode = $response.Exception.Response.StatusCode
StatusDescription = $response.Exception.Response.StatusDescription
}
}
}
else
{
try
{
$WebRequest = Invoke-WebRequest -Uri $URL -Method $Method -Headers $Headers -UseBasicParsing
}
catch
{
$Response = $_
$WebRequest = [PSCustomObject]@{
Message = $response.Exception.Message
StatusCode = $response.Exception.Response.StatusCode
StatusDescription = $response.Exception.Response.StatusDescription
}
}
}
Return $WebRequest
}
#endregion --------------------------------------------------------------------------------------------------------
#region --------------------------------------------- Authentication ----------------------------------------------
# For manual testing, get an access token for MS Graph as the current user
# ref: https://gist.github.com/SMSAgentSoftware/664dc71350a6d926ea1ec7f41ad2ed77
# $script:GraphToken = Get-MicrosoftGraphAccessToken
# For automation, use a service principal (Managed identity etc)
$AuthRetryCount = 5
$AuthRetries = 0
$AuthSuccess = $false
do {
try
{
$null = Connect-AzAccount -Identity -ErrorAction Stop
$script:GraphToken = (Get-AzAccessToken -ResourceTypeName MSGraph -ErrorAction Stop).Token
$AuthSuccess = $true
}
catch
{
$AuthErrorMessage = $_.Exception.Message
$AuthRetries ++
Write-Warning "Failed to obtain access token: $AuthErrorMessage."
Start-Sleep -Seconds 10
}
}
until ($AuthSuccess -eq $true -or $AuthRetries -ge $AuthRetryCount)
If ($AuthSuccess -eq $false)
{
throw "Failed to authenticate as the service principal: $AuthErrorMessage"
}
#endregion --------------------------------------------------------------------------------------------------------
#region ----------------------------------------------- Tester Code -----------------------------------------------
# This code is just for reference and is used to test the Graph Endpoints to determine the kind of response that is returned
<#
# Get the entity Ids
$URL = "https://graph.microsoft.com/beta/deviceManagement/operationApprovalPolicies"#?`$Select=id,displayName"
$headers = @{'Authorization'="Bearer " + $GraphToken}
$GraphRequest = Invoke-WebRequestPro -URL $URL -Headers $headers -Method GET
[array]$Content = ($GraphRequest.Content | ConvertFrom-Json).Value
# Get the assignments
$Id = $Content[0].id
$URL = "https://graph.microsoft.com/beta/deviceManagement/operationApprovalPolicies/$Id"
#$URL = "https://graph.microsoft.com/beta/deviceAppManagement/managedAppPolicies/$Id`?expand=assignments"
#$URL = "https://graph.microsoft.com/beta/deviceManagement/organizationalMessageDetails/$Id/assignments"
$headers = @{'Authorization'="Bearer " + $GraphToken}
$GraphRequest = Invoke-WebRequestPro -URL $URL -Headers $headers -Method GET
$AssignmentContent = ($GraphRequest.Content | ConvertFrom-Json)
$AssignmentContent
#>
#endregion --------------------------------------------------------------------------------------------------------
#region --------------------------------------------- Batch requests ----------------------------------------------
# Here we will loop through the resources and get the assignments for each resource, utilizing batch requests
# Create a list to store the assignments
$AssignmentList = [System.Collections.Generic.List[PSCustomObject]]::new()
# Create a stopwatch to measure the time taken
$Stopwatch = [System.Diagnostics.Stopwatch]::new()
foreach ($MasterResource in $ResourceTable.Keys)
{
# First we need to get the current list of items for the resouce type
Write-Output "Processing $MasterResource"
$Stopwatch.Start()
$ODataFail = $false
if ($MasterResource -eq "OrganizationalMessages")
{
$URL = "https://graph.microsoft.com/beta/$($ResourceTable[`"$MasterResource`"].Url)"
}
elseif ($MasterResource -eq "DeviceEnrollmentNotificationsConfigurations")
{
$URL = "https://graph.microsoft.com/beta/$($ResourceTable[`"$MasterResource`"].FilterUrl)&`$Select=$($ResourceTable[`"$MasterResource`"].SelectProperties)"
}
else
{
$URL = "https://graph.microsoft.com/beta/$($ResourceTable[`"$MasterResource`"].Url)?`$Select=$($ResourceTable[`"$MasterResource`"].SelectProperties)"
}
$headers = @{'Authorization'="Bearer " + $GraphToken}
$429Count = 0
do {
$GraphRequest = Invoke-WebRequestPro -URL $URL -Headers $headers -Method GET
If ($GraphRequest.StatusCode -eq 429)
{
$429Count++
Write-Warning "429 status code received. Waiting 30 seconds before retrying"
Start-Sleep -Seconds 30
}
}
until ($GraphRequest.StatusCode -ne 429 -or $429Count -ge $429RetryCount)
If ($GraphRequest.StatusCode -ne 200)
{
Write-Error "Failed to retrieve $MasterResource from MS Graph`: $GraphRequest"
continue
}
If ($null -eq $GraphRequest.Content)
{
Write-Warning "No content returned for $MasterResource"
continue
}
$GraphContentObject = $GraphRequest.Content | ConvertFrom-Json
$GraphContent = $GraphContentObject.Value
# If there are more items, get them
if ($GraphContentObject.'@odata.nextLink')
{
do {
$429Count = 0
do {
$GraphRequest = Invoke-WebRequestPro -URL $GraphContentObject.'@odata.nextLink' -Headers $headers -Method GET
If ($GraphRequest.StatusCode -eq 429)
{
$429Count++
Write-Warning "429 status code received. Waiting 30 seconds before retrying"
Start-Sleep -Seconds 30
}
}
until ($GraphRequest.StatusCode -ne 429 -or $429Count -ge $429RetryCount)
If ($GraphRequest.StatusCode -ne 200)
{
Write-Error "Failed to retrieve $MasterResource from MS Graph`: $GraphRequest"
$ODataFail = $true
break
}
$GraphContentObject = $GraphRequest.Content | ConvertFrom-Json
$GraphContent += $GraphContentObject.Value
}
until ($null -eq $GraphContentObject.'@odata.nextLink')
}
if ($ODataFail -eq $true)
{
continue
}
# Get ready to batch the requests to get assignments for each item
$TotalItems = $GraphContent.Count
$BatchSize = 20 # Maximum batch size is 20
$ProcessedItems = 0
$Responses = @()
If ($TotalItems -eq 0)
{
Write-Warning "No $MasterResource found"
continue
}
# The master batch loop
do {
[array]$Batch = $GraphContent | Select -First $BatchSize -Skip $ProcessedItems
$Requests = @()
0..($BatchSize - 1) | foreach {
$resourceId = $($Batch[$_].id)
If ($null -ne $resourceId)
{
# Here we set the correct URL to use for the resource type
if ($ResourceTable[$MasterResource].RequiresExpand -eq $true)
{
$url = $ResourceTable[$MasterResource].Url + "/$resourceId`?expand=assignments"
}
elseif ($MasterResource -in ("RoleAssignments"))
{
$url = $ResourceTable[$MasterResource].Url + "/$resourceId/roleAssignments"
}
elseif ($MasterResource -in ("CloudPCRoleAssignments"))
{
$url = "roleManagement/cloudPC/roleAssignments?`$filter=roleDefinitionId eq '$ResourceId'"
}
elseif ($MasterResource -in ("OrganizationalMessages"))
{
$url = "deviceManagement/organizationalMessageDetails/$ResourceId"
}
elseif ($MasterResource -in ("OperationApprovalPolicies"))
{
$url = "deviceManagement/operationApprovalPolicies/$ResourceId"
}
else
{
$url = $ResourceTable[$MasterResource].Url + "/$resourceId/assignments"
}
$Requests += @{
id = $_
method = "GET"
url = $url
}
}
}
# Post the batch request
$BatchRequest = @{
requests = $Requests
}
$BatchRequest = $BatchRequest | ConvertTo-Json
$URL = "https://graph.microsoft.com/beta/`$batch"
$headers = @{'Authorization'="Bearer " + $GraphToken}
$Response = Invoke-WebRequestPro -URL $URL -Headers $headers -Method POST -Body $BatchRequest
If ($Response.StatusCode -ne 200)
{
Write-Error "Failed to post batch request: $Response"
break
}
$BatchResponse = $Response.Content | ConvertFrom-Json
[array]$BatchResponseStatuses = $BatchResponse.responses.status | Select -Unique
# Retry the batch request if a 429 status code is received in any of the batch responses
If ($BatchResponseStatuses -contains 429)
{
Write-Warning "429 status code received. Waiting 30 seconds before retrying"
Start-Sleep -Seconds 30
$429Count = 1
do {
$Response = Invoke-WebRequestPro -URL $URL -Headers $headers -Method POST -Body $BatchRequest
If ($Response.StatusCode -ne 200)
{
Write-Error "Failed to post batch request: $Response"
break
}
$BatchResponse = $Response.Content | ConvertFrom-Json
[array]$BatchResponseStatuses = $BatchResponse.responses.status | Select -Unique
If ($BatchResponseStatuses -contains 429)
{
$429Count++
Write-Warning "429 status code received. Waiting 30 seconds before retrying"
Start-Sleep -Seconds 30
}
}
until ($BatchResponseStatuses -notcontains 429 -or $429Count -ge $429RetryCount)
If ($Response.StatusCode -ne 200)
{
Write-Error "Failed to post batch request: $Response"
break
}
}
# Add successes to the responses array
if ($BatchResponseStatuses -eq 200)
{
$Responses += $BatchResponse
}
# If the batch failed, fallback to individual requests
else
{
$BadStatusCodes = ($BatchResponseStatuses | Where { $_ -ne 200 }) -join ", "
Write-Warning "Batch request contains bad status codes: $BadStatusCodes. Falling back to individual requests"
0..($BatchSize - 1) | foreach {
$resourceId = $($Batch[$_].id)
If ($null -ne $resourceId)
{
# Here we set the correct URL to use for the resource type
if ($ResourceTable[$MasterResource].RequiresExpand -eq $true)
{
$URL = "https://graph.microsoft.com/beta/$($ResourceTable[`"$MasterResource`"].Url)/$ResourceId`?expand=assignments"
}
elseif ($MasterResource -in ("RoleAssignments"))
{
$URL = "https://graph.microsoft.com/beta/$($ResourceTable[`"$MasterResource`"].Url)/$ResourceId/roleAssignments"
}
elseif ($MasterResource -in ("CloudPCRoleAssignments"))
{
$URL = "https://graph.microsoft.com/beta/roleManagement/cloudPC/roleAssignments?`$filter=roleDefinitionId eq '$ResourceId'"
}
elseif ($MasterResource -in ("OrganizationalMessages"))
{
$url = "https://graph.microsoft.com/beta/deviceManagement/organizationalMessageDetails/$ResourceId"
}
elseif ($MasterResource -in ("OperationApprovalPolicies"))
{
$url = "https://graph.microsoft.com/beta/deviceManagement/operationApprovalPolicies/$ResourceId"
}
else
{
$URL = "https://graph.microsoft.com/beta/$($ResourceTable[`"$MasterResource`"].Url)/$ResourceId/assignments"
}
$headers = @{'Authorization'="Bearer " + $GraphToken}
$429Count = 0
do {
$Response = Invoke-WebRequestPro -URL $URL -Headers $headers -Method GET
If ($Response.StatusCode -eq 429)
{
$429Count++
Write-Warning "429 status code received. Waiting 30 seconds before retrying"
Start-Sleep -Seconds 30
}
}
until ($Response.StatusCode -ne 429 -or $429Count -ge $429RetryCount)
If ($Response.Content)
{
# Here we extract the information we want to report on
$Content = $Response.Content | ConvertFrom-Json
If ($ResourceTable[$MasterResource].RequiresExpand -eq $true)
{
$value = $Content.assignments
}
elseif ($MasterResource -in ("OrganizationalMessages","OperationApprovalPolicies"))
{
$value = $Content
}
else
{
$value = $Content.value
}
if ($value.length -gt 0 -or $value.count -gt 0)
{
foreach ($item in $value)
{
$resource = $GraphContent | Where-Object { $_.id -eq $resourceId }
# Define the resource type
$resourceType = $null
if ($MasterResource -eq "IntuneBrandingProfiles")
{
$resourceType = "intuneBrandingProfile"
}
elseif ($MasterResource -eq "ConfigurationPolicies")
{
if ($Resource.templateReference.templateFamily -eq "none")
{
$resourceType = "configurationPolicySettingsCatalog"
}
else
{
$resourceType = $Resource.templateReference.templateFamily
}
}
elseif ($MasterResource -eq "GroupPolicyConfigurations")
{
$resourceType = "groupPolicyConfiguration"
}
elseif ($MasterResource -eq "TargetedManagedAppConfigurations")
{
$resourceType = "targetedManagedAppConfiguration"
}
elseif ($MasterResource -eq "AndroidManagedAppProtections")
{
$resourceType = "androidManagedAppProtection"
}
elseif ($MasterResource -eq "IosManagedAppProtections")
{
$resourceType = "iosManagedAppProtection"
}
elseif ($MasterResource -eq "WindowsInformationProtectionPolicies")
{
$resourceType = "windowsInformationProtectionPolicy"
}
elseif ($MasterResource -eq "MdmWindowsInformationProtectionPolicies")
{
$resourceType = "mdmWindowsInformationProtectionPolicy"
}
elseif ($MasterResource -eq "PolicySets")
{
$resourceType = "policySet"
}
elseif ($MasterResource -eq "ProvisioningPolicies")
{
$resourceType = "provisioningPolicy"
}
elseif ($MasterResource -eq "UserSettings")
{
$resourceType = "userSettings"
}
elseif ($MasterResource -eq "DeviceHealthScripts")
{
$resourceType = "deviceHealthScript"
}
elseif ($MasterResource -eq "DeviceManagementScripts")
{
$resourceType = "deviceManagementScript"
}
elseif ($MasterResource -eq "DeviceShellScripts")
{
$resourceType = "deviceShellScript"
}
elseif ($MasterResource -eq "WindowsQualityUpdateProfiles")
{
$resourceType = "windowsQualityUpdateProfile"
}
elseif ($MasterResource -eq "WindowsFeatureUpdateProfiles")
{
$resourceType = "windowsFeatureUpdateProfile"
}
elseif ($MasterResource -eq "WindowsDriverUpdateProfiles")
{
$resourceType = "windowsDriverUpdateProfile"
}
elseif ($MasterResource -eq "DeviceManagementIntents")
{
$resourceType = "deviceManagementIntent"
}
elseif ($MasterResource -eq "RoleScopeTags")
{
$resourceType = "roleScopeTag"
}
elseif ($MasterResource -eq "TermsAndConditions")
{
$resourceType = "termsAndConditions"
}
elseif ($MasterResource -eq "OrganizationalMessages")
{
$resourceType = "organizationalMessage"
}
elseif ($MasterResource -eq "OperationApprovalPolicies")
{
$resourceType = "operationApprovalPolicy"
}
elseif ($MasterResource -in ("RoleAssignments"))
{
# For role assignments, we need to get the assignments for each role definition
$URL = "https://graph.microsoft.com/beta/deviceManagement/roleDefinitions/$($Resource.Id)/roleAssignments/$($item.id)"
$headers = @{'Authorization'="Bearer " + $GraphToken}
$429Count = 0
do {
$roleAssignmentsRequest = Invoke-WebRequestPro -URL $URL -Headers $headers -Method GET
If ($roleAssignmentsRequest.StatusCode -eq 429)
{
$429Count++
Write-Warning "429 status code received. Waiting 30 seconds before retrying"
Start-Sleep -Seconds 30
}
}
until ($roleAssignmentsRequest.StatusCode -ne 429 -or $429Count -ge $429RetryCount)
If ($roleAssignmentsRequest.StatusCode -ne 200)
{
Write-Error "Failed to retrieve a role assignment for $MasterResource from MS Graph`: $roleAssignmentsRequest"
continue
}
If ($null -eq $roleAssignmentsRequest.Content)
{
Write-Warning "No content returned for a role assignment for $MasterResource"
continue
}
$RoleAssignmentContent = $roleAssignmentsRequest.Content | ConvertFrom-Json
$resourceType = $RoleAssignmentContent.'@odata.Type'.Split('.')[-1]
$resourceName = "$($resource.displayName) > $($RoleAssignmentContent.displayName)"
# Add the result to the assignment list
foreach ($member in $RoleAssignmentContent.members)
{
$AssignmentList.Add([PSCustomObject]@{
ItemId = $RoleAssignmentContent.id
ItemType = $resourceType
DisplayName = $resourceName
AssignmentType = "groupAssignmentTarget"
Intent = $null
GroupId = $member
GroupDisplayName = $null
FilterId = $null
FilterDisplayName = $null
FilterType = "none"
})
}
continue
}
elseif ($MasterResource -in ("CloudPCRoleAssignments"))
{
$resourceType = "cloudPCRoleAssignment"
$resourceName = "$($resource.displayName) > $($Content.value.displayName)"
foreach ($member in $Content.value.principalIds)
{
$AssignmentList.Add([PSCustomObject]@{
ItemId = $Content.value.id
ItemType = $resourceType
DisplayName = $resourceName
AssignmentType = "groupAssignmentTarget"
Intent = $null
GroupId = $member
GroupDisplayName = $null
FilterId = $null
FilterDisplayName = $null
FilterType = "none"
})
}
continue
}
elseif ($resource.'@odata.Type')
{
$resourceType = $resource.'@odata.Type'.Split('.')[-1]
}
if ($resource.profileName)
{
$resourceName = $resource.profileName
}
elseif ($resource.displayName)
{
$resourceName = $resource.displayName
}
else
{
$resourceName = $resource.name
}
if ($MasterResource -eq "OrganizationalMessages")
{
foreach ($includeId in $item.targeting.includeIds)
{
$AssignmentList.Add([PSCustomObject]@{
ItemId = $resourceId
ItemType = $resourceType
DisplayName = $resourceName
AssignmentType = "groupAssignmentTarget"
Intent = $null
GroupId = $includeId
GroupDisplayName = $null
FilterId = $null
FilterDisplayName = $null
FilterType = "none"
})
}
foreach ($excludeId in $item.targeting.excludeIds)
{
$AssignmentList.Add([PSCustomObject]@{
ItemId = $resourceId
ItemType = $resourceType
DisplayName = $resourceName
AssignmentType = "exclusionGroupAssignmentTarget"
Intent = $null
GroupId = $includeId
GroupDisplayName = $null
FilterId = $null
FilterDisplayName = $null
FilterType = "none"
})
}
}
elseif ($MasterResource -eq "OperationApprovalPolicies")
{
foreach ($approverGroupId in $item.approverGroupIds)
{
$AssignmentList.Add([PSCustomObject]@{
ItemId = $resourceId
ItemType = $resourceType
DisplayName = $resourceName
AssignmentType = "groupAssignmentTarget"
Intent = $null
GroupId = $approverGroupId
GroupDisplayName = $null
FilterId = $null
FilterDisplayName = $null
FilterType = "none"
})
}
}
else
{
$AssignmentList.Add([PSCustomObject]@{
ItemId = $resourceId
ItemType = $resourceType
DisplayName = $resourceName
AssignmentType = $item.target.'@odata.type'.Split('.')[-1]
Intent = $item.intent
GroupId = $item.target.groupId
GroupDisplayName = $null
FilterId = $item.target.deviceAndAppManagementAssignmentFilterId
FilterDisplayName = $null
FilterType = $item.target.deviceAndAppManagementAssignmentFilterType
})
}
}
}
}
}
}
}
$ProcessedItems += $BatchSize
}
until ($ProcessedItems -ge $TotalItems)
# Process each response in the batch
foreach ($response in $responses)
{
$subresponses = $response.responses
foreach ($subresponse in $subresponses)
{
# Only process successful batches
if (($subresponse.status | Select -Unique).ToString() -eq "200")
{
# Determine the id of the item
if ($ResourceTable[$MasterResource].RequiresExpand -eq $true)
{
$resourceId = $subresponse.body.'assignments@odata.context'.Split("'")[-2]
}
elseif ($MasterResource -in ("CloudPCRoleAssignments"))
{
$resourceId = $subresponse.body.value.roleDefinitionId
}
elseif ($MasterResource -in ("OrganizationalMessages","OperationApprovalPolicies"))
{
$resourceId = $subresponse.body.id
}
else
{
$resourceId = $subresponse.body.'@odata.context'.Split("'")[-2]
}
$resource = $GraphContent | Where-Object { $_.id -eq $resourceId }
# Define the resource type
$resourceType = $null
if ($MasterResource -eq "IntuneBrandingProfiles")
{
$resourceType = "intuneBrandingProfile"
}
elseif ($MasterResource -eq "ConfigurationPolicies")
{
if ($Resource.templateReference.templateFamily -eq "none")
{
$resourceType = "configurationPolicySettingsCatalog"
}
else
{
$resourceType = $Resource.templateReference.templateFamily
}
}
elseif ($MasterResource -eq "GroupPolicyConfigurations")
{
$resourceType = "groupPolicyConfiguration"
}
elseif ($MasterResource -eq "TargetedManagedAppConfigurations")
{
$resourceType = "targetedManagedAppConfiguration"
}
elseif ($MasterResource -eq "AndroidManagedAppProtections")
{
$resourceType = "androidManagedAppProtection"
}
elseif ($MasterResource -eq "IosManagedAppProtections")
{
$resourceType = "iosManagedAppProtection"
}
elseif ($MasterResource -eq "WindowsInformationProtectionPolicies")
{
$resourceType = "windowsInformationProtectionPolicy"
}
elseif ($MasterResource -eq "MdmWindowsInformationProtectionPolicies")
{
$resourceType = "mdmWindowsInformationProtectionPolicy"
}
elseif ($MasterResource -eq "PolicySets")
{
$resourceType = "policySet"
}
elseif ($MasterResource -eq "ProvisioningPolicies")
{
$resourceType = "provisioningPolicy"
}
elseif ($MasterResource -eq "UserSettings")
{
$resourceType = "userSettings"
}
elseif ($MasterResource -eq "DeviceHealthScripts")
{
$resourceType = "deviceHealthScript"
}
elseif ($MasterResource -eq "DeviceManagementScripts")
{
$resourceType = "deviceManagementScript"
}
elseif ($MasterResource -eq "DeviceShellScripts")
{
$resourceType = "deviceShellScript"
}
elseif ($MasterResource -eq "WindowsQualityUpdateProfiles")
{
$resourceType = "windowsQualityUpdateProfile"
}
elseif ($MasterResource -eq "WindowsFeatureUpdateProfiles")
{
$resourceType = "windowsFeatureUpdateProfile"
}
elseif ($MasterResource -eq "WindowsDriverUpdateProfiles")
{
$resourceType = "windowsDriverUpdateProfile"
}
elseif ($MasterResource -eq "DeviceManagementIntents")
{
$resourceType = "deviceManagementIntent"
}
elseif ($MasterResource -eq "RoleScopeTags")
{
$resourceType = "roleScopeTag"
}
elseif ($MasterResource -eq "TermsAndConditions")
{
$resourceType = "termsAndConditions"
}
elseif ($MasterResource -eq "OrganizationalMessages")
{
$resourceType = "organizationalMessage"
}
elseif ($MasterResource -eq "OperationApprovalPolicies")
{
$resourceType = "operationApprovalPolicy"
}
elseif ($MasterResource -in ("RoleAssignments"))
{
If ($subresponse.body.value.Count -gt 0 -or $subresponse.body.length -gt 0)
{
foreach ($item in $subresponse.body.value)
{
# For role assignments, we need to get the assignments for each role definition
$URL = "https://graph.microsoft.com/beta/deviceManagement/roleDefinitions/$($Resource.Id)/roleAssignments/$($item.id)"
$headers = @{'Authorization'="Bearer " + $GraphToken}
$429Count = 0
do {
$roleAssignmentsRequest = Invoke-WebRequestPro -URL $URL -Headers $headers -Method GET
If ($roleAssignmentsRequest.StatusCode -eq 429)
{
$429Count++
Write-Warning "429 status code received. Waiting 30 seconds before retrying"
Start-Sleep -Seconds 30
}
}
until ($roleAssignmentsRequest.StatusCode -ne 429 -or $429Count -ge $429RetryCount)
If ($roleAssignmentsRequest.StatusCode -ne 200)
{
Write-Error "Failed to retrieve a role assignment for $Resource ($($subresponse.body)) from MS Graph`: $roleAssignmentsRequest"
continue
}
If ($null -eq $roleAssignmentsRequest.Content)
{
Write-Warning "No content returned a role assignment for $Resource"
continue
}
$RoleAssignmentContent = $roleAssignmentsRequest.Content | ConvertFrom-Json
$resourceType = $RoleAssignmentContent.'@odata.Type'.Split('.')[-1]
$resourceName = "$($resource.displayName) > $($RoleAssignmentContent.displayName)"
# Add the result to the assignment list
foreach ($member in $RoleAssignmentContent.members)
{
$AssignmentList.Add([PSCustomObject]@{