简体   繁体   中英

Get all users under all projects from Azure DevOps

I am trying to get all users under couple of project. The case is that under users there are many and I need to to use continuationToken . The result is messy because my logic is bad. I cannot figure out how to use the second foreach..

$outputItems = @()

foreach ($project in $projects) {
    $uriProjectDescriptor = "https://vssps.dev.azure.com/$OrganizationName/_apis/graph/descriptors/$($project.id)?api-version=5.0-preview.1"
    $projectDescriptor = Invoke-RestMethod -Uri $uriProjectDescriptor -Method Get -Headers $AzureDevOpsAuthenicationHeader
    $descriptors = $projectDescriptor.value

    foreach ($descriptor in $descriptors) {
    do
    {
        $uriUsers="https://vssps.dev.azure.com/$OrganizationName/_apis/graph/users?continuationToken=$continuationToken&scopeDescriptor=$($descriptor)&api-version=6.0-preview.1"
        $responseUsers=Invoke-WebRequest -Uri $uriUser -Method Get -ContentType "application/json" -Headers $AzureDevOpsAuthenicationHeader -UseBasicParsing -MaximumRedirection 0
        $continuationToken = $responseUsers.Headers.'x-ms-continuationtoken'
        $userSet = $responseUsers.content | ConvertFrom-Json
        $users += $userSet.value.Count
        $arealList = New-Object -TypeName PSObject -Property @{
            CountUsers = $users.Count
         } | Select-Object "CountUsers"
         $outputItems += $arealList
         $arealList = $null
    }
    while (($continuationToken))
    $ProgressPreference = 'Continue'
    }  
} $outputItems

You could try the following Powershell Script:

$token = "PAT"

$url="https://dev.azure.com/{Organizationname}/_apis/projects?api-version=6.0"


$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))

$responses = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Get -ContentType application/json


ForEach ($response in $responses.value.id)
{
   

   $url1="https://vssps.dev.azure.com/{Organizationname}/_apis/graph/descriptors/$($response)?api-version=6.0-preview.1"

   $Descriptor = Invoke-RestMethod -Uri $url1 -Headers @{Authorization = "Basic $token"} -Method Get -ContentType application/json

   ForEach ($Descriptor1 in $Descriptor.value)
   {

     do
    {
      $url2="https://vssps.dev.azure.com/{Organizationname}/_apis/graph/users?scopeDescriptor=$($Descriptor1)&api-version=6.0-preview.1"

      $UserLists = Invoke-RestMethod -Uri $url2 -Headers @{Authorization = "Basic $token"} -Method Get -ContentType application/json
      $continuationToken = $UserLists.Headers.'x-ms-continuationtoken'
   
    }
    while ($continuationToken -ne $null)
  
    Write-Host "result = $($UserLists | ConvertTo-Json -Depth 100)"
   }

} 

Explaination:

The first Rest API is used to get the Project name.

Then the second Rest API is used to get the descriptors.

The third Rest api is used to get the userlist.

I use foreach nesting to realize the loop of response to Rest API.

Update:

Test with the continuationToken and the maximum value of objects returned by a project is 500.

I found another Rest Api User Entitlements - List to get the users.

https://vsaex.dev.azure.com/Organization Name/_apis/userentitlements?top=10000&select=project&api-version=4.1-preview.1

This Rest APi could directly return the users under the organization(Project Scope). The max value is 10000.

This is untested as I'm not on a work machine, so apologies if I am off the mark here or have messed something up, but I think a function here with your repeated action would make what you're trying to do clearer.

# Output array
$OutputItems = @()

# Repeatable function for obtaining the users for the descriptor - Define this before the main part of your code.
function Get-ProjectUsers {
    Param (
        [Parameter(Mandatory=$true)][string]$Descriptor,
        [Parameter(Mandatory=$false)][string]$ContinuationToken
    )
    
    # If the continuation token has been passed, we need to add it to the API URI.
    if ($PSBoundParameters.ContainsKey("ContinuationToken")) {
        $UriUsers = "https://vssps.dev.azure.com/$script:OrganizationName/_apis/graph/users?continuationToken=$ContinuationToken&scopeDescriptor=$Descriptor&api-version=6.0-preview.1"
    }
    else {
        $UriUsers = "https://vssps.dev.azure.com/$script:OrganizationName/_apis/graph/users?scopeDescriptor=$Descriptor&api-version=6.0-preview.1"
    }

    # Invoke the web request and add the custom object to the output array.
    $Response = Invoke-WebRequest -Uri $UriUsers -Method Get -ContentType "application/json" -Headers $script:AzureDevOpsAuthenicationHeader -UseBasicParsing -MaximumRedirection 0
    $UserSet = $Response.Content | ConvertFrom-Json
    $script:OutputItems += [PSCustomObject]@{
        CountUsers = $UserSet.Value.Count
    }

    # If the continuation token exists return it so that we can carry on calling the API until there are no further records.
    if (![string]::IsNullOrEmpty($Response.Headers.'x-ms-continuationtoken')) {
        return $Response.Headers.'x-ms-continuationtoken'
    }
    else {
        return $null
    }
}

# Main code.
foreach ($Project in $Projects) {
    $UriProjectDescriptor = "https://vssps.dev.azure.com/$OrganizationName/_apis/graph/descriptors/$($Project.id)?api-version=5.0-preview.1"
    $ProjectDescriptor = Invoke-RestMethod -Uri $UriProjectDescriptor -Method Get -Headers $AzureDevOpsAuthenicationHeader
    $Descriptors = $ProjectDescriptor.value

    # We do not need to run the do loop until there is a continuation token.
    foreach ($Descriptor in $Descriptors) {
        $Repeat = Get-ProjectUsers -Descriptor $Descriptor

        # If Repeat is not null, we can use the do loop to call our function until it does return null.
        if ($null -ne $Repeat) {
            do {
                $Repeat = Get-ProjectUsers -Descriptor $Descriptor -ContinuationToken $Repeat
            } until ($null -eq $Repeat)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM