Managing Azure AD using Graph API and ADAL inside PowerShell

# replace ??????? before running the script

# visit ""
# Load Active Directory Authentication Library (ADAL) Assemblies
$adal = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.dll”
$adalforms = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll”
$cred = Get-Credential
$mycred = new-object Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential($cred.UserName,$cred.Password)
# Defining Azure AD tenant name, this is the name of your Azure Active Directory
$adTenant = ””
$login = Add-AzureRmAccount -Credential $cred
Select-AzureRmSubscription -SubscriptionID ‘????????????????‘
# Set well-known client ID for Azure PowerShell
$clientId = "1950a258-227b-4e31-a9cf-717495945fc2”
# Set redirect URI for Azure PowerShell
$redirectUri = "urn:ietf:wg:oauth:2.0:oob”
# Set Resource URI to Azure Service Management API
$resourceAppIdURI = "”
# Set Authority to Azure AD Tenant
$authority = "$adTenant"
# Create AuthenticationContext tied to Azure AD Tenant
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext” -ArgumentList $authority
# Acquire token
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $mycred)
# Building Rest Api header with authorization token
$authHeader = @{
#get your Azure AD tenant details
$resource = "tenantDetails”
$uri = "$adTenant/$($resource)?api-version=1.6"
$tenantInfo = (Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get –Verbose).value
#get users having their displayname starting with letter a
$resource = "users”
$uri = "$adtenant/$($resource)?api-version=1.6`&`$filter=startswith(displayName,'b')”
$users = (Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get –Verbose).value
#get groups and get group members of each group
$resource = "groups”
$uri = "$adtenant/$($resource)?api-version=1.6"
$groups = (Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get –Verbose).value
foreach($group in $groups)
$objectid = $group.objectid
$uri = "$adtenant/groups/$objectid/members?api-version=1.6"
$members = (Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get –Verbose).value
#create a new user
$newuser = @{
"displayName”="John Doe”;
$newuserJsonDef = $newuser | ConvertTo-Json
$resource = "users”
$uri = "$adtenant/$($resource)?api-version=1.6"
$result = Invoke-RestMethod -Uri $uri -Headers $authHeader -Method Post -Body $newuserJsonDef -ContentType "application/json”
#verify that user is created successfully
$uri = "$adtenant/users`?api-version=1.6`&`$filter=mailNickname eq 'John.Doe'”
(Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get –Verbose).value

Comments (0)

Skip to main content