Skip to content

Commit 0cbd038

Browse files
committed
Refactor group member addition to use bulk requests
Replaces single PATCH request with bulk POST requests for adding group members. Improves error handling and logging by reporting failed additions and only listing successfully added users in the result message.
1 parent 102f3a8 commit 0cbd038

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

Modules/CIPPCore/Public/Add-CIPPGroupMember.ps1

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -80,16 +80,29 @@ function Add-CIPPGroupMember {
8080
}
8181
}
8282
} else {
83-
$MemberIDs = foreach ($User in $Users) {
84-
$ODataBindString -f $User.body.id
83+
# Build one bulk request list; New-GraphBulkRequest handles internal chunking
84+
$AddRequests = foreach ($User in $Users) {
85+
@{
86+
id = $User.body.id
87+
method = 'POST'
88+
url = "/groups/$($GroupId)/members/`$ref"
89+
body = @{ '@odata.id' = ($ODataBindString -f $User.body.id) }
90+
headers = @{ 'Content-Type' = 'application/json' }
91+
}
8592
}
86-
$AddMembers = @{
87-
'[email protected]' = @($MemberIDs)
93+
$AddResults = New-GraphBulkRequest -tenantid $TenantFilter -Requests @($AddRequests)
94+
$SuccessfulUsers = [system.collections.generic.list[string]]::new()
95+
foreach ($Result in $AddResults) {
96+
if ($Result.status -lt 200 -or $Result.status -gt 299) {
97+
$FailedUsername = $Users | Where-Object { $_.body.id -eq $Result.id } | Select-Object -ExpandProperty body | Select-Object -ExpandProperty userPrincipalName
98+
Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Failed to add member $($FailedUsername): $($Result.body.error.message)" -Sev 'Error'
99+
} else {
100+
$UserPrincipalName = $Users | Where-Object { $_.body.id -eq $Result.id } | Select-Object -ExpandProperty body | Select-Object -ExpandProperty userPrincipalName
101+
$SuccessfulUsers.Add($UserPrincipalName)
102+
}
88103
}
89-
$AddMemberBody = ConvertTo-Json -InputObject $AddMembers
90-
$null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($GroupId)" -tenantid $TenantFilter -type patch -body $AddMemberBody -Verbose
91104
}
92-
$UserList = ($Users.body.userPrincipalName -join ', ')
105+
$UserList = ($SuccessfulUsers -join ', ')
93106
$Results = "Successfully added user $UserList to $($GroupId)."
94107
Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message $Results -Sev 'Info'
95108
return $Results

0 commit comments

Comments
 (0)