Beyond the supported – Cross forest style Exchange Online Migration

Migration and consolidation projects always put our skills to the test and in some cases forces us to do things that are not fully supported. But sometimes, the end justifies the means.

Some time ago, I did an Exchange Online onboarding project in a quite complex scenario, at least in terms of the identities. 10+ Active Directories and almost as many Exchange environments. On top of that, due to several reasons, it was not possible to create trusts between the different directories. Not the easiest starting point…
Looking at all different options we agreed upon to synchronize one of the directories to Azure AD. This meant that all users not in that directory were to get new accounts, effectively taking the first step towards a common environment.

– Identites – check!

The next step were to determine the migration strategy for the Exchange environments that was ranging from Exchange 2007 -> 2013. Given the quite complex scenario without trusts between the environments, our minds were set to use a third-party tool to do all the migrations. I always like challenging the obvious path, so I wanted to see if it was possible to do native mailbox moves even though there was no possibility to use the regular Hybrid Configuration Wizard.

Guess what – following cross-forest migration principals and copying the relevant attributes between the environments worked great! Cutting $100k in third-party software licensing costs from the project budget is never a bad thing either 🙂

A little simplified, we ended up with a scenario / environment looking like below:


Remember that this is a quite complex scenario where you have to do most preparations “manually”, so don’t try this unless you really need this kind of scenario. Also note that the same approach works in a staged migration scenario from Exchange 2003/2007.


  • You have a way to match users between the different environments when moving the attributes.
  • The target directory/forest has been prepared with the Exchange server schema.
  • SMTP/Port 25 is open from the source Exchange environments for outgoing coexistence mailflow.
  • You are in control of your incoming mailflow as well as AutoDiscover, depending on how your environment/domains look like. 🙂
  • This method will be used to migrate mailboxes, not for long-term coexistence. If you have separate SMTP domains per environment, free/busy sharing can be configured if needed.

Preparation steps: 
Source Exchange Environment:

1. Add the tenant routing domain ( as an accepted domain. Also create a send connector to solve outgoing email in the transition
2. Add the routing email address ( to all users in scope for migration.
3. Export the attributes needed to perform the migration from the source Exchange environment. The following attributes are needed for a successful migration. I have used Export-Clixml instead of a CSV-file for simpler handling importing back the Guid Attributes.

  • mail
  • mailNickname
  • proxyAddresses
  • msExchMailboxGuid       
  • msExchArchiveGuid  
  • legacyExchangeDN          
  • msExchRecipientDisplayType
  • msExchRecipientTypeDetails

4. Export mailbox permissions/calendar permissions for users/shared mailboxes if needed.
5. Enable MRSProxy in the Exchange Environment. Also create a service account with at least Recipient Management permissions to use setting up the migration endpoint in Exchange Online.

Target Active Directory / Exchange Online environment:
1. Set up an “Exchange Remote” migration endpoint towards the MRSProxy earlier created.
2. Import the attributes earlier exported in the user directory.
3. After a successful directory synchronization, verify that the users in scope shows up as Mail Users in Exchange Online. If you did the Exchange schema update after you installed AADConnect, don’t forget to refresh the schema there as well, otherwise you won’t synchronize the imported attributes.
4. Perform a test move and verify that everything works as expected. Just as in the case of a “normal” move, the mailbox will be converted to a remote mailbox after the move has been completed.

Migration/post migration steps 
1. Plan and execute your migration batches. Remember that this is not a regular hybrid environment with free/busy etc., so plan your batches accordingly.
2. Import eventual mailbox/calendar permissions after each batch.
3. Switch MX/Autodiscover to Office 365
4. Decommission the source Exchange environment.

One approach does not fit all and sometimes you have to think a little bit out of the box. I hope this post was interesting and that it might give you some creative ideas running in to similar scenarios. For any questions or feedback, feel free to comment here or ping me on Twitter, @daltondhcp.


Create simple PowerBI reports for Intune through the Microsoft Graph

Reporting, playing with data and creating all kinds of charts is always fun. PowerBI is probably the simplest playground doing it.

While doing an O365 / EMS project, management wanted a simple dashboard to keep track of different KPI’s in the project. Example on the data they wanted was number of onboarded users to Exchange Online and enrolled devices in Intune. The Office 365 adoption content pack is in preview and provides lots of insights to how the services are used (in some cases, maybe too much)… In this specific case, we also had an Intune Cloud Only environment, so our reporting as well as delegation possibilites were very limited.


Luckily enough, some Intune data (and its growing and growing) are nowdays exposed through the Microsoft Graph for us to consume with PowerBI directly with REST and OData.

In my example, I will simply get all registered devices to create my report. To find what possibilites there are, look in to the Microsoft Graph Documentation. If you want to use query parameters, you’ll find the supported ones here.

1. First connect and load the OData feed from Microsoft Graph. In my case I am using the endpoint. Sign in with an organizational account or app that have appropriate permissions.

2017-01-03_14-50-39 2017-01-03_14-50-55

2. After the data has been loaded successfully in to PowerBI it’s time to create som nice charts!







Result – My “finished” basic report


This was a simple example how to get started with PowerBI and the Microsoft Graph – hopefully you’ve now got some inspiration on what possibilites there are with just five minutes effort. Imagine what you could do if you really put in some time. 🙂

Happy reporting!


ADFS Customization – add custom help form to the login page

In the spirit of sharing more “not-so-evergreen” ADFS customizations, I wanted to share another customization request I got a while ago.
The case was very simple, they customer wanted to fit more end-user information in the login flow than the ADFS login page could fit without sending the user to another page.
Onload.js to the rescue again! This time we are using it to simply create an additional form where we present additional information when clicking on the help button.

My example looks like this:

Note that everything is in the JavaScript code, including the help page text. If preferred, that part could be loaded from another location.

Customize ADFS with help page (yes, I should move my content to GitHub)

// Author: Johan Dahlbom
// Blog:
// Twitter: @daltondhcp
// Get DOM elements and save as objects
var loginMessage = document.getElementById('loginMessage'),
    loginArea = document.getElementById('loginArea'),
    loginForm = document.getElementById('loginForm'),
	userNameInput = document.getElementById('userNameInput'),
	errorText = document.getElementById("errorText"),
	introArea = document.getElementById("introduction"),
	authArea = document.getElementById("authArea");

var showingHelper = false,
    showingLoginform = false;


function createHelpersForLoginForm() {
  //Create the hyperlink to the help form
  passwordResetLink = document.createElement('a');
  var linkText = "Need help?";
  passwordResetLink.title = linkText;
  passwordResetLink.href = "#";
  passwordResetLink.onclick = toggleHelpContent;


function createHelpContent() {
  if (!authArea) {
  helpContent = document.createElement("div"); = 'none';

  helpContent.innerHTML = '\
    <h2><strong>What is my username?</strong></h2>\
    <p>Your username is the same as your email address. Example:</p><br>\
    <h2><strong>What is my password?</strong></h2>\
    <p>This is a secret chosen by you. It would not be a secret if we told you. If you forgot your password, you can reset it <a href="" target="_blank">here</a><br><br>\
    <p>If you have any issues or questions, please contact our helpdesk at 555-GET-HELP or <a href=""></a><br><br><br></p>\

  // Link for close help
  var closeHelpContentLink = document.createElement('span');
  closeHelpContentLink.innerHTML = "Back to the login form";
  closeHelpContentLink.className = "submit";
  closeHelpContentLink.onclick = toggleHelpContent;

  // Duplicate it to have one before the content as well.
  // Uncomment these lines if the help  content grows.
  // var closeHelpContentLinkUpper = closeHelpContentLink.cloneNode(true);
  // closeHelpContentLinkUpper.onclick = toggleHelpContent;
  // helpContent.insertBefore(closeHelpContentLinkUpper, helpContent.firstChild);



function updateUI() {
  // Check for DOM errors
  if (!loginForm || !helpContent) {

  if (showingHelper) {
  } else {

function toggleHelpContent() {
  showingHelper = !showingHelper;


function openHelpContent() {"block";"none"

function closeHelpContent() {"none";"block"

// Create DOM elements 

As usual, you update onload.js with the Set-AdfsWebTheme cmdlet.
Hope this will be useful for some of you guys! If you have questions, ping me o twitter or email!


ADFS Customization – Branding per domain for Azure AD/Office 365

Branding your services can be very important for many reasons where recognizability and company profile are the most common ones. Making the marketing department happy is not a bad thing either.
With ADFS in Server 2016, the capability to do branding on a relying party basis was added. This was something that you in 2012 R2 needed to use JavaScript to achieve. Please note that the customizations in this post works both in 2012R2 and 2016.

While the default branding options above fit most customer needs, I recently had a customer case where two municipalities were onboarding to Office 365. Since they were sharing the same AD domain, they also shared their ADFS environment. You can probably guess where we are going now… They want continue using the same ADFS environment but have different branding depending on the login domain in Office 365 / Azure AD. I have got this request before, but have usually talked out the customers of going that path and instead agree upon common branding, but not this time. Not the most evergreen solution, but all for the customers, right? 🙂

There is a uservoice for the same request using managed domains directly in Azure AD – so clearly this is not the first time this has come up.

We will customize onload.js to apply different branding depending on the Office 365 / Azure AD domain used to login.
If browsing /idpinitiatedsignon directly or using another RP than Azure AD/Office 365, the default branding should apply. In my example, I will use the domains and I assume that basic branding/webtheme already is in place.

The branding will apply in the following scenarios:

Upload the logos and illustrations as in my example script below. For performance and looks, follow the recommendation on sizes etc. on this TechNet page. If you have many domains, using some kind of naming convention might also be a good idea ;-).

$WebThemeName = "365lab"
#The pictures to upload
$UploadData = @{
  logo = @('C:\temp\Branding\dom1.365lab.net_logo.png',
  illustration = @('C:\temp\Branding\dom1.365lab.net_illustration.jpg',
#Loop through the image HT and upload the files accordingly
foreach ($ImageType in $UploadData.Keys) {
  $UploadData[$ImageType] | ForEach-Object -Process {
    $FileName = $_.Split('\')[-1]
    Set-AdfsWebTheme -TargetName $WebThemeName `
                      -AdditionalFileResource @{
                        Uri = '/adfs/portal/{0}/{1}' -f $ImageType,$FileName
                        Path = $_.ToString() 

The JavaScript basically loops through an array and checks if the request has been referred from any of the domains in scope for customizations. In the example, the username placeholder and the login message are customized based on the “domainconfig” data as well. If you don’t know how to export/import onload.js to ADFS, looking in to this article prior doing any changes might be a good idea.

var locationUrl = window.location.href.toLowerCase(),
	referrerUrl = document.referrer.toLowerCase(),
    logoDomain = document.getElementById('header'),
    loginMessage = document.getElementById('loginMessage'),
    userNameInput = document.getElementById('userNameInput'),
    domainconfig = [
        {domain:"", companyName: "365lab Domain 1", logo:"dom1.365lab.net_logo.png", illustration:"dom1.365lab.net_illustration.jpg"},
        {domain:"", companyName: "365lab Domain 2", logo:"dom2.365lab.net_logo.png", illustration:"dom2.365lab.net_illustration.jpg"}

function checkUrlForDomain(domainName) {
  return locationUrl.indexOf(domainName) > -1 || referrerUrl.indexOf(domainName) > -1;

for (var j = 0; j < domainconfig.length; j++){
  var domainName = domainconfig[j].domain;
  if (checkUrlForDomain(domainName)) {
     var logo = domainconfig[j].logo;
     var illustration = domainconfig[j].illustration;
     var companyName = domainconfig[j].companyName;

     //for troubleshooting purposes

     //Change Logo
     logoDomain.innerHTML = "<img class='logoImage' src='/adfs/portal/logo/" + logo +"' alt='" + domainName + "'" +">"
     //Change illustration
     document.getElementsByTagName('style')[0].innerHTML = ".illustrationClass {background-image:url(/adfs/portal/illustration/" + illustration + ");}"; 
     //Change login message
     loginMessage.innerHTML = "<h2>Sign in with your " + companyName + " account </h2>" ;
     //Change username placeholder
     userNameInput.placeholder = "firstname.lastname@" + domainName ;

After updated onload.js with your code, upload the changes to your webtheme with the following PowerShell cmdlet.

$WebThemeName = "365lab"
Set-AdfsWebTheme -TargetName $WebThemeName `
                 -AdditionalFileResource @{

Voila! We now have different branding in our ADFS depending on the domain suffix entered in Office 365 / Azure AD. Note that the code won’t change branding if you change the domain suffix in the username field after hitting the ADFS farm.


Good luck with your branding and as always, let me know if you have feedback!

Happy new year!


Assign individual parts of licenses with Azure AD PowerShell V2.0

Azure AD PowerShell V2 has been in GA for almost a month now. Even though some features (like converting a domain to federated) are missing as of now, it is really time to start to rewrite all those old MSOnline module scripts as AAD PS PM Rob de Jong reminded me of this thursday.

Since licensing still is the most important task to automate in customer environments I thought it was a good idea to share some of the basics on how to licensing works in V2.0. Some day, when ‘Azure AD Group Based licensing’ is in place, we can get rid of most of these these licensing scripts.

Since most of my customers rarely roll out all services at once, I thought it was a good idea to show you how to roll out a few serviceplans at a time with Azure AD PowerShell V2.0. If you want to look in to the basics, fellow MVP Simon Wåhlin wrote a great post about this a month ago.

Find your LicenseSku’s and ServicePlans:
Luckily enough, the equivalent to Get-MsolAccountSku, Get-AzureADSubscribedSku gives us pretty much the same information as its predecessor.
As seen in the screenshot, we can still identify the licenses with their partnumber even though we need the SkuId’s when assigning the licenses later which is really helpful converting your old scripts.

Finding the individual services is as easy, you only need to look in to the ServicePlans property instead of ServiceStatus. As with the base license, you’ll need to use the ServicePlanId of the specific plan if you want to disable it.

Putting it together and assign individual ServicePlans of a license:
In my example, I will enable a non-licensed user an E3 that has Exchange Online, Skype for Business and Office 365 ProPlus enabled. In staged onboarding cases usually choose the ones to enable in my scripts instead of hard coding the disabled ones, since Microsoft tend to add new serviceplans from time to time (Teams, PowerApps, Flow etc.). You can of course do it the other way around if that fits your organization better.
Note that it is still a requirement to assign the UsageLocation on the user before assigning the license.

#The user that will get a license
$UserToLicense = Get-AzureADUser -ObjectId ""

#Define the plans that will be enabled (Exchange Online, Skype for Business and Office 365 ProPlus )
#Get the LicenseSKU and create the Disabled ServicePlans object
$LicenseSku = Get-AzureADSubscribedSku | Where-Object {$_.SkuPartNumber -eq 'ENTERPRISEPACK'} 
#Loop through all the individual plans and disable all plans except the one in $EnabledPlans
$DisabledPlans = $LicenseSku.ServicePlans | ForEach-Object -Process { 
  $_ | Where-Object -FilterScript {$_.ServicePlanName -notin $EnabledPlans }

#Create the AssignedLicense object with the License and DisabledPlans earlier created
$License = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicense
$License.SkuId = $LicenseSku.SkuId
$License.DisabledPlans = $DisabledPlans.ServicePlanId

#Create the AssignedLicenses Object 
$AssignedLicenses = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
$AssignedLicenses.AddLicenses = $License
$AssignedLicenses.RemoveLicenses = @()

#Assign the license to the user
Set-AzureADUserLicense -ObjectId $UserToLicense.ObjectId -AssignedLicenses $AssignedLicenses

In the latest preview version of the module ( that I used when writing the post, I didn’t manage to assign a license to a new user without defining the RemoveLicenses property of the AssignedLicenses object.

Verifying the licenses in the portal (yeah, could of course have done that with PowerShell as well.), it looks just as expected. If I wanted to enable more plans for the user I could just change the EnabledPlans array and run the script again.

Azure AD PowerShell V2.0 gives us all needed functionality to keep automating our license assignment in Azure AD. It might take you a bit longer to learn it since it is somewhat more “PowerShelly” with the different objects used to assign the licenses but apart from that, I really like it. I have not done any scientific tests (might do), but it seems like it is also much faster using the Graph API endpoints than the old endpoints doing different actions against Azure AD.
I will follow this post up with hopefully new and updated versions of my larger and more advanced scripts built on the old module.

Let me know if you have questions!


Common questions using Office 365 with ADFS and Azure MFA

Azure Multi Factor Authentication (MFA) is a great service that has been included in Office 365 for almost 2,5 years. The adoption has really been great – at least from an admin user perspective where 99% of my customers admins have it enabled (I usually force them).
From an end user perspective we have more technical and informational challenges, which means that the adoption has not been as great as on the admin side. Hopefully the new shiny Conditional access policies for specific workloads will boost the adoption a bit.

The purpose of this post is to share the most common questions I get from customers about using Azure MFA included in Office 365 (in most cases in combination with ADFS).

Q: Can we pre-stage the MFA authentication methods so the end user doesn’t have to enroll after being enabled for MFA?
A: As of now, unfortunately no – I tried to build a PowerShell function to pre-populate the authentication methods if the user already had a mobile phone number. I was fooled and thought it worked, but when I tried on a user that never had enrolled MFA before, it failed. Troubleshooting further, the required MFA property “StrongAuthenticationUserDetails” is not possible to pre-populate programmaticly, yet. Maybe the new AzureAD module can help here in the future.
Conclusion – we have to instruct our users to enroll for MFA.

Q: Can we prevent MFA from kicking in when authenticating from our internal network?
A: Absolutely – There are some options depending on if you have Azure AD Premium or not.

With Azure AD Premium
Here you can choose to “white list” your external IP addresses (which of course works with or without ADFS), or check the “Skip multi-factor authentication for requests from federated users on my intranet” checkbox. This will make Azure AD decide about MFA based on the insidecorporatenetwork claims issued by your own ADFS.
The following PowerShell rows will add the required Issuance Transform Rules to your Azure AD RP.

$ByPassMFAClaims = @"
@RuleName = "Passtrough - InsideCorporateNetwork"
c:[Type == ""]
 => issue(claim = c);

@RuleName = "Passtrough - PSSO"
c:[Type == ""]
 => issue(claim = c);
$AzureADRP = Get-AdfsRelyingPartyTrust -Name "Microsoft Office 365 Identity Platform" 
Set-AdfsRelyingPartyTrust -TargetName $AzureADRP.Name `
                          -IssuanceTransformRules ($AzureADRP.IssuanceTransformRules + $ByPassMFAClaims)

Without Azure AD Premium
Without Azure AD Premium we don’t have the same choices in service settings.
We can however achieve the same result, but instead of passing through the insidecorporatenetwork claims, we use it in ADFS and “tell” Azure AD that MFA is already taken care of. This can be done with the claim rules as below.

$ByPassMFAClaims = @"
@RuleName = "Bypass MFA from inside - Without Azure AD Premium"
EXISTS([Type == "", Value == "true"])
 => issue(Type = "", Value = "");

@RuleName = "Passtrough - PSSO"
c:[Type == ""]
 => issue(claim = c);
$AzureADRP = Get-AdfsRelyingPartyTrust -Name "Microsoft Office 365 Identity Platform" 
Set-AdfsRelyingPartyTrust -TargetName $AzureADRP.Name `
                          -IssuanceTransformRules ($AzureADRP.IssuanceTransformRules + $ByPassMFAClaims)

Q: Do we really need to use the f****** app passwords?
A: Not really anymore, at least not if you are using ADFS. I usually turn it off.
First of all most rich clients (Including Outlook/SfB on mobile devices) do now support Modern Authentication (ADAL), which means they can handle MFA out of the box. So as long as you have updated clients, you most often only need to handle ActiveSync (native mail clients in all kinds of devices). My approach here is usually to exclude them from MFA to get rid of the app password need, but enable conditional access in order to control the devices.

Below you find a claims rule for the ActiveSync protocol that issues the multipleauthn claim which Azure AD will honor by skipping MFA for the request.

$Claims = @"
@Claims= "Bypass MFA for ActiveSync"
EXISTS([Type == "", Value=="/adfs/services/trust/2005/usernamemixed"]) && 
EXISTS([Type == "", Value =~"^(Microsoft.Exchange.(Autodiscover|ActiveSync))$"]) 
=> Issue(Type = "", Value = ""); 
$AzureADRP = Get-AdfsRelyingPartyTrust -Name "Microsoft Office 365 Identity Platform" 
Set-AdfsRelyingPartyTrust -TargetName $AzureADRP.Name `
                          -IssuanceTransformRules ($AzureADRP.IssuanceTransformRules + $Claims)

Please note that additional rules may be needed depending on if you have an Exchange or Skype for Business Hybrid environment.

Q: Can we combine Azure MFA with our already implemented on-premises MFA solution?
A: It works fine to combine Azure MFA with any MFA solution that integrates with ADFS. The only thing you need to do is issue the authnmethodsreferences on the Azure AD RP to prevent users from getting “Double MFA” like SmartCard + Azure MFA. 🙂 For example, if I have Cert Auth as an enabled MFA provider as below, I only have to authenticate with my VSM/SmartCard even if MFA is enabled on the user.
The needed claims rule looks like this:

$Claims= @"
@RuleName = "Passthrough - MFA"
c:[Type == ""]
 => issue(claim = c);
$AzureADRP = Get-AdfsRelyingPartyTrust -Name "Microsoft Office 365 Identity Platform" 
Set-AdfsRelyingPartyTrust -TargetName $AzureADRP.Name `
                          -IssuanceTransformRules ($AzureADRP.IssuanceTransformRules + $Claims)

The above also works with the new Conditional Access policies for Exchange and SharePoint online.

Wrap up
Hopefully this post has given you some good insights what to think about implementing Azure MFA for Office 365. It is not a complete walk in the park, but it’s definately doable for most organizations.
As always, there are lots of if’s and but’s in all different environments. If I have missed something or if you have other, more specific questions, let me know!


How to resolve “We’ve run into a problem with your Office 365 subscription” with PowerShell

A colleague of mine performed a tenant to tenant migration a while ago. After the switchover to the new tenant, almost all users Office 365 ProPlus installations started to complain with the error message “We’ve run into a problem with your Office 365 subscription”. 2016-07-13_21-29-33
Signing out/in trying to activate the installation again didn’t help and after a while he found a solution at Jaap Wesselius blog.

The solution was to run the OSPP.vbs script located in the Office installation folder as in the screenshot below. Running the script with the /unpkey parameter removes the existing license and forces the user/client to re-register.

So – all good? The only challenge now was that he had over 200 clients to run the script on.

To help him automate this, I wrote a simple PowerShell script as a wrapper around OSPP.vbs to automate the key deactivation. It simply locates OSPP.vbs from the installation folder(s), fetches the key(s) and last removes all existing activations. Please note that it needs to run elevated and that it removes ALL activations on the machine.

    This script locates OSPP.vbs and removes all product keys to trigger O365 reactivation. It will remove ALL product keys.
    File Name: 
    Author   : Johan Dahlbom, johan[at]
    Blog     :
    The script is provided “AS IS” with no guarantees, no warranties, and they confer no rights.
#Check that the script runs with privileged rights
if (-not([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Warning "You need to have Administrator rights to run this script!`nPlease re-run this script as an Administrator in an elevated powershell prompt!"
#Find OSPP.vbs path and run the command with the dstatus option (Last 1...)
$OSPP = Resolve-Path -Path "C:\Program Files*\Microsoft Offic*\Office*\ospp.vbs" | Select-Object -ExpandProperty Path -Last 1
Write-Output -InputObject "OSPP Location is: $OSPP"
$Command = "cscript.exe '$OSPP' /dstatus"
$DStatus = Invoke-Expression -Command $Command

#Get product keys from OSPP.vbs output.
$ProductKeys = $DStatus | Select-String -SimpleMatch "Last 5" | ForEach-Object -Process { $_.tostring().split(" ")[-1]}

if ($ProductKeys) {
    Write-Output -InputObject "Found $(($ProductKeys | Measure-Object).Count) productkeys, proceeding with deactivation..."
    #Run OSPP.vbs per key with /unpkey option.
    foreach ($ProductKey in $ProductKeys) {
        Write-Output -InputObject "Processing productkey $ProductKey"
        $Command = "cscript.exe '$OSPP' /unpkey:$ProductKey"
        Invoke-Expression -Command $Command
} else {
    Write-Output -InputObject "Found no keys to remove... "

Hope this helps you if running in to this issue and as always – let me know if you have any questions!


Domain Join AzureRM VM’s with PowerShell

Until we have decommissioned all ‘legacy’ systems, we are still stuck in the need of joining our on-premises Active Directories for most of our servers. Deploying VM’s in Azure with the recommended deployment model Resource Manager makes it really easy to automate everything including the domain join process using JSON-templates deploying the resources.

In that case, you just define the JsonADDomainExtension for the VM’s that you want to join the domain as below:
You also find an example on how to use it here

However, a couple of weeks ago, I had a customer that had provisioned over 25 VM’s using AzureRM PowerShell instead of using JSON-templates. This is of course a lot better than if they would have done it manually through the portal, but unfortunately they had missed to join the domain in the deployment script.
To help them avoid doing manual labour, I wrote a small function that uses the same JsonADDomainExtension to automate the process of joining the already provisioned machines. The function has the join option set to 3 by default, which means it will create the AD object for the machine. It will also reboot the VM automatically.

If you simply want to join one Azure VM to the domain, you can simply run the function and specify parameters as in the screenshot below. It will automatically prompt for domain join credentials if not specified.

    Add-JDAzureRMVMToDomain -DomainName -VMName AMS-ADFS1 `
                            -ResourceGroupName 'ADFS-WestEurope' -Verbose

You can also check out the extension in the portal as below:
Joining multiple machines is almost as easy, if you want to pick your selection I recommend using Out-GridView with the -PassThru parameter, as also noted in one of the examples.

Get-AzureRmVM -ResourceGroupName 'ADFS-WestEurope' | Where-Object {$_.Name -like '*ADFS*'} |
    Add-JDAzureRMVMToDomain -DomainName -Verbose


function Add-JDAzureRMVMToDomain {
    The function joins Azure RM virtual machines to a domain.
    Get-AzureRmVM -ResourceGroupName 'ADFS-WestEurope' | Select-Object Name,ResourceGroupName | Out-GridView -PassThru | Add-JDAzureRMVMToDomain -DomainName -Verbose
    Add-JDAzureRMVMToDomain -DomainName -VMName AMS-ADFS1 -ResourceGroupName 'ADFS-WestEurope'
    Author   : Johan Dahlbom, johan[at]
    Blog     :
    The script are provided “AS IS” with no guarantees, no warranties, and it confer no rights.

    [System.Management.Automation.PSCredential]$Credentials = (Get-Credential -Message 'Enter the domain join credentials'),
    [ValidateScript({Get-AzureRmResourceGroup -Name $_})]
    begin {
        #Define domain join settings (username/domain/password)
        $Settings = @{
            Name = $DomainName
            User = $Credentials.UserName
            Restart = "true"
            Options = 3
        $ProtectedSettings =  @{
                Password = $Credentials.GetNetworkCredential().Password
        Write-Verbose -Message "Domainname is: $DomainName"
    process {
        try {
            $RG = Get-AzureRmResourceGroup -Name $ResourceGroupName
            $JoinDomainHt = @{
                ResourceGroupName = $RG.ResourceGroupName
                ExtensionType = 'JsonADDomainExtension'
                Name = 'joindomain'
                Publisher = 'Microsoft.Compute'
                TypeHandlerVersion = '1.0'
                Settings = $Settings
                VMName = $Name
                ProtectedSettings = $ProtectedSettings
                Location = $RG.Location
            Write-Verbose -Message "Joining $Name to $DomainName"
            Set-AzureRMVMExtension @JoinDomainHt
        } catch {
            Write-Warning $_
    end { }

I hope that everyone is using properly configured JSON-templates provisioning Azure Resources nowdays, but in case you don’t, I hope this function can be helpful.

As always, let me know if you have suggestions or questions!


Create AD Users with help from Azure Automation and SharePoint Online

As a follow up to one of my earlier posts where I Create AD Users with SharePoint Online as frontend, I now wanted to share an extension of this solution where we will utilize Azure Automation with a Hybrid Worker to do the heavy lifting.
So basically, instead of having a script as a scheduled task reading the SharePoint list and perform tasks based on status, we will now have a SharePoint workflow to initiate our runbooks through an Azure Automation Webhook.
I also want to thank Anders Bengtsson for his quite similiar post that finally made me finish this one up. 🙂

The post will cover the following steps

  • Create an Azure Automation runbook with a WebHook that executes the runbook on a Hybrid Worker.
  • Create a basic SharePoint workflow in SharePoint Designer with approval steps prior creating the user.
  • End user experience.

I assume that you already have the following in place.

I will use Azure PowerShell create and publish the runbook.

1. First we need to create a credential asset that will be used to write back information to our list.

#Login to Azure 
#Define ResourceGroup and Automation Account to be used used for with Automation cmdlets
$PSDefaultParameterValues = @{
    '*-AzureRmAutomation*:ResourceGroupName' = 'ResourceGroup'
    '*-AzureRmAutomation*:AutomationAccountName' = 'MyAutomationAccount'
#Create credential object with the SPO service account
$SPOCreds = Get-Credential 
#Create credential asset in Azure Automation
$SPOCredsHt = @{
    Name = 'SPOAdmin'
    Description = 'SharePoint Online Service Account for user onboarding'
    Value = $SPOCreds
New-AzureRmAutomationCredential @SPOCredsHt

2. Next up we need to create the actual runbook. Since we are doing everything with PowerShell, we need to save the script to a file and import it to Azure Automation. My example runbook (CreateADUserfromSPO.ps1) can be found below.

$SPORunbookHt = @{
    Path = 'C:\CreateADUserfromSPO.ps1'
    Name = 'Create-ADUsersFromSPO'
    Type = 'PowerShell'
    Published = $true
Import-AzureRmAutomationRunbook @SPORunbookHt 


param ( 

#SharePoint Connection Info
$SPCredentials = Get-AutomationPSCredential -Name 'SPOAdmin'
$SPConnection = @{
    SharePointSiteURL = ""
    Username = $SPCredentials.Username
    Password = $SPCredentials.GetNetworkCredential().Password
#Create an object from the webhook request
$UserData = ConvertFrom-Json -InputObject $WebhookData.RequestBody

$TargetOU = "OU=Users,OU=ACME,DC=corp,DC=acme,DC=com"
$ListName = "UserOnboarding"
$PasswordLength = "12"
$UPNSuffix = ''
$FirstName = $UserData.FirstName
$LastName = $UserData.LastName
$Title = $UserData.Title
$Manager = $UserData.Manager

#region functions
function Convert-ToLatinCharacters {
function Get-JDDNFromUPN {
    param (
        [ValidateScript({Get-ADUser -Filter {UserprincipalName -eq $_}})] 
        $ADUser = Get-ADUser -Filter {UserprincipalName -eq $UserPrincipalName} -ErrorAction stop
        return $ADUser.distinguishedname
function New-JDSamAccountName {
    param (
        [parameter(Mandatory=$false)][int]$FirstNameCharCount = 3,
        [parameter(Mandatory=$false)][int]$LastNameCharCount = 3
    #Construct the base sAMAccountName
    $BaseSam = "{0}{1}" -f (Convert-ToLatinCharacters $FirstName).Substring(0,$FirstNameCharCount),(Convert-ToLatinCharacters $LastName).Substring(0,$LastNameCharCount)
    #Add a number until you find a free sAMAccountName
    if (Get-ADUser -Filter {samaccountname -eq $BaseSam} -ErrorAction SilentlyContinue) {
        $index = 0
        do {
            $sAMAccountName = "{0}{1}" -f $BaseSam.ToLower(),$index
        } until (-not(Get-ADUser -Filter {samaccountname -eq $sAMAccountName } -ErrorAction SilentlyContinue))
    } else {
        $sAMAccountName = $BaseSam.tolower()
    return $sAMAccountName
function New-JDUPNAndMail {
    param (
    #Construct the base userPrincipalName
    $BaseUPN = "{0}.{1}@{2}" -f (Convert-ToLatinCharacters $FirstName).replace(' ','.').tolower(),(Convert-ToLatinCharacters $LastName).replace(' ','.').tolower(),$UPNSuffix
    if (Get-ADUser -Filter {userprincipalname -eq $BaseUPN} -ErrorAction SilentlyContinue) {
        $index = 0
        do {
            $UserPrincipalName = "{0}{1}@{2}" -f $BaseUPN.Split("@")[0],$index,$UPNSuffix
        } until (-not(Get-ADUser -Filter {userprincipalname -eq $UserPrincipalName} -ErrorAction SilentlyContinue))
    } else {
        $UserPrincipalName = $BaseUPN
    return $UserPrincipalName
function New-JDADUser {
    param (
        [Parameter(Mandatory=$true)][int]$PasswordLength = 12
     #Generate a password
     $Password = [System.Web.Security.Membership]::GeneratePassword($PasswordLength,2)
     #Construct the user HT
     $ADUserHt = @{
        GivenName = $FirstName
        SurName = $LastName
        ChangePasswordAtLogon = $true
        EmailAddress = $UserPrincipalName
        UserPrincipalName = $UserPrincipalName
        sAMAccountName = $sAMAccountName
        Title = $Title
        Name = "$FirstName $LastName ($sAMAccountName)"
        Displayname = "$FirstName $LastName"
        Manager = $Manager
        Path = $OU
        AccountPassword = (ConvertTo-SecureString -String $Password -AsPlainText -Force)
        Enabled = $true
        OtherAttribute = @{proxyAddresses = "SMTP:$UserPrincipalName"}
     try {
        #Create the user and return a custom object
        New-ADUser @ADUserHt -ErrorAction Stop 
        Write-Verbose "Successfully created the user $($ADUserHt.Name)"
        [pscustomobject] @{
            sAMAccountName = $ADUserHt.sAMAccountName 
            UserPrincipalName = $ADUserHt.UserPrincipalName 
            Password = $Password
     } catch {
        Write-Warning "Error creating the user $($ADUserHt.Name) `r`n$_"
#endregion functions
    try {
        $sAMAccountName = New-JDSamAccountName -FirstName $Firstname -LastName $LastName
        $UPNandMail = New-JDUPNAndMail -FirstName $Firstname -LastName $LastName -UPNSuffix $UPNSuffix
        $ManagerDN = Get-JDDNFromUPN -UserPrincipalName $Manager
        #Create the user in Active Directory
        $NewAdUserHt = @{
            FirstName = $Firstname
            LastName = $LastName
            Manager = $ManagerDN
            sAMAccountName = $sAMAccountName
            UserPrincipalName = $UPNandMail
            Title = $Title
            OU = $TargetOU
            PasswordLength = $PasswordLength
        Write-Output $NewAdUserHt
        $ADUser = New-JDADUser @NewAdUserHt -ErrorAction Stop
        $UpdateHt = @{
            Status = 'Created'
            UserName = $ADUser.sAMAccountName 
            EmailAddress = $ADUser.UserPrincipalName 
        Update-SPOListItem -SPOConnection $SPConnection -ListItemID $UserData.ID -ListFieldsValues $UpdateHt -ListName $ListName
    } catch {
         $UpdateHt = @{
            Status = 'Error'
        Update-SPOListItem -SPOConnection $SPConnection -ListItemID $UserData.ID -ListFieldsValues $UpdateHt -ListName $ListName
        Write-Warning $_

3. Last step is to create the Webhook that will be used when triggering the runbook from the SharePoint workflow. As notified when running the cmdlet, save the WebhookURI, you will need it later and cannot see it more than on Webhook creation. I have set the Webhook expirytime to 2 years, change it according to your needs.

$SPOWebHookHt = @{
    Name = 'SPOWorkflow'
    RunbookName = 'Create-ADUsersFromSPO'
    IsEnabled = $true
    ExpiryTime = (Get-Date).AddDays(730)
New-AzureRmAutomationWebhook @SPOWebHookHt


1. Open SharePoint Designer and open your website containing the custom list.
2. Add a new List Workflow to your site and associate the workflow with your custom list.
3. Click on the workflow and edit the Start Options to kick of the workflow when a new item has been created.
4. Edit and customize the workflow to fit your needs. In my case, I will have one stage for manager approval and one stage for executing the automation runbook.

Manager approval stage
a. Create a “Start a task process action” to submit the request to the manager.
b. Create a condition to Execute the runbook if the request was approved.

Execute Azure Automation Runbook stage
a. First build a dictionary with the data you want to pass to the automation webhook.
b. Insert a “Call HTTP Web Service” action and configure it to POST the earlier created dictionary to the Webhook url you saved creating the Webhook.
c. Our last step before ending the workflow will be to write back the response from the webhook to the SharePoint list item. This makes it easier for us to track if the task was properly submitted to Azure Automation. 2016-01-09_17-15-46
5. Check the workflow for errors before saving and publishing. This is my finished workflow before publishing it.

First, we create a new item in the SharePoint list to start the process.2016-01-09_19-04-18

The manager approval process sends an email to the new users manager as we stated in the workflow.

After the manager has approved the request, the workflow will kick off the runbook, create the user in Active Directory and write back the UserName/EmailAddress and status of the newly created user to the list. In this example, a password is generated but not distributed to anyone.

My hope is that you with this post have got some inspiration on what you can achieve with Azure Automation in combination with SharePoint (Online or On-Prem). Sky is the limit!


Recursively enumerate Azure AD Group members with PowerShell

Many of the scripts used to assign licenses for Azure AD / Office 365 users are utilizing groups to assign the licenses. On the topic I have received quite a lot requests on nested group support, which is not possible with Get-MsolGroupMember as of now.

To solve this problem, I have built a simple function canned Get-JDMSOLGroupMember. It checks if a group consists of other groups, and loops through them until all group members of all groups have been enumerated. In the end it will sort the members so that no duplicate member records are returned. It will only return users, not groups.

See the screenshot below on how it works:


function Get-JDMsolGroupMember { 
    The function enumerates Azure AD Group members with the support for nested groups.
    Get-JDMsolGroupMember 6d34ab03-301c-4f3a-8436-98f873ec121a
    Get-JDMsolGroupMember -ObjectId  6d34ab03-301c-4f3a-8436-98f873ec121a -Recursive
    Get-MsolGroup -SearchString "Office 365 E5" | Get-JDMsolGroupMember -Recursive
    Author   : Johan Dahlbom, johan[at]
    Blog     : 
    The script are provided “AS IS” with no guarantees, no warranties, and it confer no rights.

        [Parameter(Mandatory=$true, ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0)]
        [ValidateScript({Get-MsolGroup -ObjectId $_})]
    begin {
        $MSOLAccountSku = Get-MsolAccountSku -ErrorAction Ignore -WarningAction Ignore
        if (-not($MSOLAccountSku)) {
            throw "Not connected to Azure AD, run Connect-MsolService"
    process {
        Write-Verbose -Message "Enumerating group members in group $ObjectId"
        $UserMembers = Get-MsolGroupMember -GroupObjectId $ObjectId -MemberObjectTypes User -All
        if ($PSBoundParameters['Recursive']) {
            $GroupsMembers = Get-MsolGroupMember -GroupObjectId $ObjectId -MemberObjectTypes Group -All
            if ($GroupsMembers) {
                Write-Verbose -Message "$ObjectId have $($GroupsMembers.count) group(s) as members, enumerating..."
                $GroupsMembers | ForEach-Object -Process {
                    Write-Verbose "Enumerating nested group $($_.Displayname) ($($_.ObjectId))"
                    $UserMembers += Get-JDMsolGroupMember -Recursive -ObjectId $_.ObjectId 
        Write-Output ($UserMembers | Sort-Object -Property EmailAddress -Unique) 
    end {

As usual, let me know if you find issues or have any other suggestions.