Monday, April 26, 2021

Calculate Azure AD groups count via MS Graph in PowerShell

If you need to fetch Azure AD groups or e.g. calculate total count of AAD groups via MS Graph API in PowerShell you may use Powershell-MicrosoftGraph project on github. At first you need to clone repository locally and copy it's folder to local PowerShell Modules folder:

git clone 'https://github.com/Freakling/Powershell-MicrosoftGraph'
Copy-item -Path "Powershell-MicrosoftGraph\MicrosoftGraph\" -Destination ($env:PSModulePath.Split(';')[-1]) -recurse -force

We will make Graph requests using app permissions. It means that you need to have registered AAD app with permissions Groups.Read.All for fetching the groups:


Copy clientId and clientSecret of this AAD app and tenantId of your tenant (you may copy it from Azure portal > Azure AD overview tab). Having all this data in place run the following script:

$appID = "..."
$appSecret = "..."
$tenantID = "..."
$credential = New-Object System.Management.Automation.PSCredential($appID,(ConvertTo-SecureString $appSecret -AsPlainText -Force))
$token = Get-MSGraphAuthToken -credential $credential -tenantID $tenantID
(Invoke-MSGraphQuery -URI 'https://graph.microsoft.com/v1.0/groups' -token $token -recursive -tokenrefresh -credential $credential -tenantID $tenantID | select -ExpandProperty Value | measure).Count

It will output total count of groups in your AAD.

No comments:

Post a Comment