-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathSet-IntunePrimaryUsers.ps1
More file actions
1988 lines (1772 loc) · 115 KB
/
Set-IntunePrimaryUsers.ps1
File metadata and controls
1988 lines (1772 loc) · 115 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
<#PSScriptInfo
.VERSION 7.4.6
.GUID feedbeef-beef-4dad-beef-000000000001
.AUTHOR @MrTbone_se (T-bone Granheden)
.COPYRIGHT (c) 2026 T-bone Granheden. MIT License - free to use with attribution.
.TAGS Intune Graph PrimaryUser DeviceManagement MicrosoftGraph Azure
.LICENSEURI https://opensource.org/licenses/MIT
.PROJECTURI https://github.com/Mr-Tbone/Intune
.RELEASENOTES
1.0.2202.1 - Initial Version
2.0.2312.1 - Large update to use Graph batching and reduce runtime
3.0.2407.1 - Added support for Group filtering
3.0.2407.2 - Added a verification of required permissions
4.0.2503.1 - Added new functions and new structure for the script
5.0.2504.1 - Changed all requests to use invoke-mggraphrequets
5.0.2504.2 - Bug fixing and error and throttling handling
5.1.2504.3 - Changed sorting and selecting from the sign-in logs and overall performance improvements
6.0.2510.1 - A complete rewrite of the processes due to changes in Microsoft Graph, now 10x faster and more reliable
6.0.2510.2 - Added T-Bone logging function throughout the script to better track execution and errors
6.0.2510.3 - Improved logic and performance of the user sign-in data processing
6.0.2510.4 - Added a fallback for windows devices with no Windows sign-in logs, to use application sign-in logs instead
6.0.2510.5 - New parameters for keep and replace accounts
6.0.2511.1 - New parameters for Intune only or both Intune and Co-managed
6.1.2511.2 - Bug fixes with DeviceTimeSpan and changed the name of the script to Set-IntunePrimaryUsers.ps1
6.1.2512.1 - Added Certificate based auth and app based auth support in Invoke-ConnectMgGraph function
6.2 2512.1 - Added versions on functions to keep track of changes, aslo worked through declarations, comments and fixed minor bugs
6.1.1 2025-12-22 Fixed a better connect with parameter check
7.0.0 2025-12-23 Major update to allign all primary user scripts. Many small changes to improve performance and reliability.
7.0.1 2026-01-07 Fixed missing variable
7.0.2 2026-01-09 Fixed header to comply with best practice
7.0.3 2026-01-19 Fixed small bugs and syntax errors
7.1.0 2026-01-21 Minor update to logging module and a lot of variable naming changes
7.1.1 2026-01-30 Fixed missing $SignInsStartTime
7.2.0 2026-02-06 Fixed skip token expiration issue with automatic query restart and deduplication
7.3.0 2026-02-06 Minor update to support skip token that break graph requests early
7.4.0 2026-02-17 Minor change to avoid mismatch in microsoft.graph modules
7.4.1 2026-02-17 Fix a bug in reporting function with formating issues on some regional languages
7.4.2 2026-02-24 Fixed ClientSecret authentication PSCredential creation
7.4.3 2026-02-24 Fixed clientsecret
7.4.4 2026-02-24 Fix AuthClientSecret
7.4.5 2026-02-24 Fixed ClientSecret authentication without exposing secrets
7.4.6 2026-03-02 Fix to support both secure and non secure secret string using object type
#>
<#
.SYNOPSIS
Script for Intune to set Primary User on Device
.DESCRIPTION
This script gets Entra Sign-in logs for Windows and application sign-ins,
determines the most frequent user in the last 30 days, and sets them as Primary User.
Uses Microsoft Graph and requires only the Microsoft.Graph.Authentication module.
.EXAMPLE
.\Set-IntunePrimaryUsers.ps1
Sets primary user for all Intune devices with default settings.
.EXAMPLE
.\Set-IntunePrimaryUsers.ps1 -OperatingSystems All -ReportDetailed $true -ReportToDisk $true
Sets primary user for all Intune devices and saves detailed report to disk.
.EXAMPLE
.\Set-IntunePrimaryUsers.ps1 -OperatingSystems Windows -SignInsTimeSpan 7 -DeviceTimeSpan 7
Sets primary user for Windows devices based on sign-ins and device activity in the last 7 days.
.NOTES
Please feel free to use this, but make sure to credit @MrTbone_se as the original author
.LINK
https://tbone.se
#>
#region ---------------------------------------------------[Set Script Requirements]-----------------------------------------------
#Requires -Modules Microsoft.Graph.Authentication
#Requires -Version 5.1
#endregion
#region ---------------------------------------------------[Modifiable Parameters and Defaults]------------------------------------
# Customizations
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory = $false, HelpMessage = "Name of the script action for logging.")]
[string]$ScriptActionName = "Set Intune Primary User",
[Parameter(Mandatory = $false, HelpMessage = "Device operatingsystems to process ('All', 'Windows', 'Android', 'iOS', 'macOS'). Default is 'Windows'")]
[ValidateSet('All', 'Windows', 'Android', 'iOS', 'macOS')]
[string[]]$OperatingSystems = @('Windows'),
[Parameter(Mandatory = $false, HelpMessage = "Filter Intune only managed devices (true) or also include Co-managed devices (false). Default is true")]
[bool]$IntuneOnly = $true,
[Parameter(Mandatory = $false, HelpMessage = "Filter to only include devicenames that starts with specific strings like ('Tbone', 'Desktop'). Default is blank")]
[string[]]$IncludedDeviceNames = @(),
[Parameter(Mandatory = $false, HelpMessage = "Filter to exclude devicenames that starts with specific strings like ('Tbone', 'Desktop'). Default is blank")]
[string[]]$ExcludedDeviceNames = @(),
[Parameter(Mandatory = $false, HelpMessage = "Filter to exclude specific accounts as primary owners for example enrollment accounts ('wds@tbone.se','install@tbone.se'). Default is blank")]
[string[]]$ReplaceUserAccounts = @(),
[Parameter(Mandatory = $false, HelpMessage = "Filter to keep specific accounts that always should be keept as primary owners ('Monitoring@tbone.se'). Default is blank")]
[string[]]$KeepUserAccounts = @(),
[Parameter(Mandatory = $false, HelpMessage = "Time period in days to retrieve user sign-in activity logs. Default is 30 days")]
[ValidateRange(1,90)]
[int]$SignInsTimeSpan = 30,
[Parameter(Mandatory = $false, HelpMessage = "Time period in days to retrieve active devices. Default is 30 days")]
[ValidateRange(1,365)]
[int]$DeviceTimeSpan = 30,
[Parameter(Mandatory = $false, HelpMessage = "Testmode, same as -WhatIf. Default is false")]
[bool]$Testmode = $false,
# ==========> Authentication (Invoke-ConnectMgGraph) Leave blank if use Interactive or Managed Identity <==============
[Parameter( HelpMessage = "Entra ID Tenant ID (directory ID) (required for Client Secret or Certificate authentication)")]
[ValidateNotNullOrEmpty()]
[string]$AuthTenantId,
[Parameter( HelpMessage = "Entra ID Application ID (ClientID) (required for Client Secret or Certificate authentication)")]
[ValidateNotNullOrEmpty()]
[string]$AuthClientId,
[Parameter( HelpMessage = "Client Secret as SecureString or string for app-only authentication (require also ClientId and TenantId)")]
[ValidateNotNull()]
[Object]$AuthClientSecret,
[Parameter( HelpMessage = "Certificate thumbprint for certificate-based authentication (if certificate is stored in CurrentUser or LocalMachine store)")]
[ValidateNotNullOrEmpty()]
[string]$AuthCertThumbprint,
[Parameter( HelpMessage = "Certificate subject name for certificate-based authentication (if certificate is stored in CurrentUser or LocalMachine store)")]
[ValidateNotNullOrEmpty()]
[string]$AuthCertName,
[Parameter( HelpMessage = "File path to certificate (.pfx or .cer) for certificate-based authentication (if certificate is stored as a file)")]
[ValidateNotNullOrEmpty()]
[string]$AuthCertPath,
[Parameter( HelpMessage = "Password for certificate file as SecureString (required if certificate is stored as a file and password-protected)")]
[SecureString]$AuthCertPassword,
# ==========> Logging (Invoke-TboneLog) <==============================================================================
[Parameter(Mandatory = $false, HelpMessage='Name of Log, to set name for Eventlog and Filelog')]
[string]$LogName = "",
[Parameter(Mandatory = $false, HelpMessage='Show output in console during execution')]
[bool]$LogToGUI = $true,
[Parameter(Mandatory = $false, HelpMessage='Write complete log array to Windows Event when script ends')]
[bool]$LogToEventlog = $false,
[Parameter(Mandatory = $false, HelpMessage='EventLog IDs as hashtable: @{Info=11001; Warn=11002; Error=11003}')]
[hashtable]$LogEventIds = @{Info=11001; Warn=11002; Error=11003},
[Parameter(Mandatory = $false, HelpMessage='Return complete log array as Host output when script ends (Good for Intune Remediations)')]
[bool]$LogToHost = $false,
[Parameter(Mandatory = $false, HelpMessage='Write complete log array to Disk when script ends')]
[bool]$LogToDisk = $false,
[Parameter(Mandatory = $false, HelpMessage='Path where Disk logs are saved (if LogToDisk is enabled)')]
[string]$LogToDiskPath = "$env:TEMP",
[Parameter(Mandatory = $false, HelpMessage = "Enable verbose logging. Default is false")]
[bool]$LogVerboseEnabled = $false,
# ==========> Reporting (Invoke-ScriptReport) <========================================================================
[Parameter(Mandatory = $false, HelpMessage = "Title of the report")]
[string]$ReportTitle = "",
[Parameter(Mandatory = $false, HelpMessage = "Return report with statistics on how many changed objects. Default is true")]
[bool]$ReportEnabled = $true,
[Parameter(Mandatory = $false, HelpMessage = "Include detailed device changes in the report. Default is true")]
[bool]$ReportDetailed = $true,
[Parameter(Mandatory = $false, HelpMessage = "Save report to disk. Default is false")]
[bool]$ReportToDisk = $false,
[Parameter(Mandatory = $false, HelpMessage = "Path where to save the report. Default is TEMP directory for Azure Automation compatibility")]
[string]$ReportToDiskPath = "$env:TEMP",
# ==========> Throttling and Retry (Invoke-MgGraphRequestSingle and Invoke-MgGraphRequestBatch) <======================
[Parameter(Mandatory = $false, HelpMessage = "Wait time in milliseconds between throttled requests. Default is 1000")]
[ValidateRange(100,5000)]
[int]$GraphWaitTime = 1000,
[Parameter(Mandatory = $false, HelpMessage = "Maximum number of retry attempts for failed requests. Default is 3")]
[ValidateRange(1,10)]
[int]$GraphMaxRetry = 3
)
#endregion
#region ---------------------------------------------------[Modifiable Variables and defaults]------------------------------------
# Application IDs for the search of sign-in logs on different OS
[string]$AppId_Android = '9ba1a5c7-f17a-4de9-a1f1-6178c8d51223' # Microsoft Intune Company Portal
[string]$AppId_iOS = 'e8be65d6-d430-4289-a665-51bf2a194bda' # Microsoft 365 App Catalog Services
[string]$AppId_macOS = '29d9ed98-a469-4536-ade2-f981bc1d605e' # Microsoft Authentication Broker
[string]$AppId_Windows = '38aa3b87-a06d-4817-b275-7a316988d93b' # Windows Sign In
[string]$AppId_Windows_Fallback = 'fc0f3af4-6835-4174-b806-f7db311fd2f3' # Microsoft Intune Windows Agent. Fallback if no Windows Sign In logs are found
# ==========> Authentication (Invoke-ConnectMgGraph) <=================================================================
[System.Collections.ArrayList]$RequiredScopes = @( # Required Graph API permission scopes used in function Invoke-ConnectMgGraph
"DeviceManagementManagedDevices.ReadWrite.All", # Read/write Intune device to set Primary Users
"AuditLog.Read.All", # Read sign-in logs
"User.Read.All" # Read users
)
#endregion
#region ---------------------------------------------------[Set global script settings]--------------------------------------------
# Exit if running as a managed identity in PowerShell 7.2 due to bugs connecting to MgGraph https://github.com/microsoftgraph/msgraph-sdk-powershell/issues/3151
if ($env:IDENTITY_ENDPOINT -and $env:IDENTITY_HEADER -and $PSVersionTable.PSVersion -eq [version]"7.2.0") {
Write-Error "This script cannot run as a managed identity in PowerShell 7.2. Please use a different version of PowerShell."
exit 1}
# set strict mode to latest version
Set-StrictMode -Version Latest
# Save original preference states at script scope for restoration in finally block
[System.Management.Automation.ActionPreference]$script:OriginalErrorActionPreference = $ErrorActionPreference
[System.Management.Automation.ActionPreference]$script:OriginalVerbosePreference = $VerbosePreference
[bool]$script:OriginalWhatIfPreference = $WhatIfPreference
# Set verbose- and whatif- preference based on parameter instead of hardcoded values
if ($LogVerboseEnabled) {$VerbosePreference = 'Continue'} # Set verbose logging based on the parameter $LogVerboseEnabled
else {$VerbosePreference = 'SilentlyContinue'}
if($Testmode) {$WhatIfPreference = 1} # Manually enable whatif mode with parameter $Testmode for testing
#endregion
#region ---------------------------------------------------[Import Modules and Extensions]-----------------------------------------
# Import Microsoft.Graph.Authentication with automatic version conflict resolution
[string]$ModuleName = 'Microsoft.Graph.Authentication'
if (-not (Get-Module -Name $ModuleName)) {
try { # Try normal import first
& {$VerbosePreference = 'SilentlyContinue'; Import-Module $ModuleName -ErrorAction Stop}
Write-Verbose "Imported $ModuleName v$((Get-Module -Name $ModuleName).Version)"
}
catch { # Reported bug with missmatch version. This will catch the error and try to clean up and retry the import
if ($_.Exception -is [System.TypeLoadException] -or $_.Exception.Message -match 'does not have an implementation') {
Write-Warning "Module version conflict detected - cleaning up and retrying"
& {$VerbosePreference = 'SilentlyContinue'; Get-Module Microsoft.Graph.* | Remove-Module -Force -ErrorAction SilentlyContinue}
[version]$LatestVersion = (Get-Module -Name $ModuleName -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1).Version
& {$VerbosePreference = 'SilentlyContinue'; Import-Module $ModuleName -RequiredVersion $LatestVersion -Force -ErrorAction Stop}
Write-Verbose "Resolved conflict - imported $ModuleName v$LatestVersion"
} else {throw}
}
} else {Write-Verbose "Module '$ModuleName' already loaded v$((Get-Module -Name $ModuleName).Version)"}
#endregion
#region ---------------------------------------------------[Static Variables]------------------------------------------------------
# ==========> Logging (Invoke-TboneLog) <==============================================================================
if([string]::IsNullOrWhiteSpace($LogName)) {[string]$LogName = $ScriptActionName} # Logname defaults to script action name
# ==========> Reporting (Invoke-ScriptReport) <========================================================================
if([string]::IsNullOrWhiteSpace($ReportTitle)) {[string]$ReportTitle = $ScriptActionName} # Report title defaults to script action name
[datetime]$ReportStartTime = ([DateTime]::Now) # Script start time for reporting
[hashtable]$ReportResults = @{} # Initialize empty hashtable for report results
[scriptblock]$AddReport = {param($Target,$OldValue,$NewValue,$Action,$Details) # Small inline function to add report entries
if(-not $ReportResults.ContainsKey($Action)){$ReportResults[$Action]=[System.Collections.ArrayList]::new()}
$null=$ReportResults[$Action].Add([PSCustomObject]@{Target=$Target;OldValue=$OldValue;NewValue=$NewValue;Action=$Action;Details=$Details})}
# Data collection variables - initialized dynamically during script execution
[datetime]$SignInsStartTime = (Get-Date).AddDays(-$SigninsTimeSpan) # Sign-in logs start time
#endregion
#region ---------------------------------------------------[Functions]------------------------------------------------------------
function Invoke-ConnectMgGraph {
<#
.SYNOPSIS
Connects to Microsoft Graph API with multiple authentication methods.
.DESCRIPTION
Supports Managed Identity, Interactive, Client Secret, and Certificate authentication...
.NOTES
Author: @MrTbone_se (T-bone Granheden)
Version: 2.0
Version History:
1.0 - Initial version
2.0 - 2026-01-09 - Changed parameter names and fixed minor bugs on certificate authentication
2.1 - 2026-02-24 - Fixed ClientSecret authentication PSCredential creation
2.2 - 2026-03-01 - Fix to support both secure and non secure secret string using object type
#>
[CmdletBinding()]
param (
[Parameter( HelpMessage = "Array of required Microsoft Graph API permission scopes example:('User.Read.All','DeviceManagementManagedDevices.ReadWrite.All') ")]
[string[]]$RequiredScopes = @("User.Read.All"),
[Parameter( HelpMessage = "Entra ID Tenant ID (directory ID) (required for Client Secret or Certificate authentication)")]
[ValidateNotNullOrEmpty()]
[string]$AuthTenantId,
[Parameter( HelpMessage = "Entra ID Application ID (ClientID) (required for Client Secret or Certificate authentication)")]
[ValidateNotNullOrEmpty()]
[string]$AuthClientId,
[Parameter( HelpMessage = "Client Secret as SecureString or stringfor app-only authentication (require also ClientId and TenantId)")]
[ValidateNotNull()]
[Object]$AuthClientSecret,
[Parameter( HelpMessage = "Certificate subject name for certificate-based authentication (if certificate is stored in CurrentUser or LocalMachine store)")]
[ValidateNotNullOrEmpty()]
[string]$AuthCertName,
[Parameter( HelpMessage = "Certificate thumbprint for certificate-based authentication (if certificate is stored in CurrentUser or LocalMachine store)")]
[ValidateNotNullOrEmpty()]
[string]$AuthCertThumbprint,
[Parameter( HelpMessage = "File path to certificate (.pfx or .cer) for certificate-based authentication (if certificate is stored as a file)")]
[ValidateNotNullOrEmpty()]
[string]$AuthCertPath,
[Parameter( HelpMessage = "Password for certificate file as SecureString (required if certificate is stored as a file and password-protected)")]
[SecureString]$AuthCertPassword
)
Begin {
$ErrorActionPreference = 'Stop'
[string]$ResourceURL = "https://graph.microsoft.com/"
# Detect authentication method based on parameters and environment (priority: ClientSecret > Certificate > ManagedIdentity > Interactive)
[bool]$HasClientId = -not [string]::IsNullOrWhiteSpace($AuthClientId)
[bool]$HasTenantId = -not [string]::IsNullOrWhiteSpace($AuthTenantId)
[bool]$HasClientSecret = $null -ne $AuthClientSecret
[bool]$HasCertInput = -not [string]::IsNullOrWhiteSpace($AuthCertThumbprint) -or -not [string]::IsNullOrWhiteSpace($AuthCertName) -or -not [string]::IsNullOrWhiteSpace($AuthCertPath)
[string]$AuthMethod = if ($HasClientSecret -and $HasClientId -and $HasTenantId) {'ClientSecret'}
elseif ($HasCertInput -and $HasClientId -and $HasTenantId) {'Certificate'}
elseif ($env:IDENTITY_ENDPOINT -and $env:IDENTITY_HEADER) {'ManagedIdentity'}
else {'Interactive'}
Write-Verbose "Using authentication method: $AuthMethod"
}
Process {
try {
# Check for existing valid connection and required scopes
try {
$Context = Get-MgContext -ErrorAction SilentlyContinue
if ($Context) {
Write-Verbose "Existing connection found for: $($Context.Account)"
# Validate scopes only for Interactive auth (Managed Identity/app-only doesn't use delegated scopes)
if ($AuthMethod -eq 'Interactive') {
[string[]]$CurrentScopes = @($Context.Scopes)
[string[]]$MissingScopes = @($RequiredScopes | Where-Object { $_ -notin $CurrentScopes })
if ($MissingScopes.Count -eq 0) {
Write-Verbose "Reusing existing connection with valid scopes"
return $Context.Account
}
Write-Verbose "Existing connection missing scopes: $($MissingScopes -join ', ')"
Disconnect-MgGraph -ErrorAction SilentlyContinue
} else {
# For app-only auth, reuse existing connection
return $Context.Account
}
}
}
catch {
Write-Verbose "No existing connection found"
}
# Build connection parameters
$ConnectParams = @{ NoWelcome = $true }
switch ($AuthMethod) {
'ManagedIdentity' {
Write-Verbose "Connecting with Managed Identity"
# Validate environment variables
if (-not $env:IDENTITY_ENDPOINT -or -not $env:IDENTITY_HEADER) {
throw "Managed Identity environment variables not set"
}
# Get Graph SDK version for compatibility
[version]$GraphVersion = (Get-Module -Name 'Microsoft.Graph.Authentication' -ListAvailable |
Sort-Object Version -Descending | Select-Object -First 1).Version
Write-Verbose "Graph SDK version: $GraphVersion"
if ($GraphVersion -ge [version]"2.0.0") {
$ConnectParams['Identity'] = $true
} else {
# For older SDK versions, get token manually from managed identity endpoint
[hashtable]$Headers = @{
'X-IDENTITY-HEADER' = $env:IDENTITY_HEADER
'Metadata' = 'True'
}
$Response = Invoke-RestMethod -Uri "$($env:IDENTITY_ENDPOINT)?resource=$ResourceURL" -Method GET -Headers $Headers -TimeoutSec 30 -ErrorAction Stop
if (-not $Response -or [string]::IsNullOrWhiteSpace($Response.access_token)) {
throw "Failed to retrieve access token from managed identity endpoint"
}
$ConnectParams['AccessToken'] = $Response.access_token
Write-Verbose "Retrieved managed identity token"
}
}
'ClientSecret' {
Write-Verbose "Connecting with Client Secret"
# Validate required inputs
if (-not $HasClientId -or -not $HasTenantId) {
throw "ClientSecret authentication requires both ClientId and TenantId."
}
# Convert to SecureString if it's a plain string
[SecureString]$SecureClientSecret = if ($AuthClientSecret -is [SecureString]) {$AuthClientSecret}
elseif ($AuthClientSecret -is [string]) {ConvertTo-SecureString -String $AuthClientSecret -AsPlainText -Force}
else {throw "AuthClientSecret must be either a string or SecureString"}
# Now lets use the secure string to build credentials
[System.Management.Automation.PSCredential]$ClientCredential = [System.Management.Automation.PSCredential]::new($AuthClientId, $SecureClientSecret)
$ConnectParams['TenantId'] = $AuthTenantId
$ConnectParams['ClientSecretCredential'] = $ClientCredential
Write-Verbose "Using ClientId: $AuthClientId, TenantId: $AuthTenantId"
}
'Certificate' {
Write-Verbose "Connecting with Certificate"
# Validate required inputs
if (-not $HasClientId -or -not $HasTenantId) {
throw "Certificate authentication requires both ClientId and TenantId."
}
$ConnectParams['ClientId'] = $AuthClientId
$ConnectParams['TenantId'] = $AuthTenantId
# Handle different certificate input methods
if ($AuthCertThumbprint) {
$ConnectParams['CertificateThumbprint'] = $AuthCertThumbprint
Write-Verbose "Using certificate thumbprint: $AuthCertThumbprint"
}
elseif ($AuthCertName) {
$ConnectParams['CertificateName'] = $AuthCertName
Write-Verbose "Using certificate name: $AuthCertName"
}
elseif ($AuthCertPath) {
# Load certificate from file
if (-not (Test-Path $AuthCertPath)) {
throw "Certificate file not found: $AuthCertPath"
}
try {
# Declare variable for StrictMode compliance
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Cert = $null
# Use MachineKeySet flag for Azure Automation compatibility
[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]$KeyFlags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet
if ($AuthCertPassword) {
$Cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new(
$AuthCertPath,
$AuthCertPassword,
$KeyFlags
)
} else {
$Cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($AuthCertPath, [string]::Empty, $KeyFlags)
}
# Validate certificate has private key (required for auth)
if (-not $Cert.HasPrivateKey) {
throw "Certificate does not contain a private key, which is required for authentication"
}
$ConnectParams['Certificate'] = $Cert
Write-Verbose "Loaded certificate from: $AuthCertPath (Subject: $($Cert.Subject), Expires: $($Cert.NotAfter))"
}
catch {
throw "Failed to load certificate: $($_.Exception.Message)"
}
}
else {
throw "No certificate specified. Use CertificateThumbprint, CertificateName, or CertificatePath"
}
}
'Interactive' {
Write-Verbose "Connecting interactively"
# Ensure scopes are a string array
$ConnectParams['Scopes'] = @($RequiredScopes)
}
}
# Connect to Microsoft Graph
try {
Connect-MgGraph @ConnectParams -ErrorAction Stop
Write-Verbose "Successfully connected to Microsoft Graph"
}
catch {
throw "Failed to connect to Microsoft Graph: $($_.Exception.Message)"
}
finally {
# Clear sensitive credentials if used (PSCredential object)
if ($ConnectParams.ContainsKey('ClientSecretCredential')) {
$ConnectParams['ClientSecretCredential'] = $null
}
}
# Validate permissions for delegated auth (Interactive only)
if ($AuthMethod -eq 'Interactive' -and @($RequiredScopes).Count -gt 0) {
try {
$Context = Get-MgContext
$CurrentScopes = @($Context.Scopes)
$ReqScopes = @($RequiredScopes)
$MissingScopes = @($ReqScopes | Where-Object { $_ -notin $CurrentScopes })
if (@($MissingScopes).Count -gt 0) {
throw "Missing required scopes: $($MissingScopes -join ', ')"
}
Write-Verbose "Validated all required scopes: $($RequiredScopes -join ', ')"
}
catch {
throw "Failed to validate permissions: $($_.Exception.Message)"
}
}
# Return account context
$Context = Get-MgContext
$Account = $Context.Account
Write-Verbose "Connected as: $Account"
return $Account
}
catch {
Write-Error "Connection failed: $($_.Exception.Message)"
throw
}
}
End {
# End function and report memory usage
[double]$MemoryUsage = [Math]::Round(([System.GC]::GetTotalMemory($false) / 1MB), 2)
Write-Verbose "Function finished. Memory usage: $MemoryUsage MB"
}
}
function Invoke-TboneLog {
<#
.SYNOPSIS
Unified tiny logger for PowerShell 5.1–7.5 and Azure Automation; overrides Write-* cmdlets and stores all messages in-memory
.DESCRIPTION
A lightweight, cross-platform logging solution that intercepts all Write-Host, Write-Output, Write-Verbose,
Write-Warning, and Write-Error calls. Stores messages in memory with timestamps and can optionally output to:
-LogToGUI - Console (real-time during execution) -LogToDisk - Disk (log file at script completion) -LogToEventlog - Windows Event Log (Application log)
.NOTES
Author: @MrTbone_se (T-bone Granheden)
Version: 1.1.0
Version History:
1.0 - Initial version
1.0.1 - Fixed event log source creation for first-time runs
1.1.0 - Added parameter logName and logEventIds to customize event log source and file log name
#>
[CmdletBinding()]
param(
[Parameter( HelpMessage='Start=Begin logging, Stop=End and output log array')]
[ValidateSet('Start','Stop')]
[string]$LogMode,
[Parameter( HelpMessage='Name of Log, to set name for Eventlog and Filelog')]
[string]$LogName = "PowerShellScript",
[Parameter( HelpMessage='Show output in console during execution')]
[bool]$LogToGUI = $true,
[Parameter( HelpMessage='Write complete log array to Windows Eventlog when script ends')]
[bool]$LogToEventlog = $true,
[Parameter( HelpMessage='EventLog IDs as hashtable: @{Info=11001; Warn=11002; Error=11003}')]
[hashtable]$LogEventIds = @{Info=11001; Warn=11002; Error=11003},
[Parameter( HelpMessage='Return complete log array as Host output when script ends (Good for Intune Remediations)')]
[bool]$LogToHost = $True,
[Parameter( HelpMessage='Write complete log array to filelog on disk when script ends')]
[bool]$LogToDisk = $true,
[Parameter( HelpMessage='Path where Disk logs are saved (if LogToDisk is enabled)')]
[string]$LogPath = "$env:TEMP"
)
# Auto-detect mode: if logger functions is already loaded in memory and no mode specified, assume Stop
if(!$LogMode){$LogMode=if(Get-Variable -Name _l -Scope Global -EA 0){'Stop'}else{'Start'}}
if(!$LogPath){$LogPath=if($global:_p){$global:_p}elseif($env:TEMP){$env:TEMP}else{'/tmp'}}
# Stop mode: Save logs and cleanup
if ($LogMode -eq 'Stop') {
if((Get-Variable -Name _l -Scope Global -EA 0) -and (Test-Path function:\global:_Save)){_Save;if($global:_r){,$global:_l.ToArray()}}
Unregister-Event -SourceIdentifier PowerShell.Exiting -ea 0 -WhatIf:$false
if(Test-Path function:\global:_Clean){_Clean}
return
}
# Start mode: Initialize logging and proxy all Write-* functions
if ($LogMode -eq 'Start') {
# Create helper functions and variables
$global:_az=$env:AZUREPS_HOST_ENVIRONMENT -or $env:AUTOMATION_ASSET_ACCOUNTID # Detect Azure Automation environment
$global:_l=[Collections.Generic.List[string]]::new();$global:_g=$LogToGUI;$global:_s=$Logname;$global:_n="{0}-{1:yyyyMMdd-HHmmss}"-f$Logname,(Get-Date);$global:_p=$LogPath;$global:_d=$LogToDisk;$global:_e=$LogToEventlog;$global:_i=$LogEventIds;$global:_r=$LogToHost;$global:_w=([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT)
if(!(Test-Path function:\global:_Time)){function global:_Time{Get-Date -f 'yyyy-MM-dd,HH:mm:ss'}}
if(!(Test-Path function:\global:_ID)){function global:_ID{$c=(Get-PSCallStack)[2];$n=if($c.Command -and $c.Command -ne '<ScriptBlock>'){$c.Command}elseif($c.FunctionName -and $c.FunctionName -ne '<ScriptBlock>'){$c.FunctionName}else{'Main-Script'};if($n -like '*.ps1'){'Main-Script'}else{$n}}}
if(!(Test-Path function:\global:_Save)){function global:_Save{try{if($global:_d){[IO.Directory]::CreateDirectory($global:_p)|Out-Null;[IO.File]::WriteAllLines((Join-Path $global:_p "$($global:_n).log"),$global:_l.ToArray())};if($global:_e -and $global:_w){$isAdmin=$false;try{$id=[Security.Principal.WindowsIdentity]::GetCurrent();$isAdmin=([Security.Principal.WindowsPrincipal]::new($id)).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)}catch{};$la=$global:_l -join"`n";$h=$la -match ',ERROR,';$et=if($h){'Error'}elseif($la -match ',WARN,'){'Warning'}else{'Information'};$eid=if($h){$global:_i.Error}elseif($la -match ',WARN,'){$global:_i.Warn}else{$global:_i.Info};$ok=$false;try{Write-EventLog -LogName Application -Source $global:_s -EventId $eid -EntryType $et -Message $la -EA Stop;$ok=$true}catch{};if(-not $ok -and $isAdmin){try{[Diagnostics.EventLog]::CreateEventSource($global:_s,'Application')}catch{};try{Write-EventLog -LogName Application -Source $global:_s -EventId $eid -EntryType $et -Message $la}catch{}}}}catch{}}}
if(!(Test-Path function:\global:_Clean)){function global:_Clean{$WhatIfPreference=$false;Remove-Item -Path function:\Write-Host,function:\Write-Output,function:\Write-Warning,function:\Write-Error,function:\Write-Verbose,function:\_Save,function:\_Clean,function:\_ID,function:\_Time -ea 0 -Force;Remove-Variable -Name _l,_g,_s,_n,_p,_d,_e,_i,_r,_w,_az -Scope Global -ea 0}}
# Register exit handler FIRST (before Write-* overrides)
$null=Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action{if($global:_l){try{_Save}catch{}};if(Test-Path function:\_Clean){_Clean}} -MaxTriggerCount 1
# Create Write-* proxy functions (skip in Azure Automation)
function Script:Write-Host{$m="$args";$c=(Get-PSCallStack)[1];$r="Row$($c.ScriptLineNumber)";$e="$(_Time),INFO,$r,$(_ID),$m";$global:_l.Add($e);if($global:_g){if($global:_az){Microsoft.PowerShell.Utility\Write-Output $m}else{Microsoft.PowerShell.Utility\Write-Host $e -ForegroundColor Green}}}
function Script:Write-Output{$m="$args";$c=(Get-PSCallStack)[1];$r="Row$($c.ScriptLineNumber)";$e="$(_Time),OUTPUT,$r,$(_ID),$m";$global:_l.Add($e);if($global:_g){if($global:_az){Microsoft.PowerShell.Utility\Write-Output $m}else{Microsoft.PowerShell.Utility\Write-Host $e -ForegroundColor Green}}}
function Script:Write-Verbose{$m="$args";$c=(Get-PSCallStack)[1];$r="Row$($c.ScriptLineNumber)";$e="$(_Time),VERBOSE,$r,$(_ID),$m";$global:_l.Add($e);if($global:_g -and $VerbosePreference -ne 'SilentlyContinue'){if($global:_az){Microsoft.PowerShell.Utility\Write-Verbose $m}else{Microsoft.PowerShell.Utility\Write-Host $e -ForegroundColor cyan}}}
function Script:Write-Warning{$m="$args";$c=(Get-PSCallStack)[1];$r="Row$($c.ScriptLineNumber)";$e="$(_Time),WARN,$r,$(_ID),$m";$global:_l.Add($e);if($global:_g){if($global:_az){Microsoft.PowerShell.Utility\Write-Warning $m}else{Microsoft.PowerShell.Utility\Write-Host $e -ForegroundColor Yellow}};if($WarningPreference -eq 'Stop'){_Save;_Clean;exit}}
function Script:Write-Error{$m="$args";$c=(Get-PSCallStack)[1];$r="Row$($c.ScriptLineNumber)";$e="$(_Time),ERROR,$r,$(_ID),$m";$global:_l.Add($e);if($global:_g){if($global:_az){Microsoft.PowerShell.Utility\Write-Error $m}else{Microsoft.PowerShell.Utility\Write-Host $e -ForegroundColor Red}};if($ErrorActionPreference -eq 'Stop'){_Save;_Clean;exit}}
}
}
function Invoke-MgGraphRequestSingle {
<#
.SYNOPSIS
Makes a single Graph API call with Invoke-MgGraphRequest and support for filtering, property selection, and count queries.
.DESCRIPTION
Makes Graph API calls using Invoke-MgGraphRequest but add automatic pagination, throttling handling, and exponential backoff retry logic.
Supports filtering, property selection, and count queries. Returns all pages of results automatically.
Handles skip token expiration by restarting query with smaller page size and deduplication.
.NOTES
Author: @MrTbone_se (T-bone Granheden)
Version: 2.2
Version History:
1.0 - Initial version
2.0 - Fixed some small bugs with throttling handling
2.1 - Added more error handling for Post/Patch methods
2.2 - Added skip token expiration recovery with automatic restart and deduplication
#>
[CmdletBinding()]
Param(
[Parameter( HelpMessage = "The Graph API version ('beta' or 'v1.0')")]
[ValidateSet('beta', 'v1.0')]
[string]$GraphRunProfile = "v1.0",
[Parameter( HelpMessage = "The HTTP method for the request(e.g., 'GET', 'PATCH', 'POST', 'DELETE')")]
[ValidateSet('GET', 'PATCH', 'POST', 'DELETE')]
[String]$GraphMethod = "GET",
[Parameter(Mandatory=$true, HelpMessage = "The Graph API endpoint path to target (e.g., 'me', 'users', 'groups')")]
[ValidateNotNullOrEmpty()]
[string]$GraphObject,
[Parameter( HelpMessage = "Request body for POST/PATCH operations")]
[string[]]$GraphBody,
[Parameter( HelpMessage = "Graph API properties to include")]
[string[]]$GraphProperties,
[Parameter( HelpMessage = "Graph API filters to apply")]
[string]$GraphFilters,
[Parameter( HelpMessage = "Page size (Default is 500 for better stability)")]
[ValidateRange(1,1000)]
[int]$GraphPageSize = 500,
[Parameter( HelpMessage = "Skip pagination and only get the first page. (Default is false)")]
[bool]$GraphSkipPagination = $false,
[Parameter( HelpMessage = "Include count of total items. Adds ConsistencyLevel header. (Default is false)")]
[bool]$GraphCount = $false,
[Parameter( HelpMessage = "Delay in milliseconds between requests if throttled")]
[ValidateRange(100,5000)]
[int]$GraphWaitTime = 1000,
[Parameter( HelpMessage = "Maximum retry attempts for failed requests when throttled")]
[ValidateRange(1,10)]
[int]$GraphMaxRetry = 3
)
Begin {
# Initialize variables
[nullable[int]]$TotalCount = $null
[System.Collections.ArrayList]$PsobjectResults = [System.Collections.ArrayList]::new()
[int]$RetryCount = 0
[string]$Uri = "https://graph.microsoft.com/$GraphRunProfile/$GraphObject"
[System.Collections.ArrayList]$GraphQueryParams = [System.Collections.ArrayList]::new()
# Skip token recovery variables (only used if needed)
[string]$BaseUri = $Uri
[System.Collections.Generic.HashSet[string]]$SeenIds = $null
# Add Count parameter to Query if requested
if ($GraphCount) {[void]$GraphQueryParams.Add("`$count=true")}
# Add page size parameter to Query if specified
if ($GraphMethod -eq 'GET') {[void]$GraphQueryParams.Add("`$top=$GraphPageSize")}
# Add properties to Query if specified
if ($GraphProperties) {
[string]$Select = $GraphProperties -join ','
[void]$GraphQueryParams.Add("`$select=$Select")
}
# Add filters to Query if specified
if ($GraphFilters) {
[void]$GraphQueryParams.Add("`$filter=$([System.Web.HttpUtility]::UrlEncode($GraphFilters))")
}
# Combine query parameters into URI
if ($GraphQueryParams.Count -gt 0) {$Uri += "?" + ($GraphQueryParams -join '&')}
}
Process {
do {
try {
Write-Verbose "Making request to: $Uri"
$I = 1
do {
$Response = $null
Write-Verbose "Requesting page $I with $GraphPageSize items"
# Set default parameters for Invoke-MgGraphRequest
$Params = @{
Method = $GraphMethod
Uri = $Uri
ErrorAction = 'Stop'
OutputType = 'PSObject'
Verbose = $false
}
# Add ConsistencyLevel header if Count is requested
if ($GraphCount) { $Params['Headers'] = @{ 'ConsistencyLevel' = 'eventual' } }
# Add additional parameters based on method
if ($GraphMethod -in 'POST', 'PATCH') {
$Params['Body'] = $GraphBody
if (-not $Params.ContainsKey('Headers')) {
$Params['Headers'] = @{}
}
$Params['Headers']['Content-Type'] = 'application/json'
Write-Verbose "Request body: $($GraphBody | ConvertTo-Json -Depth 10)"
}
# Send request to Graph API
try {
$Response = Invoke-MgGraphRequest @Params
Write-Verbose "Request successful"
}
catch {
# Check if this is an expired skip token error
if ($_.Exception.Message -match "Skip token.*expired|Skip token is null") {
Write-Warning "Skip token expired at page $I after $($PsobjectResults.Count) items. Restarting..."
# Initialize deduplication on first skip token failure
if ($null -eq $SeenIds) {
$SeenIds = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
$PsobjectResults | Where-Object {$_.id} | ForEach-Object {[void]$SeenIds.Add($_.id)}
}
# Reduce page size and rebuild URI
$GraphPageSize = [Math]::Max([int]($GraphPageSize / 2), 100)
$GraphQueryParams.Clear()
if ($GraphCount) {[void]$GraphQueryParams.Add("`$count=true")}
if ($GraphMethod -eq 'GET') {[void]$GraphQueryParams.Add("`$top=$GraphPageSize")}
if ($GraphProperties) {[void]$GraphQueryParams.Add("`$select=$($GraphProperties -join ',')")}
if ($GraphFilters) {[void]$GraphQueryParams.Add("`$filter=$([System.Web.HttpUtility]::UrlEncode($GraphFilters))")}
$Uri = $BaseUri + "?" + ($GraphQueryParams -join '&')
break
}
Write-Verbose "Request failed with error: $($_.Exception.Message)"
throw
}
if ($GraphMethod -in 'POST', 'PATCH', 'DELETE') {return $Response}
# Add items (with deduplication if skip token recovery active)
if ($Response.value) {
if ($SeenIds) {
foreach ($item in $Response.value) {
if ($item.id -and -not $SeenIds.Contains($item.id)) {
[void]$PsobjectResults.Add($item)
[void]$SeenIds.Add($item.id)
}
}
} else {
[void]$PsobjectResults.AddRange($Response.value)
}
}
# Capture count from first response if requested
if ($GraphCount -and $null -eq $TotalCount -and $Response.'@odata.count') {
$TotalCount = $Response.'@odata.count'
Write-Verbose "Total count available: $TotalCount items"
}
Write-Verbose "Retrieved page $I, Now total: $($PsobjectResults.Count) items"
# Check for next page
if ($GraphSkipPagination) {
Write-Verbose "SkipPagination enabled, stopping after first page"
$Uri = $null
}
elseif ($Response.PSObject.Properties.Name -contains '@odata.nextLink') {
if ($Response.'@odata.nextLink') {
$Uri = $Response.'@odata.nextLink'
Write-Verbose "Next page found: $Uri"
}
else {
Write-Verbose "No @odata.nextLink value, stopping pagination"
$Uri = $null
}
}
else {
Write-Verbose "No more pages found"
$Uri = $null
}
$I++
} while ($Uri)
Write-Verbose "Completed pagination. Returning array with $($PsobjectResults.Count) items"
# Return results with count if requested
if ($GraphCount -and $null -ne $TotalCount) {
return [PSCustomObject]@{
Items = $PsobjectResults
Count = $TotalCount
}
}
return $PsobjectResults # Success, return results and exit retry loop
}
catch {
[string]$ErrorMessage = $_.Exception.Message
# Get full error string including nested JSON messages for better pattern matching
[string]$FullErrorString = $_ | Out-String
Write-Warning "Request failed (Retry attempt $($RetryCount + 1)/$GraphMaxRetry): $ErrorMessage"
# First check for throttling in error message (Invoke-MgGraphRequest may internally retry and throw with embedded 429 info)
if ($ErrorMessage -match "TooManyRequests|Too Many Requests|429" -or $FullErrorString -match "TooManyRequests|Too Many Requests|429") {
# Throttling detected from error message - use exponential backoff
[int]$Delay = [math]::Min(($GraphWaitTime * ([math]::Pow(2, $RetryCount + 1))), 60000)
Write-Warning "Throttling detected from error message. Waiting $Delay milliseconds before retrying."
Start-Sleep -Milliseconds $Delay
}
# Check if the exception has response details (standard HTTP errors)
elseif ($_.Exception.PSObject.Properties.Name -contains 'Response' -and $_.Exception.Response) {
[object]$StatusCode = $_.Exception.Response.StatusCode
# Use switch to handle specific status codes (handle both enum names and numeric values)
switch ($StatusCode) {
{$_ -eq 429 -or $_ -eq 'TooManyRequests'} { # Throttling
$RetryAfter = $_.Exception.Response.Headers["Retry-After"]
if ($RetryAfter) {
Write-Warning "Throttling detected (429). Waiting $($RetryAfter * 1000) milliseconds before retrying."
Start-Sleep -Milliseconds ($RetryAfter * 1000)
} else {
[int]$Delay = [math]::Min(($GraphWaitTime * ([math]::Pow(2, $RetryCount))), 60000)
Write-Warning "Throttling detected (429). No Retry-After header found. Waiting $Delay milliseconds before retrying."
Start-Sleep -Milliseconds $Delay
}
# Break not needed, will fall through to retry logic below
}
{$_ -eq 404 -or $_ -eq 'NotFound'} { # Not Found
# For DELETE operations, 404 means already deleted - treat as success
if ($GraphMethod -eq 'DELETE') {
Write-Verbose "Resource not found (404) - treating as already deleted"
return [PSCustomObject]@{ id = $GraphObject; status = 204; note = 'Already deleted' }
}
Write-Warning "Resource not found (404). Error: $ErrorMessage"
throw "$ErrorMessage (Object Deleted/No User License)"
}
{$_ -eq 400 -or $_ -eq 'BadRequest'} { # Bad Request
if ($ErrorMessage -match "Skip token.*expired|Skip token is null" -or $FullErrorString -match "Skip token.*expired|Skip token is null") {
# Fallback - should normally be handled in inner try-catch
Write-Warning "Skip token expired (outer catch fallback). Returning $($PsobjectResults.Count) items."
return $PsobjectResults
}
if ($ErrorMessage -match "does not have intune license or is deleted" -or $FullErrorString -match "does not have intune license or is deleted") { # Check if no license, common for Intune queries
Write-Warning "Object Deleted or User has no Intune license"
return "$ErrorMessage (Object Deleted/No User License)"
}
# For DELETE operations, "not found" patterns mean already removed - treat as success
if ($GraphMethod -eq 'DELETE' -and ($ErrorMessage -imatch 'does not exist|not found|cannot be found|no longer exists|was not found|resource .+ not found' -or $FullErrorString -imatch 'does not exist|not found|cannot be found|no longer exists')) {
Write-Verbose "Object already removed or not found (400) - treating as success"
return [PSCustomObject]@{ id = $GraphObject; status = 204; note = 'Already removed' }
}
# For POST operations, "already exists" patterns mean already created - treat as success
if ($GraphMethod -eq 'POST' -and ($ErrorMessage -imatch 'already exist|duplicate|conflict|references already exist|object reference already exist' -or $FullErrorString -imatch 'already exist|duplicate|conflict')) {
Write-Verbose "Object already exists (400) - treating as success"
return [PSCustomObject]@{ id = $GraphObject; status = 200; note = 'Already exists' }
}
Write-Error "Bad request (400). Error: $ErrorMessage"
throw $_
}
{$_ -eq 403 -or $_ -eq 'Forbidden'} { # Forbidden / Access Denied
Write-Error "Access denied (403). Error: $ErrorMessage"
throw $_
}
default { # Other HTTP errors - Use generic retry
[int]$Delay = [math]::Min(($GraphWaitTime * ([math]::Pow(2, $RetryCount))), 60000)
Write-Warning "HTTP error $StatusCode. Waiting $Delay milliseconds before retrying."
Start-Sleep -Milliseconds $Delay
# Break not needed, will fall through to retry logic below
}
}
} else {
# Non-HTTP errors (e.g., network issues, DNS resolution) - Use generic retry
[int]$Delay = [math]::Min(($GraphWaitTime * ([math]::Pow(2, $RetryCount))), 60000)
Write-Warning "Non-HTTP error. Waiting $Delay milliseconds before retrying. Error: $ErrorMessage"
Start-Sleep -Milliseconds $Delay
}
# Increment retry count and check if max retries exceeded ONLY if not already thrown
$RetryCount++
if ($RetryCount -gt $GraphMaxRetry) {
Write-Error "Request failed after $($GraphMaxRetry) retries. Aborting."
throw "Request failed after $($GraphMaxRetry) retries. Last error: $ErrorMessage"
}
# If retries not exceeded and error was potentially retryable (e.g., 429, other HTTP, non-HTTP), the loop will continue
}
} while ($RetryCount -le $GraphMaxRetry)
Write-Error "Request failed after $($GraphMaxRetry) retries. Aborting."
throw "Request failed after $($GraphMaxRetry) retries." # Re-throw the exception after max retries
}
End {
# End function and report memory usage
[double]$MemoryUsage = [Math]::Round(([System.GC]::GetTotalMemory($false) / 1MB), 2)
Write-Verbose "Function finished. Memory usage: $MemoryUsage MB"
}
}
function Invoke-MgGraphRequestBatch {
<#
.SYNOPSIS
Processes multiple Graph API requests in batches for improved performance.
.DESCRIPTION
Sends Graph API requests in batches (up to 20 per batch) to efficiently process large numbers of objects.
Handles throttling, retries, and provides progress tracking. Supports GET, PATCH, POST, and DELETE operations.
.NOTES
Author: @MrTbone_se (T-bone Granheden)
Version: 1.3
Version History:
1.0 - Initial version
1.1 - Added version on function to keep track of changes, minor bug fixes
1.2 - Added more error handling for Post/Patch methods
1.3 - Added a new parameter GraphNoObjectIdInUrl to allow requests where objectId should not be appended to the URL
#>
[CmdletBinding()]
Param(
[Parameter(
HelpMessage = "The Graph API version ('beta' or 'v1.0')")]
[ValidateSet('beta', 'v1.0')]
[string]$GraphRunProfile = "v1.0",
[Parameter(
HelpMessage = "The HTTP method for the request(e.g., 'GET', 'PATCH', 'POST', 'DELETE')")]
[ValidateSet('GET', 'PATCH', 'POST', 'DELETE')]
[String]$GraphMethod = "GET",
[Parameter(
HelpMessage = "The Graph API endpoint path to target (e.g., 'me', 'users', 'groups')")]
[string]$GraphObject,
[Parameter(
HelpMessage = "Array of objects to process in batches")]
[System.Object[]]$GraphObjects,
[Parameter(HelpMessage = "Do not append objectId to the request URL (useful for endpoints like POST groups/id/members)")]
[bool]$GraphNoObjectIdInUrl = $false,
[Parameter(
HelpMessage = "The Graph API query on the objects")]
[string]$GraphQuery,
[Parameter(HelpMessage = "Request body for POST/PATCH operations")]
[object]$GraphBody,
[Parameter(HelpMessage = "Graph API properties to include")]
[string[]]$GraphProperties,
[Parameter(HelpMessage = "Graph API filters to apply")]
[string]$GraphFilters,
[Parameter(HelpMessage = "Batch size (max 20 objects per batch)")]
[ValidateRange(1,20)]
[int]$GraphBatchSize = 20,
[Parameter(HelpMessage = "Delay between batches in milliseconds")]
[ValidateRange(100,5000)]
[int]$GraphWaitTime = 1000,
[Parameter(HelpMessage = "Maximum retry attempts for failed requests")]
[ValidateRange(1,10)]
[int]$GraphMaxRetry = 3
)
Begin {
$ErrorActionPreference = 'Stop'
[scriptblock]$script:GetTimestamp = { ([DateTime]::Now).ToString('yyyy-MM-dd HH:mm:ss') }
[datetime]$StartTime = Get-Date
[int]$RetryCount = 0
[int]$TotalObjects = $GraphObjects.Count
# Pre-allocate collections with capacity for better performance
[System.Collections.Generic.List[PSObject]]$CollectedObjects = [System.Collections.Generic.List[PSObject]]::new($TotalObjects)
[System.Collections.Generic.List[PSObject]]$RetryObjects = [System.Collections.Generic.List[PSObject]]::new()
# Check execution context once
[bool]$ManagedIdentity = [bool]$env:AUTOMATION_ASSET_ACCOUNTID
Write-Verbose "Running in $(if ($ManagedIdentity) { 'Azure Automation' } else { 'interactive PowerShell' }) context"
# Pre-calculate common values to avoid repeated work
[string]$BatchUri = "https://graph.microsoft.com/$GraphRunProfile/`$batch"
[hashtable]$BatchHeaders = @{'Content-Type' = 'application/json'}
# Build URL query parameters once (they're the same for all requests)
[string]$UrlQueryString = $null
if ($GraphProperties -or $GraphFilters) {
[System.Collections.Generic.List[string]]$UrlParams = [System.Collections.Generic.List[string]]::new()
if ($GraphProperties) {
$UrlParams.Add("`$select=$($GraphProperties -join ',')")
}
if ($GraphFilters) {
$UrlParams.Add("`$filter=$([System.Web.HttpUtility]::UrlEncode($GraphFilters))")
}
$UrlQueryString = "?" + ($UrlParams -join '&')
}
# Pre-determine if method needs body/headers (avoid repeated checks)
[bool]$NeedsBody = $GraphMethod -in 'PATCH','POST'
[string]$ContentTypeHeader = if ($NeedsBody) { 'application/json' } else { $null }
Write-Verbose "Graph batch processing initialized for $TotalObjects objects"
}
Process {
try {