Create new user via Microsoft Graph using PowerShell

cls

# 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”
[System.Reflection.Assembly]::LoadFrom($adal)
[System.Reflection.Assembly]::LoadFrom($adalforms)
$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 = ”??????.onmicrosoft.com”
$login = Add-AzureRmAccount -Credential $cred
Get-AzureRmSubscription
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 = "https://graph.microsoft.com”
# Set Authority to Azure AD Tenant
$authority = "https://login.windows.net/$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 = @{
‘Content-Type’=‘application\json’
‘Authorization’=$authResult.CreateAuthorizationHeader()
}

#get users having their displayname starting with letter a
$resource = "users”
$uri = "https://graph.microsoft.com/v1.0/users”
$users = (Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get –Verbose).value
$users

#create a new user
$newuser = @{
"accountEnabled”=$true;
"userPrincipalName”="name.surname2@?????.onmicrosoft.com”;
"displayName”="Name Surname”;
"passwordProfile”=@{
"password”="Mypassword1!”;`
"forceChangePasswordNextSignIn”=$true
};
"mailNickname”="name.surname2”
}
$newuserJsonDef = $newuser | ConvertTo-Json
$resource = "users”
$uri = "https://graph.microsoft.com/v1.0/users"
$result = Invoke-RestMethod -Uri $uri -Headers $authHeader -Method Post -Body $newuserJsonDef -ContentType "application/json”

#get users having their displayname starting with letter a
$resource = "users”
$uri = "https://graph.microsoft.com/v1.0/users”
$users = (Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get –Verbose).value
$users