Automate Intune: User creation

In this post you will create the following automation:

When new email with user specification is reaching the automation Office 365 mailbox, a user is created based on the data in email body

We create the following:

  1. Automation account and a PowerShell runbook

  2. Function to clean the email body of any http special characters

  3. LogicApp to put everything together

1.Create Automation Account and Runbook

1.1 Create Automation Account

  • Sign in to the Azure portal using your account credentials
  • Click Create a resource
  • Search for Automation
  • Select automation account and click Create in the next blade

  • Add an account name <IntuneAutoAccount>
  • Assign a resource group or create a new one <IntuneAutomation-RG>
  • Assign a location. Note that not all locations are available for this kind of resource
  • Leave Create Azure Run As account checked to Yes
  • Click Create

  • Wait for deployment to complete
  • Open the resource group that has the automation account
  • Open the automation account
  • Click Credentials
  • Click Add a credential

  • For this scenario purpose use an existing account that has permissions
  • Fill in a name and credentials of a user that has access to create users. Click create

  • Now we need to add the MSOnline Module
  • Click Modules->Browse gallery

  • Search and import the MSOnline module

1.2 Create Automation Runbook

  • In the automation account that you just created click runbooks ->add runbook
  • In the new blade click Create a new Runbook
  • Fill in the name a description and select PowerShell type
  • Click Create
  • Once created the portal will open the runbook in edit mode
  • Add the following PowerShell script
This Runbook us used to create Msol users based on string contraining firstname, lastname, location and group
Author: Gabriel Marculescu
Aternate email address contains the manager email address for future references
#$ProcessedEmail=”firstname Chuck lastname Norris location US group Autopilot manageremail”
$ProcessedEmail -match “firstname\s+(\w+)\s+lastname\s+(\w+)\s+location\s+(\w+)\s+group\s+(\w+)\s+manageremail\s+(\w+.\w+@\w+.\w+)”
$DispName = “$Firstname $LastName”
$AADUser = “$Firstname.$”
$MailNick = “$Firstname.$LastName”
#Email parameteres
$smtpserver = “”
$SmtpPort = ‘587’
#connect to Msol
$cred = Get-AutomationPSCredential -Name ‘IntuneAutomationCredentials’
Connect-MsolService -Credential $cred
#Create User
try {
$createuser = New-MsolUser -UserPrincipalName $AADUser -FirstName $FirstName -LastName $LastName -UsageLocation $UsageLocation -DisplayName “$FirstName $LastName” -LicenseAssignment $lic AlternateEmailAddresses $mgremail
catch {
write-error “Error creating user $AADUser”
Try {
Set-MsolUserLicense -UserPrincipalName $AADUser -AddLicenses $lic
catch {
write-error “Error Adding license to user $AADUser”
try {
Add-MsolGroupMember -GroupObjectId (Get-MsolGroup | Where-Object DisplayName -eq $group).ObjectId -GroupMemberType User -GroupMemberObjectId (Get-MsolUser | Where-Object UserprincipalName -EQ $AADUser).ObjectId
write-error “Error adding user $AADuser to group “
$mailparam = @{
To = $mgremail
From = $FromAddress
Subject = “User successfuly created”
Body =@”
User $AADUser has been created successfuly and added to group $group.
Password is $($createuser.password)
SmtpServer = $smtpserver
Port = $smtpport
Credential = $cred
write-output $createuser.password
write-output $mailparam
send-MailMessage @mailparam -UseSsl
  • Make sure you put yourdomain on line $AADUser = “$Firstname.$LastName@yourdomain
  • Put your pointer below Connect to Msol
  • In the left pane of your Edit Runbook, expand ASSETS, expand Credential.
  • Right-Click the three dots at the right of the credential you created before
  • Add code until you have something like this

#connect to Msol

$cred = Get-AutomationPSCredential -Name ‘IntuneAutomationCredentials’

Connect-MsolService -Credential $cred

#Create User

Now we have the script ready it is time to test it

1.3 Test Runbook

  • Click Test Pane
  • Enter some test data in the filed PROCESSEDEMAIL = firstname Lara lastname Croft location us group autopilot
  • Click Start
  • Wait for the script to finish
  • You should get something like this

  • Go to Intune Users to check if you have the user created

  • Delete the newly created user

2. Function

Create Function

  • Click Create a resource and search for Function app then Enter

  • Click create in new Function App blade
  • In the Function App blade enter the application name, select subscription
  • For resource group use the resource group we created for the Automation Account
  • Select location preferably the same you have for your automation account
  • Runtime Stack stays .NET
  • Create a new storage and select an application insights location – note that not all locations are available. Note Application Insights is required for app debugging is needed

  • Click create
  • Wait for deployment to finish and click go to resource
  • in the function app blade click function, then new function

  • select HTTP trigger
  • in the new blade enter name and leave Authorization level set to Function
  • click Create

  • replace the code with the following

#r “Newtonsoft.Json”

using System.Net;

using Microsoft.AspNetCore.Mvc;

using Microsoft.Extensions.Primitives;

using Newtonsoft.Json;

using System.Text.RegularExpressions;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)


log.LogInformation(“C# HTTP trigger function processed a request.”);

string name = req.Query[“name”];

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

string updatedBody = Regex.Replace(requestBody, “<.*?>”, string.Empty);

updatedBody = updatedBody.Replace(“\\r\\n”, ” “);

updatedBody = updatedBody.Replace(@”&nbsp;”, ” “);

// dynamic data = JsonConvert.DeserializeObject(requestBody);

dynamic data = JsonConvert.DeserializeObject(updatedBody);

name = name ?? data?.name;

return name != null

// ? (ActionResult)new OkObjectResult($”Hello, {name}”)

? (ActionResult)new OkObjectResult(name)

: new BadRequestObjectResult(“Please pass a name on the query string or in the request body”);


  • The application we entered replaces all special html characters from the email body and sends clean text as output

Test Function

  • In the cleanemailbody blade press run
  • In Request Body enter test string
  • Check Output

3. Logic App

  • Click Create Resource and look for logic app

  • Select Logic App and click Create in the next blade
  • In the Create logic app blade add name, select subscription
  • Select the existing resource group created for the automation account

  • Select location and click Create
  • Wait for deployment to complete and go to resource

  • When the Apps Designer blade select Blank Logic App
  • In the logic app designer blade click search connectors and triggers and look for office. Select Office 365

  • In the next blade select When a new email arrives

  • Login with the account that will receive the trigger email. This usually is a service email account
  • Once the login was successful, click show advanced options
  • Configure the email trigger as required by your scenario. In this blog we use sender email and subject to filter out our email triggers
  • In Subject filter enter new user

  • In Choose an action window look for function
  • Select the cleanemailbody function we previously created

  • In the cleanemailbody window enter the following
  • Request body {‘name’: then add Body from dynamic content and close the json expression with }
  • Set method to POST
  • Click New Step

  • In the new window look for automation

  • Select Create job (preview)
  • In Azure Automation window click Sign in and sign in with your user
  • In the new window select your subscription, Resource Group, Automation account and runbook name. runbook parameter should be the body that comes out from the function

  • Click Save to save the function

4. Test the automation

  • In the logic app designer click run
  • Open the office portal at
  • Open outlook
  • Sent the following email to your automation email account
  • Subject: new user
  • Body : firstname Chuck lastname Norris location US group Autopilot
  • Send the email

  • Go to the logic app Overview page
  • In runs history you should see the job, click on it. In the next page you should have something similar

  • Look for the used in ADD