Add devices to an Azure AD Group using the Microsoft Graph API

Have you ever needed to add a device to an Azure AD Group as part of your MEMCM or Autopilot deployment for specific app, profiles or scripts?

Well it became the case that my organisation needed to do so for a couple of reason, one of those was to disable Windows Hello and the other for devices migrating from a previous Configuration Manager (Not MEMCM).

Because I was using Hybrid AD Join Autopilot Deployments it became the case that I had to use the devices' computer name and get the device information that way.

For you that don’t use the Hybrid AD Join Autopilot method, This creates two Azure AD computers, The first been purely Azure AD Joined and the second is an Intune (MDM Enrolled) object. Microsoft do link these together for the Bitlocker Keys etc. and from my understanding they are looking at making them just one object but at the time this article was written they remain two separate objects…. I look forward to the day when two become one ;).

Oh… did I also mention that you do not need to install any other modules for PowerShell to be able to run these script? No? Well that’s the nature of the game for me is to have as little reliance on Modules etc so the scripts can be run practically anywhere :D.

The Script

You will notice that most of this (the authentication part and most of the param block at least) are the same as my other script… But if its not broke why fix it? (Those famous last words!!!).

As mentioned above you will notice that this uses the computer name to identify the device and then use the information from that device object to add it to the Azure AD Group. When the device is identified from the name it gets the device Azure ID and then proceeds to create the JSON body for the request and then submits this to the API.

    [Parameter(DontShow = $true)]
    $MsGraphVersion = "beta",
    [Parameter(DontShow = $true)]
    $MsGraphHost = "",
    #The AzureAD ClientID (Application ID) of your registered AzureAD App
    $ClientID = "<YourClientID>",
    #The Client Secret for your AzureAD App
    $ClientSecret = "<YourClientSecret>",
    #Your Azure Tenent ID
    $TenantId = "<YourTenentID>",
    #The Azure AD Group Object ID
    $GroupID = "<YourGroupID>",
    #The name of the device

IF (!($InputDevice)) {
    $InputDevice = $env:COMPUTERNAME

#Create the body of the Authentication of the request for the OAuth Token
$Body = @{client_id=$ClientID;client_secret=$ClientSecret;grant_type="client_credentials";scope="https://$MSGraphHost/.default";}
#Get the OAuth Token 
$OAuthReq = Invoke-RestMethod -Method Post -Uri "$TenantId/oauth2/v2.0/token" -Body $Body
#Set your access token as a variable
$global:AccessToken = $OAuthReq.access_token

$GroupMembers = Invoke-RestMethod -Method Get -uri "https://$MSGraphHost/$MsGraphVersion/groups/$GroupID/members" -Headers @{Authorization = "Bearer $AccessToken"} | Select-Object -ExpandProperty Value

$Devices = Invoke-RestMethod -Method Get -uri "https://$MSGraphHost/$MSGraphVersion/devices?`$filter=startswith(displayName,'$InputDevice')" -Headers @{Authorization = "Bearer $AccessToken"} | Select-Object -ExpandProperty Value | %{ 

    if ($GroupMembers.ID -contains $ {
        Write-Host -ForegroundColor Yellow "$($_.DisplayName) ($($_.ID)) is in the Group"   
    } else {
        Write-Host -ForegroundColor Green "Adding $($_.DisplayName) ($($_.ID)) To The Group"
        $BodyContent = @{
        } | ConvertTo-Json
        Invoke-RestMethod -Method POST -uri "https://$MSGraphHost/$MsGraphVersion/groups/$GroupID/members/`$ref" -Headers @{Authorization = "Bearer $AccessToken"; 'Content-Type' = 'application/json'} -Body $BodyContent

The Pre-Reqs

To make the script work you will need an Azure App Registration with the following permissions for the Microsoft Graph API;

  • GroupMember.ReadWrite.All
  • Group.ReadWrite.All
  • Directory.ReadWrite.All

You will also need the Group ID and Tenant ID, to find this following these steps

  • Login to the Azure AD console (You can get your Tenant ID from the Overview tab under Tenant Information)
  • Select Groups
  • Search for the group you want to utilise and open it
  • From the Group overview page copy the Object ID as this is the Group ID we need.
If your not sure how to create an Azure AD App Registration head over to one of my other posts by clicking HERE, Don't forget to store your Client ID and Secret securely and also have it to hand for the rest of the post :D.

Executing the Script

There are numerous ways you can execute this script, you could use it as a script in Script in MEMCM or Intune, In a Task Sequence, as an Application or Package (You will need to add some for of check file for the detection rule) or you could execute this directly from the command line.

I will demonstrate the Script in MEMCM and Intune for you.

Script in MEMCM

This is the best option if you want to do it manually on a case by case basis (i.e. Right click on the computer object and select run script).

Jump into the Script section in MEMCM (Software Library > Scripts) and click Create Script from the ribbon.

Give the script a Name, select the language as PowerShell and then copy and paste the script above (Tip: In the top right corner of the script block you can click Copy Script Text).

Click Next, This is where you need the details we noted earlier. MEMCM is great at pulling through the Param block parameters, all we need to do is amend the ClientID, ClientSecret and TenantId arguments as below.

As we are using the environment variable for the InputDevice we will need to Hide this from selection as the script will use the Environment Variable if the parameter is not used.

Double Click on InputDevice, Change the Hidden drop down to True click OK.

When finished click Next review the settings and then click next and then close.

Don’t forget to Approve your Script

Now lets choose a client computer from Assets and Compliance > Devices. Right click on the object and select Run Script, Select the script object you created and review the details and then let the script run.

This does not take long to run and the output of the script if the device is successfully added to the group is as below;

As mentioned before as these devices are Hybrid Joined they have two entries in Azure AD which is why the output shows its adding the device twice with two different GUIDS.

Script in Intune

This time the script needs to be saved as a .ps1 file to be uploaded and used by Intune, unfortunately using the Scripts section in Intune you cannot specify parameters so you will need to put your Client ID, Secret, TenantID and Group ID into the script before uploading. You could use a Win32 App as an alternative method if you wish to use them via the command line. Once you’ve saved the script launch the Endpoint Manager Console from your favourite web browser.

Select Devices from the left hand pane, under the Policy section click Scripts.

Click Add > Windows 10, Name your script appropriately and enter a short description (Even a link to this blog :P), Once you’ve done hit next and then select your script to use.

Leave all of the sliders as No;

Click Next, Add your Scope Tags (if any) and your assignments. Review the configuration and click Add.

This doesn’t run instantaneously, please refer to the Microsoft Documentation this also has some other notable consideration listed.

To Conclude

These are just two of the ways you can run the script, you could also potentially run this in the back end of a web application for people who want to request to disable things like Windows Hello (As I mentioned at the start). I could spent days, weeks even months on writing articles for some of the uses. A user one will no doubt follow in due course so watch this space :D.

I did fully test these methods at the time of writing the blog but if you come across any information you think may be wrong then please leave a comment or e-mail me on [email protected].

I hope this is useful for your needs.

comments powered by Disqus