Configuring Writeback Permissions in Active Directory for Azure Active Directory Sync

Posted on 34 CommentsPosted in 2008, 2008 R2, 2012, 2012 R2, active directory, ADFS 3.0, Azure, Azure Active Directory, cloud, exchange, exchange online, groups, hybrid, IAmMEC, Office 365, WAP, Web Application Proxy, windows

[Update March 2017 – added another blog post on using the below to fix permission-issue errors on admin and other protected accounts at]

[This blog post was last updated 18th June 2017 in advance of the release of AADConnect version 1.1.552.0. This post contains updates to the below scripts to include the latest attributes synced back to on-premises]

Azure Active Directory has been long the read-only cousin of Active Directory for those Office 365 and Azure users who sync their directory from Active Directory to Azure Active Directory apart from eight attributes for Exchange Server hybrid mode. Not any more. Azure Active Directory writeback is now available and in preview for some of the writeback types at the time of writing. This enabled objects to be mastered or changed in Azure Active Directory and written back to on-premises Active Directory.

This writeback includes:

  • Devices that can be enrolled with Office 365 MDM or Intune, which will allow login to AD FS controlled resources based on user and the device they are on
  • “Modern Groups” in Office 365 can be written back to on-premises Exchange Server 2013 CU8 or later hybrid mode and appear as mail enabled distribution lists on premises. Does not require AAD Premium licences
  • Users can change their passwords via the login page or user settings in Office 365 and have that password written back online.
  • Exchange Server hybrid writeback is the classic writeback from Azure AD and is the apart from Group Writeback is the only one of these writebacks that does not require Azure AD Premium licences.
  • User writeback from Azure AD (i.e. users made in Office 365 in the cloud for example) to on-premises Active Directory
  • Windows 10 devices for “Azure AD Domain Join” functionality

All of these features (apart from Exchange Hybrid writeback) require AADSync and not DirSync. Install and run the AADConnect program to migrate from DirSync to AADSync and then in the Synchronization Options on rerunning the AADConnect wizard you can add all these writeback functions.

SourceAnchor Writeback

For users with (typically) multi-forest deployments or plans or a forest migration, the objectGuid value in Active Directory, which is used as the source for the attribute that keys your on-premises object to your synced cloud object – in AAD sync parlance, this is known as the SourceAnchor. If you set up AADConnect version 1.1.552.0 or later you can opt to change from objectGuid to a new source anchor attribute known as ms-ds-consistencyGuid. To be able to use this new feature you need the ability for AADConnect connector account to be able to read ObjectGUID and then write it back to ms-ds-consistencyGuid. The read permissions are typically available to the connector account without doing anything special, and if AADConnect is installed in Express Mode it will get the write permissions it needs, but as with the rest of this blog, if you are not using Express Mode you need to grant the permissions manually and so write permissions are needed to the ms-ds-consistencyGuid attribute. This can be done with this script.

$accountName = "domain\aad_account" #[this is the account that will be used by Azure AD Connect Sync to manage objects in the directory, this is an account in the form of AAD_number].
$ForestDN = "DC=contoso,DC=com"

$cmd = "dsacls '$ForestDN' /I:S /G '`"$accountName`":WP;ms-ds-consistencyGuid;user'"
Invoke-Expression $cmd | Out-Null

Note that if you use ms-ds-consistencyGuid then there are changes required on your ADFS deployment as well. The Issuance Transform Rules for the Office 365 Relying Party Trust contains a rule that specifies the ImmutableID (aka AADConnect SourceAnchor) that the user will be identified as for login. By default this is set to ObjectGUID, and if you use AADConnect to set up ADFS for you then the application will update the rule. But if you set up ADFS yourself then you need to update the rule.

Issuance Transform Rules

When Office 365 is configured to federate a domain (use ADFS for authentication of that domain and not Azure AD) then the following are the claims rules that exist out of the box need to be adjusted. This is to support the use of ms-ds-consistencyguid as the immutable ID.

ADFS Management UI > Trust Relationships > Relying Party Trusts

Select Microsoft Office 365 Identity Platform > click Edit Claim Rules

You get two or three rules listed here. You get three rules if you use -SupportMultipleDomain switch in Convert-MSOLDomainToFederated.
Rule 1:
Change objectGUID to ms-DS-ConsistencyGUID
Rule Was:
c:[Type == “”]
=> issue(store = “Active Directory”, types = (“”, “”), query = “samAccountName={0};userPrincipalName,objectGUID;{1}”, param = regexreplace(c.Value, “(?<domain>[^\\]+)\\(?<user>.+)”, “${user}”), param = c.Value);
New Value:
c:[Type == “”]
=> issue(store = “Active Directory”, types = (“”, “”), query = “samAccountName={0};userPrincipalName,ms-DS-ConsistencyGUID;{1}”, param = regexreplace(c.Value, “(?<domain>[^\\]+)\\(?<user>.+)”, “${user}”), param = c.Value);

Preparing for Device Writeback

If you do not have a 2012 R2 or later domain controller then you need to update the schema of your forest. Do this by getting a Windows Server 2012 R2 ISO image and mounting it as a drive. Copy the support/adprep folder from this image or DVD to a 64 bit domain member in the same site as the Schema Master. Then run adprep /forestprep from an admin cmd prompt when logged in as a Schema Admin. The domain member needs to be a 64 bit domain joined machine for adprep.exe to run.

Wait for the schema changes to replicate around the network.

Import the cmdlets needed to configure your Active Directory for writeback by running Import-Module ‘C:\Program Files\Microsoft Azure Active Directory Connect\AdPrep\AdSyncPrep.psm1’ from an administrative PowerShell session. You need Azure AD Global Admin and Enterprise Admin permissions for Azure and local AD forest respectively. The cmdlets for this are obtained by running the Azure AD Connect tool.

$accountName = "domain\aad_account" #[this is the account that will be used by Azure AD Connect Sync to manage objects in the directory, this is an account in the form of AAD_number].
Initialize-ADSyncDeviceWriteBack -AdConnectorAccount $accountName -DomainName #[domain where devices will be created].

This will create the “Device Registration Services” node in the Configuration partition of your forest as shown:


To see this, open Active Directory Sites and Services and from the View menu select Show Services Node. Also in the domain partition you should now see an OU called RegisteredDevices. The AADSync account now has permissions to write objects to this container as well.

In Azure AD Connect, if you get the error “This feature is disabled because there is no eligible forest with appropriate permissions for device writeback” then you need to complete the steps in this section and click Previous in the AADConnect wizard to go back to the “Connect your directories” page and then you can click Next to return to the “Optional features” page. This time the Device Writeback option will not be greyed out.

Device Writeback needs a 2012 R2 or later AD FS server and WAP to make use of the device info in the Active Directory (for example, conditional access to resources based on the user and the device they are using). Once Device Writeback is prepared for with these cmdlets and the AADConnect Synchronization Options page is enabled for Device Writeback then the following will appear in Active Directory:


Not shown in the above, but adding the Display Name column in Active Directory Users and Computers tells you the device name. The registered owner and registered users of the device are available to view, but as they are SID values, they are not really readable.

If you have multiple forests, then you need add the SCP record for the tenant name in each separate forest. The above will do it for the forest AADConnect is installed in and the below script can be used to add the SCP to other forests:

$verifiedDomain = ""  # Replace this with any of your verified domain names in Azure AD
$tenantID = "27f998bf-86f2-41bf-91ab-2d7ab011df35"  # Replace this with you tenant ID
$configNC = "CN=Configuration,DC=corp,DC=contoso,DC=com"  # Replace this with your AD configuration naming context
$de = New-Object System.DirectoryServices.DirectoryEntry
$de.Path = "LDAP://CN=Services," + $configNC
$deDRC = $de.Children.Add("CN=Device Registration Configuration", "container")
$deSCP = $deDRC.Children.Add("CN=62a0ff2e-97b9-4513-943f-0d221bd30080", "serviceConnectionPoint")
$deSCP.Properties["keywords"].Add("azureADName:" + $verifiedDomain)
$deSCP.Properties["keywords"].Add("azureADId:" + $tenantID)

Preparing for Group Writeback

Writing Office 365 “Modern Groups” back to Active Directory on-premises requires Exchange Server 2013 CU8 or later schema updates and servers installed. To create the OU and permissions required for Group Writeback you need to do the following.

Import the cmdlets needed to configure your Active Directory for writeback by running Import-Module ‘C:\Program Files\Microsoft Azure Active Directory Connect\AdPrep\AdSyncPrep.psm1’ from an administrative PowerShell session. You need Domain Admin permissions for the domain in the local AD forest that you will write back groups to. The cmdlets for this are obtained by running the Azure AD Connect tool.

$accountName = "domain\aad_account" #[this is the account that will be used by Azure AD Connect Sync to manage objects in the directory, this is an account usually in the form of AAD_number].
$cloudGroupOU = "OU=CloudGroups,DC=contoso,DC=com"
Initialize-ADSyncGroupWriteBack -AdConnectorAccount $accountName -GroupWriteBackContainerDN $cloudGroupOU

Once these cmdlets are run the AADSync account will have permissions to write objects to this OU. You can view the permissions in Active Directory Users and Computers for this OU if you enable Advanced mode in that program. There should be a permission entry for this account that is not inherited from the parent OU’s.

At the time of writing, the distribution list that is created on writeback from Azure AD will not appear in the Global Address List in Outlook etc. or allow on-premises mailboxes to send to these internal only cloud based groups. To add it to the address book you need to create a new subdomain, update public DNS and add send connectors to hybrid Exchange Server. This is all outlined in This ensure’s that on-premises mailboxes can deliver to groups as internal senders and not require external senders enabled on the group. To add the group to the Global Address List you need to run Update-AddressList in Exchange Server. Once group writeback is prepared for using these cmdlets here and AADConnect has had it enabled during the Synchronization Options page, you should see the groups appearing in the selected OU as shown:


And you should find that on-premises users can send email to these groups as well.

Preparing for Password Writeback

The option for users to change their passwords in the cloud and have then written back to on-premises (with multifactor authentication and proof of right to change the password) is also available in Office 365 / Azure AD with the Premium Azure Active Directory or Enterprise Mobility Pack licence.

To enable password writeback for AADConnect you need to enable the Password Writeback option in AADConnect synchronization settings and then run the following three PowerShell cmdlets on the AADSync server:

Get-ADSyncConnector | fl name,AADPasswordResetConfiguration
Get-ADSyncAADPasswordResetConfiguration -Connector " - AAD"
Set-ADSyncAADPasswordResetConfiguration -Connector " - AAD" -Enable $true

The first of these cmdlets lists the ADSync connectors and the name and password reset state of the connector. You need the name of the AAD connector. The middle cmdlet tells you the state of password writeback on that connector and the last cmdlet enables it if needed. The name of the connector is required in these last two cmdlets.

To set the permissions on-premises for the passwords to be written back the following script is needed:

$passwordOU = "DC=contoso,DC=com" #[you can scope this down to a specific OU]
$accountName = "domain\aad_account" #[this is the account that will be used by Azure AD Connect Sync to manage objects in the directory, this is an account usually in the form of AAD_number].

$cmd = "dsacls.exe '$passwordOU' /I:S /G '`"$accountName`":CA;`"Reset Password`";user'"
Invoke-Expression $cmd | Out-Null

$cmd = "dsacls.exe '$passwordOU' /I:S /G '`"$accountName`":CA;`"Change Password`";user'"
Invoke-Expression $cmd | Out-Null

$cmd = "dsacls.exe '$passwordOU' /I:S /G '`"$accountName`":WP;lockoutTime;user'"
Invoke-Expression $cmd | Out-Null

$cmd = "dsacls.exe '$passwordOU' /I:S /G '`"$accountName`":WP;pwdLastSet;user'"
Invoke-Expression $cmd | Out-Null

Finally you need to run the above once per domain.

Preparing for Exchange Server Hybrid Writeback

Hybrid mode in Exchange Server requires the writing back on eight attributes from Azure AD to Active Directory. The list of attributes written back is found here. The following script will set these permissions for you in the OU you select (or as shown at the root of the domain). The DirSync tool used to do all this permissioning for you, but the AADSync tool does not. Therefore scripts such as this are required. This script sets lots of permissions on these eight attributes, but for clarify on running the script the output of the script is sent to Null. Remove the “| Out-Null” from the script to see the changes as they occur (the script also takes a lot longer to run).

$accountName = "domain\aad_account"
$HybridOU = "DC=contoso,DC=com"

#Object type: user
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;proxyAddresses;user'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msExchUCVoiceMailSettings;user'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msExchUserHoldPolicies;user'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msExchArchiveStatus;user'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msExchSafeSendersHash;user'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msExchBlockedSendersHash;user'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msExchSafeRecipientsHash;user'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msDS-ExternalDirectoryObjectID;user'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;publicDelegates;user'"
Invoke-Expression $cmd | Out-Null

#Object type: iNetOrgPerson
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;proxyAddresses;iNetOrgPerson'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msExchUCVoiceMailSettings;iNetOrgPerson'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msExchUserHoldPolicies;iNetOrgPerson'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msExchArchiveStatus;iNetOrgPerson'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msExchSafeSendersHash;iNetOrgPerson'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msExchBlockedSendersHash;iNetOrgPerson'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msExchSafeRecipientsHash;iNetOrgPerson'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;msDS-ExternalDirectoryObjectID;iNetOrgPerson'"
Invoke-Expression $cmd | Out-Null
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;publicDelegates;iNetOrgPerson'"
Invoke-Expression $cmd | Out-Null

#Object type: group
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;proxyAddresses;group'"
Invoke-Expression $cmd | Out-Null

#Object type: contact
$cmd = "dsacls '$HybridOU' /I:S /G '`"$accountName`":WP;proxyAddresses;contact'"
Invoke-Expression $cmd | Out-Null

Finally you need to run the above once per domain.

Preparing for User Writeback

[This functionality is not in the current builds of AADConnect]

Currently in preview at the time of writing, you are able to make users in Azure Active Directory (cloud users as Office 365 would call them) and write them back to on-premises Active Directory. The users password is not written back and so needs changing before the user can login on-premises.

To prepare the on-premises Active Directory to writeback user objects you need to run this script. This is contained in AdSyncPrep.psm1 and that is installed as part of Azure AD Connect. Azure AD Connect will install Azure AD Sync, which is needed to do the writeback. To load the AdSyncPrep.psm1 module into PowerShell run Import-Module ‘C:\Program Files\Microsoft Azure Active Directory Connect\AdPrep\AdSyncPrep.psm1’ from an administrative PowerShell session.

$accountName = "domain\aad_account" #[this is the account that will be used by Azure AD Connect Sync to manage objects in the directory, this is an account usually in the form of AAD_number].
$cloudUserOU = "OU=CloudUsers,DC=contoso,DC=com"
Initialize-ADSyncUserWriteBack -AdConnectorAccount $accountName -UserWriteBackContainerDN $cloudUserOU

Once the next AADSync occurs you should see users in the OU used above that match the cloud users in Office 365 as shown:


Prepare for Windows 10 Registered Device Writeback Sync

Windows 10 devices that are joined to your domain can be written to Azure Active Directory as a registered device, and so conditional access rules on device ownership can be enforced. To do this you need to import the AdSyncPrep.psm1 module. This module supports the following two additional cmdlets to prepare your Active Directory for Windows 10 device sync:

CD "C:\Program Files\Microsoft Azure Active Directory Connect\AdPrep"
Import-Module .\AdSyncPrep.psm1

These cmdlets are run as follows:

$accountName = "domain\aad_account" #[this is the account that will be used by Azure AD Connect Sync to manage objects in the directory, this is an account usually in the form of AAD_number].
$azureAdCreds = Get-Credential #[Azure Active Directory administrator account]

CD "C:\Program Files\Microsoft Azure Active Directory Connect\AdPrep"
Import-Module .\AdSyncPrep.psm1
Initialize-ADSyncDomainJoinedComputerSync -AdConnectorAccount $accountName -AzureADCredentials $azureAdCreds 
Initialize-ADSyncNGCKeysWriteBack -AdConnectorAccount $accountName 

Once complete, open Active Directory Sites and Services and from the View menu Show Services Node. Then you should see the GUID of your domain under the Device Registration Configuration container.


Managing Office 365 Groups With Remote PowerShell

Posted on 2 CommentsPosted in Azure, cloud, exchange, exchange online, groups, IAmMEC, mcm, mcsm, MVP, Office 365, owa, powershell

Announced during Microsoft Ignite 2015, there are now PowerShell administration cmdlets available for the administration of the Groups feature in Office 365.

The cmdlets are all based around “UnifedGroups”, for example Get-UnifiedGroups.

Create a Group

Use New-UnifiedGroup to do this. An example would be New-UnifiedGroup -DisplayName “Sales” -Alias sales –EmailAddress

The use of the EmailAddress parameter is useful as it allows you to set a group that is not given an email address based on your default domain, but from one of the other domains in your Office 365 tenant.

Modify a Groups Settings

Use Set-UnifiedGroup to change settings such as the ability to receive emails from outside the tenant (RequireSenderAuthenticationEnabled would be $false), limit email from a whitelist (AcceptMessagesOnlyFromSendersOrMembers) and other Exchange distribution list settings such as hidden from address lists, mail tips and the like. AutoSubscribeNewMembers can be used to tell the group to email all new messages to all new members, PrimarySmtpAddress to change the email address that the group sends from.

Remove a Group

This is the new Remove-UnifiedGroup cmdlet.

Add Members to a Group

This cmdlet is Add-UnifiedGroupLinks. For example Add-UnifiedGroupLinks sales -LinkType members -Links brian,nicolas will add the two names members to the group. The LinkType value can be members as shown, but also “owners” and “subscribers” to add group administrators (owners) or just those who receive email sent to the group but not access to the groups content. To change members to owners you do not need to remove the members, just run something like Add-UnifiedGroupLinks sales –LinkType owners -Links brian,nicolas

You can also pipe in a user list from, for example a CSV file, to populate a group. This would read: Add-UnifiedGroupLinks sales -LinkType members -Links $users where $users = Get-Content username.csv would be run before it to populate the $users variable. The source of the variable can be anything done in PowerShell.

Remove Members from a Group

For this use Remove-UnifiedGroupLinks and mention the group name, the LinkType (member, owner or subscriber) and the user or users to remove.

To Disable Group Creation in OWA

Set-OWAMailboxPolicy is used to create a policy that is not allowed to create Groups and then users have that policy applied to them. For example Set-OWAMailboxPolicy “Students” –GroupCreationEnabled $false followed by Set-CASMailbox mary –OWAMailboxPolicy Students to stop the user “mary” creating groups. After the policy is assigned and propagates around the Office 365 service, the user can join and leave groups, but not create them.

Control Group Naming

This feature allows you to control the group name or block words from being used. This is easier to set in the Distribution Groups settings in Exchange Control Panel rather than via PowerShell. To do this EAC use Recipients > Groups and click the ellipses icon (…) and select Configure Group Naming Policy. This is the same policy for distribution groups. You can add static text to the start or end of name, as well as dynamic text such as region.

Admins creating groups are not subject to this policy, but unlike DL’s if they create groups in PowerShell the policy is also not applied and so the -IgnoreNamingPolicy switch is not required.

Speaking at TechEd Europe 2014

Posted on 4 CommentsPosted in certificates, cloud, EOP, exchange, exchange online, Exchange Online Protection, GeoDNS, hybrid, IAmMEC, journaling, mcm, mcsm, MVP, Office 365, smarthost, smtp, starttls, TechEd, TLS, transport

I’m please to announce that Microsoft have asked me to speak on “Everything You Need To Know About SMTP Transport for Office 365” at TechEd Europe 2014 in Barcelona. Its going to be a busy few weeks as I go from there to the MVP Summit in Redmond, WA straight from that event.


My session is going to see how you can ensure your migration to Office 365 will be successful with regards to keeping mail flow working and not seeing any non-deliverable messages. We will cover real world scenarios for hybrid and staged migrations so that we can consider the impact of mail flow at all stages of the project. We will look at testing mail flow, SMTP to multiple endpoints, solving firewalling issues, and how email addressing and distribution group delivery is done in Office 365 so that we always know where a user is and what is going to happen when they are migrated.

Compliance and hygiene issues will be covered with regards to potentially journaling from multiple places and the impact of having anti-spam filtering in Office 365 that might not be your mail flow entry point.

We will consider the best practices for changing SMTP endpoints and when is a good time to change over from on-premise first to cloud first delivery, and if you need to maintain on-premises delivery how should you go about that process.

And finally we will cover troubleshooting the process should it go wrong or how to see what is actually happening during your test phase when you are trying out different options to see which works for your company and your requirements.

Full details of the session, once it goes live, are at (Microsoft ID login needed to see this). Room and time to be announced.

Creating Mailboxes in Office 365 When Using DirSync

Posted on 12 CommentsPosted in 2008 R2, 2012, 2012 R2, 2013, Azure, cloud, dirsync, exchange, exchange online, Office 365

This blog post describes the process to create a new user in Active Directory on-premises when email is held in Office 365 and DirSync is in use. With DirSync in use the editable copy of the user object is on-premises and most attributes cannot be modified in the cloud.

Creating the User

  1. Open Active Directory Users and Computers on a Windows 2008 R2 or later server. Ensure that Advanced Features is enabled (View > Advanced Features)
    • Note that if you do not have 2008 R2 or later then use ADSI Edit to make the changes mentioned below that are made on the Attribute Editor tab in Active Directory Users and Computers 2008 R2 or later.
  2. Create an Active Directory user as you normally would. Do not complete any Exchange server properties if you are requested to do so. Completing Exchange on-premises will make a mailbox on premises that will then need to be migrated to Exchange Online. This document describes creating the mailbox online.
  3. Ensure that the user’s email address on the General tab of the AD properties is correct.
  4. Ensure that the users login name on the Account tab is as follows:
    1. User Logon Name: The first part of their email address
    2. The Domain name drop-down: The second part of their email address (not the AD domain name if they are different)
    3. User Logon Name (Pre Windows 2000): DOMAIN as provided and use the first part of the email address (i.e. first.last etc). If first part of email is too long enter as much as you can and ensure it is unique within domain)

Setting the Email Address Properties

  1. On the Attribute Editor tab ensure that Filter > Show only attributes that have values is not selected. Then find and enter the following information:
    1. proxyAddresses: for this user – SMTP needs to be in capitals. Then add additional email addresses as required, but these start with smtp: in lower case.
    2. targetAddress:
    3. Note that both these addresses need to be unique within your directory – Attribute Editor will not check them for uniqueness but they will fail to replicate to Azure with DirSync if they are not unique.
  2. Click OK and close the account creation dialog.
  3. Within three hours this object will sync to Windows Azure Active Directory.
    1. This can be speeded up by logging into the DirSync server and starting PowerShell
    2. Type “Import-Module DirSync” in PowerShell
    3. Type “Start-OnlineCoexistenceSync” in PowerShell – DirSync will replicate now rather than waiting up to three hours.
  4. Check that the DirSync process was successful – if you have entered values that are not unique then DirSync will fail to replicate them and you will need to fix them on-premises and replicate them again.
  5. Licence the user in Office 365 by logging into and granting a licence to this user that contains an Exchange Online licence. The mailbox will be created automatically shortly after this.

Additional Attributes

The following are a list of attributes to change in ADSI Edit or the Attribute Editor tab to modify other attributes as required:

  • msExchHideFromAddressLists – Set to TRUE to hide from address lists
  • msExchRecipientDisplayType – Set to 6 for a remote mail user, 7 for room mailbox and 8 for an equipment mailbox, and 0 for a mailbox. A full list of these is at

Enabling Microsoft Rights Management in SharePoint Online

Posted on Leave a commentPosted in aadrm, active directory, cloud, IAmMEC, Office 365, policy, rms, sharepoint

This article is the fifth in a series of posts looking at Microsoft’s new Rights Management product set. In an earlier previous post we looked at turning on the feature in Office 365 and in this post we will look at protecting documents in SharePoint. This means your cloud users and will have their data protected just by saving it to a document library.

In this series of articles we will look at the following:

The items above will get lit up as the articles are released – so check back or leave a comment to the first post in the series and I will let you know when new content is added.

To enable SharePoint Online to integrate with Microsoft Rights Management you need to turn on RMS in SharePoint. You do this with the following steps:

  1. Go to service settings, click sites, and then click View site collections and manage additional settings in the SharePoint admin center:
  2. Click settings and find Information Rights Management (IRM) in the list:
  3. Select Use the IRM service specified in your configuration and click Refresh IRM Settings:
  4. Click OK

Once this is done, you can now enable selected document libraries for RMS protection.

  1. Find the document library that you want to enforce RMS protection upon and click the PAGE tab to the top left of the SharePoint site (under the Office 365 logo).
  2. Then click Library Settings:
  3. If the site is not a document library, for example the picture below shows a “document center” site you will not see the Library Settings option. For these sites, navigate to the document library specifically and click the LIBRARY tab and then choose Library Settings:
  4. Click Information Rights Management
  5. Select Restrict permissions on this library on download and add your policy title and policy description. Click SHOW OPTIONS to configure additional RMS settings on the library, and then click OK.
  6. The additional options allow you to enforce restrictions to the document library such as RMS key caching (for offline use) and to allow the document to be shared with a group of users. This group must be mail enabled (or at least have an email address in its email address attribute) and be synced to the cloud.

To start using the RMS functionality in SharePoint, upload a document to this library or create a new document in the library. Then download the document again – it will now be RMS protected.

Exchange DLP Rules in Exchange Management Shell

Posted on Leave a commentPosted in 2013, cloud, DLP, EOP, exchange, exchange online, Exchange Online Protection, IAmMEC, IFilter, mcm, mcsm, Office 365

This one took a while to work out, so noting it down here!

If you want to create a transport rule for a DLP policy that has one data classification (i.e. data type to look for such as ‘Credit Card Number’) then that is easy in PowerShell and an example would be as below.

New-TransportRule -name “Contoso Pharma Restricted DLP Rule (Blocked)” -DlpPolicy ContosoPharma” -SentToScope NotInOrganization -MessageContainsDataClassifications @{Name=”Contoso Pharmaceutical Restricted Content”} -SetAuditSeverity High -RejectMessageEnhancedStatusCode 5.7.1 -RejectMessageReasonText “This email contains restricted content and you are not allowed to send it outside the organization”

As you can see, and highlighted in red, the data classification is a hashtable and the single classification is mentioned.

To add more than one classification is much more involved:

$DataClassificationA = @{Name=”Contoso Pharmaceutical Private Content”}
$DataClassificationB = @{Name=”Contoso Pharmaceutical Restricted Content”}
$AllDataClassifications = @{}
New-TransportRule -name “Notify if email contains ContosoPharma documents 1” -DlpPolicy “ContosoPharma” -SentToScope NotInOrganization -MessageContainsDataClassifications $AllDataClassifications.Values -SetAuditSeverity High -GenerateIncidentReport administrator -IncidentReportContent “Sender”,”Recipients”,”Subject” -NotifySender NotifyOnly

And as you can see, shown in red above, you need to make a hashtable of hashtables and then use the value of the final hashtable in the New-TransportRule

An “Inexpensive” Exchange Lab In Azure

Posted on Leave a commentPosted in 2010, 2013, Azure, cloud, DNS, exchange, exchange online, hyper-v, IAmMEC, Office 365, vhd, vm, vpn

This blog post centres around two scripts that can be used to quickly provision an Exchange Server lab in Azure and then to remove it again. The reason why the blog post is titled “inexpensive” is that Azure charges compute hours even if the virtual machines are shut down. Therefore to make my Exchange lab cheaper to operate and to not charge me when the lab is not being used, I took my already provisioned VHD files and created a few scripts to create the virtual machines and cloud service and then to remove it again if needed.

Before you start using these scripts, you need to have already uploaded or created your own VHD’s in Azure and designed your lab as you need. These scripts will then take a CSV file with the relevant values in them and create a VM for each VHD in the correct subnet (that you have also created in Azure) and always in the correct order – thus ensuring they always get the same IP address from your virtual network (UPDATE: 14 March 2014 – Thanks to Bhargav, this script now reserves the IPs as well as this is a newish feature in Azure). Without reserving an IP, when you boot your domain controller first in each subnet it will always get the fourth available IP address. This IP is the DNS IP address in Azure and then each of the other machines are created and booted in the order of your choosing and so get the subsequent IP’s. Azure never used to guarantee the IP but updates in Feb 2014 now allow this with the latest Azure PowerShell cmdlets. This way we can ensure the private IP is always the same and machine dependancies such as domain controllers running first are adhered to.

These scripts are created in PowerShell and call the Windows Azure PowerShell cmdlets. You need to install the Azure cmdlets on your computer and these scripts rely on features found in version or later. You can install the cmdlets from


# Retrieve with Get-AzureSubscription 
$subscriptionName = "Visual Studio Premium with MSDN"

Import-AzurePublishSettingsFile ''

# Select the subscription to work on if you have more than one subscription
Select-AzureSubscription -SubscriptionName $subscriptionName

# Name of Virtual Network to add VM's to
$VMNetName = "MCMHybrid"

# CSV File with following columns (BringOnline,VMName,StorageAccount,VMOSDiskName,VMInstanceSize,SubnetName,IPAddress,Location,AffinityGroup,WaitForBoot,PublicRDPPort)
$CSVFile = Import-CSV 'path\filename.csv'

# Loop to build lab here. Ultimately get values from CSV file
foreach ($VMItem in $CSVFile) {

    # Retrieve with Get-AzureStorageAccount  
    $StorageAccount = $VMItem.StorageAccount

    # Specify the storage account location containing the VHDs 
    Set-AzureSubscription -SubscriptionName $subscriptionName  -CurrentStorageAccount $StorageAccount
    # Not Used $location = $VMItem.Location     # Retrieve with Get-AzureLocation

    # Specify the subnet to use. Retreive with Get-AzureVNetSite | FL Subnets
    $subnetName = $VMItem.SubnetName

    $AffinityGroup = $VMItem.AffinityGroup      # From Get-AzureAffinityGroup (for association with a private network you have already created). 

    $VMName = $VMItem.VMName
    $VMOSDiskName = $VMItem.VMOSDiskName        # From Get-AzureDisk
    $VMInstanceSize = $VMItem.VMInstanceSize    # ExtraSmall, Small, Medium, Large, ExtraLarge 
    $CloudServiceName = $VMName
    $IPAddress = $VMItem.IPAddress              # Reserves a specific IP for the VM
    if ($VMItem.BringOnline -eq "Yes") {
        Write-Host "Creating VM: " $VMName
        $NewVM = New-AzureVMConfig -Name $VMName -DiskName $VMOSDiskName -InstanceSize $VMInstanceSize | Add-AzureEndpoint -Name 'Remote Desktop' -LocalPort 3389 -PublicPort $VMItem.PublicRDPPort -Protocol tcp | Add-AzureEndpoint -Protocol tcp -LocalPort 25 -PublicPort 25 -Name 'SMTP' | Add-AzureEndpoint -Protocol tcp -LocalPort 443 -PublicPort 443 -Name 'SSL' | Add-AzureEndpoint -Protocol tcp -LocalPort 80 -PublicPort 80 -Name 'HTTP' | Set-AzureSubnet –SubnetNames $subnetName | Set-AzureStaticVNetIP –IPAddress $IPAddress        
        # Creates new VM and waits for it to boot if required
        if ($VMItem.WaitForBoot -eq "Yes") {New-AzureVM -ServiceName $CloudServiceName -AffinityGroup $AffinityGroup -VMs $NewVM -VNetName $VMNetName -WaitForBoot}
            else {New-AzureVM -ServiceName $CloudServiceName -AffinityGroup $AffinityGroup -VMs $NewVM -VNetName $VMNetName }


# Retrieve with Get-AzureSubscription 
$subscriptionName = "Visual Studio Premium with MSDN"

Import-AzurePublishSettingsFile ''

# Select the subscription to work on if you have more than one subscription
Select-AzureSubscription -SubscriptionName $subscriptionName

# CSV File with following columns (BringOnline,VMName,StorageAccount,VMOSDiskName,VMInstanceSize,SubnetName,IPAddress,Location,AffinityGroup,WaitForBoot,PublicRDPPort)
$CSVFile = Import-CSV 'path\filename.csv'

# Loop to build lab here. Ultimately get values from CSV file
foreach ($VMItem in $CSVFile) {

    # Stop VM
    Stop-AzureVM -Name $VMItem.VMName -ServiceName $VMItem.VMName -Force

    # Remove VM but leave VHDs behind
    Remove-AzureVM -ServiceName $VMItem.VMName -Name $VMItem.VMName 

    # Remove Cloud Service
    Remove-AzureService $VMItem.VMName -Force

CSV File Format

The CSV file has a row per virtual machine, listed in order that the machine is booted:

Yes,mh-oxf-dc1,portalvhdsjv47jtq9qdrmb,mh-oxf-mbx2-mh-oxf-mbx2-0-201312301745030496,Small,Oxford,,West Europe,C7Solutions-AG,Yes,3389

The columns are as follows:

  • BringOnline: Yes or No
  • VMName: This name is used for the VM and the Cloud Service. It must be unique within Azure. An example might be EX-LAB-01 (if that is unique that is)
  • StorageAccount: The name of the storage account that the VHD is stored in. This might be one you created yourself or one made by Azure with a name containing random letters. For example portalvhdshr4djwe9dwcb5 would be what this value might look like. Use Get-AzureStorageAccount to find this value.
  • VMOSDiskName: This is the disk name (not the file name) and is retrieved with Get-AzureDisk
  • VMInstanceSize: ExtraSmall, Small, Medium, Large or ExtraLarge
  • SubnetName: Get with Get-AzureVNetSite | FL Subnets
  • IPAddress: Sets a specific IP address for the VM. VM will always get this IP when it boots and other VM’s will not take it if the happen to boot before it
  • Location: Retrieve with Get-AzureLocation. This value is not used in the script as I use Affinity Groups and subnets instead.
  • AffinityGroup: From Get-AzureAffinityGroup (for association with a private network you have already created).
  • WaitForBoot: Yes or No. This will wait for the VM to come online (and thus get an IP correctly provisioned in order) or ensure things like the domain controller is running first.
  • PublicRDPPort: Set to 3389 unless you want to use a different port. For simplicity, the script sets ports 443, 80 and 25 as open on the IP addresses of the VM

Highly Available Office 365 to On-Premises Mail Routing

Posted on 20 CommentsPosted in 2010, 2013, cloud, DNS, EOP, exchange, exchange online, Exchange Online Protection, hybrid, IAmMEC, MX, Office 365, smarthost, smtp

This article looks at how to configure mail flow from Office 365 (via Exchange Online Protection – EOP) to your On Premises organization to ensure that it is highly available and work in disaster recovery scenarios with no impact. It is based on exactly the same principle to that which I blogged about in 2012: on creating redundant outbound connections from Exchange on premises.

The best way to explain this feature is to describe it in the way of an example:

For example MCMEmail Ltd have Hybrid set up, and delivery to the cloud first. So the DNS zone for has MX pointing to EOP.

They then create a new DNS zone at either a subzone (as in this example) or a different domain if they have one available. In the example this could be Into this zone they add the following records:

10 MX

10 MX

20 MX

The below picture shows an example of this configured in AWS Route 53 DNS (though there are other DNS providers available)


In Exchange Online Protection administration pages (Office 365 Portal > Exchange Admin > Mail Flow > Connectors and modify your on-premises connector to point to the new zone. Example shown in the below picture:


Then all email is always delivered to the Oxford datacentre and nothing to the Nuneaton one (where the DR servers reside) unless the two Oxford datacentres (A and B) are both offline and so the 10 preference does not answer at all. At that time and that time only does the 20 preference get connected to.

Errors in Moving Exchange Archive Mailboxes to Office 365

Posted on 1 CommentPosted in 2010, 2013, archive, cloud, exchange, exchange online, Office 365, Outlook

I was trying to move an Archive mailbox to the Office 365 service from my demo environment the other day when I came across an error I thought I would note down here for completion. I could not find the error elsewhere on the internet

An archive mailbox must be enabled before it can be moved

Now this sounds a stupid sort of error, because if I am moving an archive mailbox then it must already be enabled or the move mailbox wizard will not let me move it. But the mailbox does have an archive on the Exchange organization on-premises, but when the move has completed it has errors reported.

The reason for the error is all down, in my case, to two things.

  1. Its a demo environment and I am doing things too quickly
  2. DirSync is not working at the moment.

In my scenario the DirSync services on my server had stopped a few weeks ago and I had not started them – ensure that DirSync is running. And secondly, as it was a demo I was doing I was creating an archive mailbox and then moving it to the cloud shortly afterwards. Even if DirSync was running, the chances are that it would not have had a chance to sync the existence of the archive mailbox associated with the user account to Office 365’s directory. Archive mailboxes can only be moved from on-premises to the cloud if the cloud service knows about the mailbox archive to move.

To fix my issue I restarted DirSync services and forced a full sync with the cmdlet Start-OnlineCoexistenceSync –FullSync. See on the steps to force a directory sync for running this cmdlet.

Once the sync was completed and Office 365 directory is aware that my user has an on-premises archive I was able to move the archive to Office 365 and keep the mailbox on-premises.

Of course, if I want to create an archive in the cloud with a mailbox on premises for real (not a demo) then I would just create the archive straight in the cloud. My scenario and the three hour DirSync delay (or forcing DirSync) was only needed as I had created an archive and then moved it.

Creating an Azure VPN with a Draytek Router

Posted on 10 CommentsPosted in Azure, cloud, draytek, exchange, firewall, ipsec, vpn

The Microsoft Azure cloud operating system can be connected to your network by way of a virtual private network or VPN. Azure lists some supported devices and provides configuration scripts for them, but does not include the Draytek range of devices. Draytek devices are common in the small business market and for techy home users. This blog post will show how to configure a site to site VPN between your network and your Azure tenant using a Draytek 2920 router. Other Draytek routers will work as well, just the screenshots and instructions here are from that model of router.

Collecting required information

Before you start you need the following information to hand:

  • The IP subnets of your network. For the purposes of this blog these are and
  • The IP subnet that you wish to use in Azure. This needs to be different from the subnet(s) on your LAN. For the purpose of this blog this will be

Configuring Azure Networks

To configure your VPN login to your Azure tenant at and from the services area on the left click Networks near the bottom. Add a new network by clicking Create a virtual network or from the bottom toolbar clicking + New and from the options select Custom Create. Note that Quick Create will not create a valid solution as it will note create a VPN gateway.

Enter the name of the VPN network and enter a name for the affinity group that you need to create. You will place virtual machines into this affinity group so that they get an IP address valid for this network. I’m based in the UK, so I choose West Europe (i.e. Dublin) as the datacentre to use.


Click the right-hand arrow at the bottom of the screen and check Site to site VPN. You only need to add a DNS name and IP address (to an existing DNS server) on your LAN if your virtual machines need to use this DNS server to resolve on-premises resources. I will use Azure to do my name resolution, so will not enter them here.


Click the right-hand arrow at the bottom of the screen and enter a name for your LAN and your external IP address (not shown here). This needs to be a static IP address that is not NAT’ed, so in my case this will be the external IP address of the Draytek router. Also enter the address space(s) for your LAN.


Click the right-hand arrow at the bottom of the screen to go to page 4 of the wizard and select an address space that does not conflict with your LAN address spaces entered on the previous screen. In the picture below I have configured as the subnet with a /24 CIDR range. You can edit the values provided if they do not suit. For the subnets within this network, you need one or more subnets for the address space. My final aim for the Azure tenant is to host a multisite Exchange Server lab, so I will create four subnets within the address space. The first address space is going to be reserved for routing purposes back to my LAN. The routing subnet is configured by clicking the add gateway subnet button.


Click the tick mark and wait for the network to be created. Once created click the network name and then Dashboard.


You will see that the gateway is not created. To start the VPN gateway at Azure click the Create Gateway button on the lower black toolbar. Choose Static Routing and confirm the choice. In about 15 minutes time the status of the gateway will go blue and the VPN grey.


We can now move onto configuring the router on your LAN as Azure is now waiting for the connection to take place.

Configuring a Draytek Router to Connect to Azure

On the VPN page in Azure you will see the status of the connection showing the amount of data that has crossed the connection to date and the IP address that you need to connect your VPN tunnel to. Make a note of this IP address (redacted in the above picture) and also make a note of the Shared Key, this you can get from the Manged Key button on the toolbar. Copy this to your clipboard and navigate to your Draytek admin page.


Ensure that your router provides service for IPSec VPN’s and that this type of traffic is not being passed through the router to another device. This is available from VPN and Remote Access > Remote Access Control in the Draytek web admin pages.


Change to VPN and Remote Access > LAN to LAN and click an available LAN to LAN profile that is not being used. In section 1 give the profile a suitable name and enable it, disable Netbios naming packets from crossing the VPN and allow multicast if you will need it. Set the Call Direction to Dial-Out and check the Always on option if you require the connection to be up all the time. Scheduled connections are also possible.


Under Dial-Out Settings (section 2) ensure IPSec Tunnel is selected and the Server IP/Host Name for VPN matches the Gateway IP Address provided on the Azure management page. Under IKE Authentication ensure Pre-Shared Key is selected. Click the IKE Pre-Shared Key button and paste the pre-shared key from Azure.


Under IPSec Security Method select High (ESP) and ensure AES with Authentication is selected. Azure requires AES encryption. The Advanced options do not need changing as they are valid for Azure already.


Scroll down to section 5 (sections 3 and 4 do not need completing) and enter the network address space in use at Azure as the value for Remote Network IP and ensure the Remote Network Mask value is correct. This ensures that connections to this subnet are routed down this VPN tunnel. If you have multiple address spaces created at Azure then click the More button and add the rest of the Azure networks (not the individual subnets within the address space) if you added additional address spaces.


Save the VPN profile and navigate to VPN and Remote Access > Connection Management. In about 10 seconds you will see this page refresh and you should see the connection to Azure has been made.


Back on the Azure management console the VPN at the LAN side should be green and the Data In and Data Out values increasing. At the time of writing, an Azure VPN costs £1.44 per day and this does not include any network traffic across the link.


Creating Azure Virtual Machines on Your VPN

Ensure that your link is up by pinging the VPN endpoint at Azure. This will be the second IP address on the gateway subnet that was created earlier. In my example this is


Virtual machines in Azure will get an IP address from your VPN and will be directly reachable to and from your LAN if they are associated with the VPN network created when the VPN was created. To do this either create a virtual machine from the gallery option (not Quick Create) to make a new virtual machine from a template or one of your existing unused VHDs or images and set the region/affinity group to the VPN network.


Note that you cannot change the network that an existing machine is associated with – you need to delete the virtual machine (but without deleting the disks) and also delete the associated cloud service. Then you can make the VM again and choose My Disks from the gallery and select the VPN as the Region/Affinity Group/Virtual Network value.


That is it. You virtual machines will come online and be provisioned and get an IP address on your virtual network. To see the IP address click the virtual machine and view the dashboard. Note that shutting down the virtual machine will release the IP and you cannot assign static IP’s in Azure or the machine will not be reachable – all connectivity to Azure machines is via resolved names.