I need to add a long list of users to a new created azure devops group.
When I run the following script I get the error :
PS /Users/myuser # Get the descriptor of the group PS /Users/myuser> $groupsUrl = "$apiUrl/graph/groups?api-version=6.0-preview.1" PS /Users/myuser> $groups = Invoke-RestMethod -Uri $groupsUrl -Method Get -Headers $headers Invoke-RestMethod: Page Not Found
my code:
# Your Azure DevOps organization and PAT
$organization = " "
$personalAccessToken = " "
$apiUrl = "https://vsaex.dev.azure.com/$organization/_apis"
# Group name to add users to
$groupName = " "
# Path to the CSV file
$csvFilePath = Resolve-Path "/Users/ /test.csv"
# Base64-encode the Personal Access Token and add it to the headers
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($personalAccessToken)"))
$headers = @{
Authorization = "Basic $base64AuthInfo"
}
# Function to add a user to a group
function Add-UserToAzureDevOpsGroup {
param(
[string]$organization,
[string]$groupId,
[string]$memberId,
[string]$pat
)
$uri = "https://vsaex.dev.azure.com/$organization/_apis/GroupEntitlements/$groupId/members/$memberId?api-version=7.0"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$pat"))
Invoke-RestMethod -Uri $uri -Method Put -Headers @{Authorization=("Basic $base64AuthInfo")} -ContentType "application/json"
}
# Get the descriptor of the group
$groupsUrl = "$apiUrl/graph/groups?api-version=6.0-preview.1"
$groups = Invoke-RestMethod -Uri $groupsUrl -Method Get -Headers $headers
$group = $groups.value | Where-Object { $_.principalName -eq $groupName }
$groupDescriptor = $group.descriptor
# Import the user list from the CSV
$users = Import-Csv -Path $csvFilePath
# Loop through each user and add them to the group
foreach ($user in $users) {
$userEmail = $user.UserName
$userDescriptorUrl = "$apiUrl/graph/users?api-version=6.0-preview.1&subjectTypes=user&mailAddress=$userEmail"
$userDescriptorObject = Invoke-RestMethod -Uri $userDescriptorUrl -Method Get -Headers $headers
$userDescriptor = $userDescriptorObject.value.descriptor
if ($userDescriptor) {
Add-UserToGroup -userDescriptor $userDescriptor -groupDescriptor $groupDescriptor
Write-Host "Added user ($userEmail) to group ($groupName)"
} else {
Write-Host "Could not find user descriptor for email ($userEmail)"
}
}
the above code explains
The error is caused by the incorrect
$apiUrl, for user list rest api, the url should be started withhttps://vssps.dev.azure.com, nothttps://vsaex.dev.azure.com. In addition, there are other syntax errors in your script.You are using Members - Add rest api to add the user to the group, it requires
groupidandmemberid, it's NOTgroupDescriptoranduserDescriptor.You need to change the rest api used.
I edited your script, and it's working on my side.
My test.csv:
Execution result:
The DevOps User added in the group: