Creating a new user in Office 365 using GraphAPI - Part 4

Creating a new user in Office 365 using Graph API


Links to my old post on this series are given below.

In this post, we will learn to issue a POST request to Graph using PowerShell REST method.

Requirements: 

Service account should have following permissions
  • Permission: User.ReadWrite.All, Directory.ReadWrite.All
  • Role: At least "User management administrator"
When using the POST method, we need to supply the JSON in the request body, we will be using the "https://graph.microsoft.com/v1.0/users" URL to post the REST request.

Example of sample Post method:

Header: contains the authorization token and contact type information

"Method to get the '$accesstoken' Access token has been discussed in the previous post mentioned above"

$Header = @{
            'Content-Type'  = 'application/json'
            'Authorization' = $AccessToken.CreateAuthorizationHeader()
           }

Sample JSON: Following are the required attribute need to be pass in the JSON


$JSON=@"
{
  "accountEnabled": true,
  "displayName": $displayName,
  "mailNickname": $mailNickname ,
  "userPrincipalName":$UPN,
  "passwordProfile" : {
                        "forceChangePasswordNextSignIn": true,
                        "password":$password
                      }
  }
"@

Request Sample: Supply the $header, $JSON, Uri and Method

$URI="https://graph.microsoft.com/v1.0/users"
$Results = Invoke-RestMethod -Headers $Header -Uri $Uri -Method POST -Body $JSON

You can download the full script from my Github page here

This completes my post on how to use a post method with graph API using PowerShell, feel free to leave your feedback in the comment section. 

Comments