-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-IntuneUsersAndDevicesFromGroups.ps1
More file actions
660 lines (567 loc) · 26.7 KB
/
Get-IntuneUsersAndDevicesFromGroups.ps1
File metadata and controls
660 lines (567 loc) · 26.7 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
<#
.SYNOPSIS
Query Intune devices from groups, filter by OS version, and populate target groups with devices or users
.DESCRIPTION
Queries Intune devices from Entra ID groups (containing users or devices), filters by OS version,
and populates target groups with either the matching devices or their primary users.
Recursively expands nested groups. Uses batch API calls for performance.
Runs in Azure Automation with managed identity or interactively with delegated permissions.
.EXAMPLE
# Find users with iOS devices < 18.0 and add to notification group
.\Get-IntuneUsersAndDevicesFromGroups.ps1 -SourceGroupName @("Sales", "Marketing") -IOSVersion "18.0" -Operator "lt" -TargetGroupName "iOS-Update-Notifications" -AddToGroup Users
.EXAMPLE
# Get all Windows 10+ devices from Finance team and add devices to group
.\Get-IntuneUsersAndDevicesFromGroups.ps1 -SourceGroupName @("Finance Team") -WindowsVersion "10" -Operator "ge" -TargetGroupName "Finance-Windows-Devices" -AddToGroup Devices
.EXAMPLE
# Get all devices (iOS and Windows) from a group without version filtering
.\Get-IntuneUsersAndDevicesFromGroups.ps1 -SourceGroupName @("IT Department") -TargetGroupName "All-IT-Devices" -AddToGroup Devices
.EXAMPLE
# Discovery mode - report only, no changes
.\Get-IntuneUsersAndDevicesFromGroups.ps1 -SourceGroupName @("Sales") -WindowsVersion "10" -Operator "ge" -WhatIf $true
.EXAMPLE
# Clear target group and add Windows devices with specific build
.\Get-IntuneUsersAndDevicesFromGroups.ps1 -SourceGroupName @("Team - IT") -WindowsVersion "10.0.22631" -Operator "lt" -TargetGroupName "Windows-Outdated" -AddToGroup Devices -ClearTargetGroup $true
.NOTES
Authors:
Martin Bengtsson (https://imab.dk)
Christian Frohn (https://christianfrohn.dk)
Date: November 2025
Version History:
1.0 - November 2025
- Initial release
1.1 - December 12, 2025
- Added device deduplication using hashtable instead of array
- Removed per-device Intune API queries - now uses cached device collection
- Removed per-device Azure AD lookups - implemented batch query of all Azure AD devices
- Added parameter validation for version format (numeric only)
- Optimized device cache to always populate when processing groups
- Removed redundant group lookups - groups queried once and cached
- Removed redundant null initializations and duplicate cache checks
- Removed unreachable fallback code paths
- Added Microsoft.Graph.Identity.DirectoryManagement module for Get-MgDevice cmdlet
- Improved error handling with detailed error output
- Enhanced performance: Reduced API calls from O(n) per device to O(1) batch operations
- Fixed Azure AD device ID lookup to use batch dictionary lookup
- Cleaned up unused variables and redundant code paths
#>
[CmdletBinding()]
param(
[string[]]$SourceGroupName,
[string]$IOSVersion,
[string]$WindowsVersion,
[ValidateSet("eq", "ne", "lt", "le", "gt", "ge")]
[string]$Operator = "lt",
[string]$TargetGroupName,
[ValidateSet("Users", "Devices", "Both")]
[string]$AddToGroup,
[bool]$ClearTargetGroup = $false,
[bool]$WhatIf = $false
)
# Output script start immediately
Write-Output "--- SCRIPT STARTING ---"
Write-Output "Timestamp: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Output "PowerShell Version: $($PSVersionTable.PSVersion)"
Write-Output "Parameters received:"
Write-Output " SourceGroupName: $($SourceGroupName -join ', ')"
Write-Output " IOSVersion: $IOSVersion"
Write-Output " WindowsVersion: $WindowsVersion"
Write-Output " Operator: $Operator"
Write-Output " TargetGroupName: $TargetGroupName"
Write-Output " AddToGroup: $AddToGroup"
# Check for required modules
Write-Output ""
Write-Output "Checking for required modules..."
$requiredModules = @(
'Microsoft.Graph.Authentication',
'Microsoft.Graph.DeviceManagement',
'Microsoft.Graph.Groups',
'Microsoft.Graph.Users',
'Microsoft.Graph.Identity.DirectoryManagement'
)
foreach ($moduleName in $requiredModules) {
$module = Get-Module -ListAvailable -Name $moduleName | Select-Object -First 1
if ($module) {
Write-Output " [OK] $moduleName - Version $($module.Version)"
} else {
Write-Output " [MISSING] $moduleName - NOT FOUND"
throw "Required module '$moduleName' is not installed"
}
}
Write-Output ""
Write-Output "Importing modules..."
try {
Import-Module Microsoft.Graph.Authentication -ErrorAction Stop
Write-Output " [OK] Imported Microsoft.Graph.Authentication"
Import-Module Microsoft.Graph.DeviceManagement -ErrorAction Stop
Write-Output " [OK] Imported Microsoft.Graph.DeviceManagement"
Import-Module Microsoft.Graph.Groups -ErrorAction Stop
Write-Output " [OK] Imported Microsoft.Graph.Groups"
Import-Module Microsoft.Graph.Users -ErrorAction Stop
Write-Output " [OK] Imported Microsoft.Graph.Users"
Import-Module Microsoft.Graph.Identity.DirectoryManagement -ErrorAction Stop
Write-Output " [OK] Imported Microsoft.Graph.Identity.DirectoryManagement"
}
catch {
Write-Output "ERROR importing modules: $($_.Exception.Message)"
throw
}
# Connect to Graph
# Detect if running in Azure Automation
if ($env:AUTOMATION_ASSET_ACCOUNTID) {
# Running in Azure Automation - use managed identity
Write-Output "Detected Azure Automation environment - using managed identity..."
try {
# For system-assigned managed identity:
Connect-MgGraph -Identity -NoWelcome
Write-Output "Successfully connected to Microsoft Graph using managed identity"
}
catch {
Write-Output "FAILED to connect using managed identity: $($_.Exception.Message)"
throw
}
# For user-assigned managed identity, uncomment and set ClientId:
# $ClientId = "YOUR-USER-ASSIGNED-MANAGED-IDENTITY-CLIENT-ID"
# Connect-MgGraph -Identity -ClientId $ClientId -NoWelcome
}
else {
# Running interactively - use delegated permissions
Write-Output "Running in interactive mode - using delegated permissions..."
$scopes = @(
"DeviceManagementManagedDevices.Read.All",
"Group.Read.All",
"Group.ReadWrite.All",
"User.Read.All",
"GroupMember.Read.All",
"Device.Read.All"
)
Write-Verbose "Connecting to Microsoft Graph with delegated permissions..."
Connect-MgGraph -Scopes $scopes -NoWelcome
Write-Verbose "Connected successfully"
}
# Helper function to compare versions
function Compare-DeviceVersion {
param(
[string]$CurrentVersion,
[string]$TargetVersion,
[string]$Operator
)
try {
# Ensure version strings have at least 2 parts (Major.Minor)
$currentVer = $CurrentVersion
$targetVer = $TargetVersion
if ($currentVer -notmatch '\.') { $currentVer += '.0' }
if ($targetVer -notmatch '\.') { $targetVer += '.0' }
$current = [version]$currentVer
$target = [version]$targetVer
switch ($Operator) {
"eq" { return $current -eq $target }
"ne" { return $current -ne $target }
"lt" { return $current -lt $target }
"le" { return $current -le $target }
"gt" { return $current -gt $target }
"ge" { return $current -ge $target }
}
} catch {
Write-Verbose "Failed to parse version: Current=$CurrentVersion, Target=$TargetVersion"
return $false
}
}
# Helper function to get devices by OS and version
function Get-DevicesByOSVersion {
param(
[string]$OS,
[string]$Version,
[string]$Operator
)
$filter = "operatingSystem eq '$OS'"
if ($Operator -eq "eq") { $filter += " and osVersion eq '$Version'" }
elseif ($Operator -eq "ne") { $filter += " and osVersion ne '$Version'" }
$foundDevices = Get-MgDeviceManagementManagedDevice -Filter $filter -All
# Client-side filtering for lt/le/gt/ge operators
if ($Operator -in @("lt", "le", "gt", "ge")) {
$foundDevices = $foundDevices | Where-Object {
Compare-DeviceVersion -CurrentVersion $_.OsVersion -TargetVersion $Version -Operator $Operator
}
}
return $foundDevices
}
# Helper function to add members to a group
function Add-MembersToGroup {
param(
[array]$Members,
[string]$GroupId,
[string]$MemberType,
[string]$GroupName,
[bool]$WhatIfMode
)
if ($Members.Count -eq 0) {
Write-Output ""
Write-Output "No $MemberType found to add to group."
return
}
Write-Output ""
Write-Output "Adding $($Members.Count) $MemberType to '$GroupName':"
foreach ($member in $Members) {
if ($WhatIfMode) {
Write-Output " WHATIF: Would add $($member.DisplayName)"
} else {
try {
New-MgGroupMember -GroupId $GroupId -DirectoryObjectId $member.Id -ErrorAction Stop
Write-Output " ADDED: $($member.DisplayName)"
} catch {
if ($_.Exception.Message -like "*already exist*" -or $_.Exception.Message -like "*already a member*") {
Write-Output " ALREADY MEMBER: $($member.DisplayName)"
} else {
Write-Output " FAILED: $($member.DisplayName) - $($_.Exception.Message)"
}
}
}
}
}
# Helper function to apply version filter to a device
function Test-DeviceVersionFilter {
param(
[string]$DeviceOS,
[string]$DeviceVersion,
[string]$IOSVersion,
[string]$WindowsVersion,
[string]$Operator
)
# If iOS filter specified and device is iOS, check version
if ($IOSVersion -and $DeviceOS -eq "iOS") {
return Compare-DeviceVersion -CurrentVersion $DeviceVersion -TargetVersion $IOSVersion -Operator $Operator
}
# If Windows filter specified and device is Windows, check version
if ($WindowsVersion -and $DeviceOS -eq "Windows") {
return Compare-DeviceVersion -CurrentVersion $DeviceVersion -TargetVersion $WindowsVersion -Operator $Operator
}
# If a version filter is specified but doesn't match this device's OS, exclude it
if ($IOSVersion -or $WindowsVersion) {
return $false
}
# No version filter specified, include device
return $true
}
# Helper function to get group members recursively (handles nested groups)
function Get-GroupMembersRecursive {
param(
[string]$GroupId,
[hashtable]$ProcessedGroups = @{}
)
# Prevent circular references (Group A -> Group B -> Group A)
if ($ProcessedGroups.ContainsKey($GroupId)) {
Write-Verbose "Skipping already processed group: $GroupId (circular reference prevention)"
return @()
}
$ProcessedGroups[$GroupId] = $true
Write-Verbose "Retrieving members from group: $GroupId"
$members = Get-MgGroupMember -GroupId $GroupId -All
$allMembers = @()
foreach ($member in $members) {
$memberType = $member.AdditionalProperties.'@odata.type'
if ($memberType -eq '#microsoft.graph.group') {
# Nested group found - recurse into it
$nestedGroupName = $member.AdditionalProperties.displayName
Write-Verbose "Found nested group: $nestedGroupName - expanding recursively"
$nestedMembers = Get-GroupMembersRecursive -GroupId $member.Id -ProcessedGroups $ProcessedGroups
$allMembers += $nestedMembers
}
else {
# Direct member (user or device) - add it
$allMembers += $member
}
}
return $allMembers
}
try {
Write-Output "Script started - validating parameters..."
# Validate parameters
if ($TargetGroupName -and -not $AddToGroup) {
throw "When using -TargetGroupName, you must specify -AddToGroup (Users, Devices, or Both)"
}
# Validate version parameters
if ($IOSVersion -and $IOSVersion -notmatch '^\d+(\.\d+)*$') {
throw "IOSVersion must be in numeric format (e.g., '18.0' or '18.1.2')"
}
if ($WindowsVersion -and $WindowsVersion -notmatch '^\d+(\.\d+)*$') {
throw "WindowsVersion must be in numeric format (e.g., '10' or '10.0.26100')"
}
Write-Output "Parameters validated successfully"
# Enable discovery mode if no TargetGroupName specified
if (-not $TargetGroupName) {
Write-Output ""
Write-Output "--- DISCOVERY MODE - No changes will be made ---"
Write-Output "Use -TargetGroupName and -AddToGroup to add items to a target group"
Write-Output ""
}
# Get devices (using hashtable for deduplication by device name)
$devicesHash = @{}
if ($SourceGroupName) {
Write-Output ""
Write-Output "Processing $($SourceGroupName.Count) source group(s)..."
$groupMembersCache = @{} # Cache recursive member lookups
# First pass: cache all group members (including nested groups)
Write-Output "Scanning groups and caching members..."
foreach ($groupName in $SourceGroupName) {
Write-Output " Looking up group: $groupName"
$checkGroup = Get-MgGroup -Filter "displayName eq '$groupName'" -ErrorAction SilentlyContinue
if ($checkGroup) {
$checkMembers = Get-GroupMembersRecursive -GroupId $checkGroup.Id
$groupMembersCache[$groupName] = $checkMembers
Write-Output " Cached $($checkMembers.Count) members from: $groupName"
}
else {
Write-Output " WARNING: Group '$groupName' not found"
}
}
# Fetch all devices once for efficient processing
Write-Output ""
Write-Output "Pre-fetching all managed devices for efficient processing..."
$allDevicesCached = Get-MgDeviceManagementManagedDevice -All -Property "id,deviceName,operatingSystem,osVersion,userId"
Write-Output "Cached $($allDevicesCached.Count) devices"
foreach ($groupName in $SourceGroupName) {
Write-Output ""
Write-Output "Processing group: $groupName"
# Skip if group wasn't found in first pass
if (-not $groupMembersCache.ContainsKey($groupName)) {
Write-Output " WARNING: Group not found, skipping..."
continue
}
# Use cached members
$members = $groupMembersCache[$groupName]
# Analyze group membership
$groupDevices = $members | Where-Object { $_.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.device' }
$groupUsers = $members | Where-Object { $_.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.user' }
Write-Output " Group members: $($members.Count) total, $($groupDevices.Count) devices, $($groupUsers.Count) users"
if ($groupDevices.Count -gt 0) {
Write-Output " Processing $($groupDevices.Count) devices from group..."
foreach ($device in $groupDevices) {
$deviceOS = $device.AdditionalProperties.operatingSystem
$deviceVersion = $device.AdditionalProperties.operatingSystemVersion
$deviceName = $device.AdditionalProperties.displayName
$deviceId = $device.Id
if (Test-DeviceVersionFilter -DeviceOS $deviceOS -DeviceVersion $deviceVersion -IOSVersion $IOSVersion -WindowsVersion $WindowsVersion -Operator $Operator) {
# Add device with deduplication
if (-not $devicesHash.ContainsKey($deviceName)) {
# Look up the device in Intune cache to get userId
$intuneDevice = $allDevicesCached | Where-Object { $_.DeviceName -eq $deviceName } | Select-Object -First 1
$devicesHash[$deviceName] = [PSCustomObject]@{
Name = $deviceName
OS = $deviceOS
Version = $deviceVersion
UserId = if ($intuneDevice) { $intuneDevice.UserId } else { $null }
AzureDeviceId = $deviceId
}
}
}
}
Write-Output " Found $($devicesHash.Count) unique matching devices so far"
}
if ($groupUsers.Count -gt 0) {
Write-Output " Processing $($groupUsers.Count) users from group..."
$userIds = $groupUsers | ForEach-Object { $_.Id }
foreach ($device in $allDevicesCached) {
if ($device.UserId -in $userIds) {
# Apply OS version filtering
if (Test-DeviceVersionFilter -DeviceOS $device.OperatingSystem -DeviceVersion $device.OsVersion -IOSVersion $IOSVersion -WindowsVersion $WindowsVersion -Operator $Operator) {
# Add to hash for deduplication (Azure AD ID will be looked up in batch later)
if (-not $devicesHash.ContainsKey($device.DeviceName)) {
$devicesHash[$device.DeviceName] = [PSCustomObject]@{
Name = $device.DeviceName
OS = $device.OperatingSystem
Version = $device.OsVersion
UserId = $device.UserId
AzureDeviceId = $null
}
}
}
}
}
Write-Output " Found $($devicesHash.Count) unique matching devices so far"
}
if ($groupDevices.Count -eq 0 -and $groupUsers.Count -eq 0) {
Write-Output " WARNING: Group appears to be empty or contains unsupported member types"
}
}
}
else {
# Get devices by version (organization-wide)
Write-Output ""
Write-Output "Querying organization-wide devices by version..."
if ($IOSVersion) {
$iosDevices = Get-DevicesByOSVersion -OS "iOS" -Version $IOSVersion -Operator $Operator
Write-Output "Found $($iosDevices.Count) iOS devices"
foreach ($device in $iosDevices) {
if (-not $devicesHash.ContainsKey($device.DeviceName)) {
$devicesHash[$device.DeviceName] = [PSCustomObject]@{
Name = $device.DeviceName
OS = "iOS"
Version = $device.OsVersion
UserId = $device.UserId
AzureDeviceId = $null
}
}
}
}
if ($WindowsVersion) {
$winDevices = Get-DevicesByOSVersion -OS "Windows" -Version $WindowsVersion -Operator $Operator
Write-Output "Found $($winDevices.Count) Windows devices"
foreach ($device in $winDevices) {
if (-not $devicesHash.ContainsKey($device.DeviceName)) {
$devicesHash[$device.DeviceName] = [PSCustomObject]@{
Name = $device.DeviceName
OS = "Windows"
Version = $device.OsVersion
UserId = $device.UserId
AzureDeviceId = $null
}
}
}
}
}
# Convert hashtable to array
$devices = @($devicesHash.Values)
if ($devices.Count -eq 0) {
Write-Output ""
Write-Output "No devices found matching criteria"
return
}
Write-Output ""
Write-Output "Looking up primary users for $($devices.Count) unique devices..."
$uniqueUsers = @{}
# Collect all unique user IDs using hashtable for O(1) lookups
$userIdSet = @{}
foreach ($device in $devices) {
if ($device.UserId -and -not $userIdSet.ContainsKey($device.UserId)) {
$userIdSet[$device.UserId] = $true
}
}
$allUserIds = @($userIdSet.Keys)
# Batch lookup users if we have any
if ($allUserIds.Count -gt 0) {
Write-Output "Querying $($allUserIds.Count) unique users..."
# Query users in batch (Graph supports up to 15 IDs in a filter OR clause, so we batch them)
$batchSize = 15
for ($i = 0; $i -lt $allUserIds.Count; $i += $batchSize) {
$batch = $allUserIds[$i..[Math]::Min($i + $batchSize - 1, $allUserIds.Count - 1)]
$filterParts = $batch | ForEach-Object { "id eq '$_'" }
$filter = $filterParts -join " or "
$batchUsers = Get-MgUser -Filter $filter -All -ErrorAction SilentlyContinue
foreach ($user in $batchUsers) {
$uniqueUsers[$user.Id] = $user
}
}
}
# Display devices with user info
Write-Output ""
Write-Output "--- DEVICES FOUND ---"
foreach ($device in $devices) {
$userName = "Unknown User"
$userId = $device.UserId
# Look up user from our cached batch
if ($userId -and $uniqueUsers.ContainsKey($userId)) {
$userName = $uniqueUsers[$userId].DisplayName
}
Write-Output "$($device.Name) ($($device.OS) $($device.Version)) - $userName"
}
# Add users or devices to target group
if ($TargetGroupName) {
$targetGroup = Get-MgGroup -Filter "displayName eq '$TargetGroupName'"
if (!$targetGroup) { throw "Target group '$TargetGroupName' not found" }
# Clear target group if requested
if ($ClearTargetGroup) {
Write-Output ""
Write-Output "Clearing existing members from '$TargetGroupName'..."
$existingMembers = Get-MgGroupMember -GroupId $targetGroup.Id -All
if ($existingMembers.Count -gt 0) {
Write-Output "Found $($existingMembers.Count) existing members to remove"
foreach ($member in $existingMembers) {
$memberType = $member.AdditionalProperties.'@odata.type' -replace '#microsoft.graph.', ''
if ($WhatIf) {
Write-Output " WHATIF: Would remove $memberType $($member.AdditionalProperties.displayName)"
} else {
try {
Remove-MgGroupMemberByRef -GroupId $targetGroup.Id -DirectoryObjectId $member.Id
Write-Output " REMOVED: $memberType $($member.AdditionalProperties.displayName)"
} catch {
Write-Output " FAILED TO REMOVE: $($member.Id) - $($_.Exception.Message)"
}
}
}
Write-Output "Target group cleared successfully"
} else {
Write-Output "Target group is already empty"
}
}
# Add devices to group
if ($AddToGroup -eq "Devices" -or $AddToGroup -eq "Both") {
if ($devices.Count -gt 0) {
Write-Output ""
Write-Output "Looking up Azure AD device IDs for $($devices.Count) devices..."
# Batch query Azure AD devices
$azureDevices = @()
$devicesNeedingLookup = $devices | Where-Object { -not $_.AzureDeviceId }
if ($devicesNeedingLookup.Count -gt 0) {
Write-Output " Querying $($devicesNeedingLookup.Count) devices not yet cached..."
$allAzureDevices = Get-MgDevice -All -Property "id,displayName" -ErrorAction SilentlyContinue
$azureDeviceDict = @{}
foreach ($azDevice in $allAzureDevices) {
$azureDeviceDict[$azDevice.DisplayName] = $azDevice.Id
}
# Update devices with Azure IDs
foreach ($device in $devicesNeedingLookup) {
if ($azureDeviceDict.ContainsKey($device.Name)) {
$device.AzureDeviceId = $azureDeviceDict[$device.Name]
}
}
}
# Build final list of devices with valid Azure AD IDs
foreach ($device in $devices) {
if ($device.AzureDeviceId) {
$azureDevices += [PSCustomObject]@{
Id = $device.AzureDeviceId
DisplayName = $device.Name
}
} else {
Write-Output " WARNING: Device '$($device.Name)' not found in Azure AD"
}
}
Write-Output " Successfully mapped $($azureDevices.Count) of $($devices.Count) devices to Azure AD"
Add-MembersToGroup -Members $azureDevices -GroupId $targetGroup.Id -MemberType "devices" -GroupName $TargetGroupName -WhatIfMode $WhatIf
} else {
Write-Output ""
Write-Output "No devices found to add to group."
}
}
# Add users to group
if ($AddToGroup -eq "Users" -or $AddToGroup -eq "Both") {
$userObjects = @($uniqueUsers.Values | ForEach-Object { [PSCustomObject]@{ Id = $_.Id; DisplayName = $_.DisplayName } })
Add-MembersToGroup -Members $userObjects -GroupId $targetGroup.Id -MemberType "users" -GroupName $TargetGroupName -WhatIfMode $WhatIf
}
}
else {
# No target group specified - show summary
Write-Output ""
Write-Output "--- SUMMARY ---"
Write-Output "Devices found: $($devices.Count)"
Write-Output "Unique users: $($uniqueUsers.Count)"
Write-Output ""
Write-Output "To add these to a group, use -TargetGroupName and -AddToGroup parameters"
}
}
catch {
Write-Output ""
Write-Output "--- FATAL ERROR ---"
Write-Output "Error Type: $($_.Exception.GetType().FullName)"
Write-Output "Error Message: $($_.Exception.Message)"
Write-Output "Stack Trace: $($_.ScriptStackTrace)"
Write-Output "Line Number: $($_.InvocationInfo.ScriptLineNumber)"
Write-Output "Line: $($_.InvocationInfo.Line)"
throw
}
finally {
Write-Output ""
Write-Output "Disconnecting from Microsoft Graph..."
Disconnect-MgGraph | Out-Null
Write-Output "Script completed at: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
}