Category Archives: Uncategorized

Recipient “xxxxx” couldn’t be read from domain controller “xxxxx”. This may be due to replication delays. Switching out of Forest mode should allow this operation to complete successfully.

I got the following error when trying to execute actions against Exchange online using the MSOnline module. Specifically when trying to call Set-UserPhoto. The production site we ran this against uses ADSync so I assumed it was something to do with this, as my testing worked perfectly in my demo environments. We searched google for ages and couldn't figure it out.

After about 2 hours, this had magically fixed itself and the script has run fine ever since. Unsure what happened, but try waiting for a while to see if it resolves. ADSync wasn't new to the organisation so it wasn't as if data hadn't been synced. 

Recipient "xxxxx" couldn't be read from domain controller "xxxxx". This 
may be due to replication delays. Switching out of Forest mode should allow this operation to complete successfully.

Set SharePoint Online user profile mobile number from Azure Active Directory, PowerShell

PowerShell to get values from Azure AD and set them in SharePoint user profiles. Here I am getting all users that are licensed and setting their mobile numbers. This has been run in a production environment and works well. 

Import-Module MSOnline

# add SharePoint CSOM libraries
Import-Module 'C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll'
Import-Module 'C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'
Import-Module 'C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.UserProfiles.dll'

# Defaults
$spoAdminUrl = ""
$overwriteExistingSPOUPAValue = "True"

# Get credentials of account that is AzureAD Admin and SharePoint Online Admin
$userName = "ADMINEMAIL"
$password = ConvertTo-SecureString "PASSWORD" -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $password

Try {
    # Connect to AzureAD
    Connect-MsolService -Credential $credential

    # Get credentials for SharePointOnline
    $spoCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credential.GetNetworkCredential().Username, (ConvertTo-SecureString $credential.GetNetworkCredential().Password -AsPlainText -Force))
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($spoAdminUrl)
    $ctx.Credentials = $spoCredentials
    $spoPeopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($ctx)

    # Get all AzureAD Users
    $AzureADUsers = Get-MsolUser | Where-Object { $_.isLicensed -eq "TRUE" }
    ForEach($AzureADUser in $AzureADUsers){ 
        $mobilePhone = $AzureADUser.MobilePhone
        $targetUPN = $AzureADUser.UserPrincipalName.ToString()
        $targetSPOUserAccount = ("i:0#.f|membership|" + $targetUPN)

        # Check to see if the AzureAD User has a MobilePhone specified
        if (!([string]::IsNullOrEmpty($mobilePhone))) {
            $targetspoUserAccount = ("i:0#.f|membership|" + $AzureADUser.UserPrincipalName.ToString())
            $spoPeopleManager.SetSingleValueProfileProperty($targetspoUserAccount, "CellPhone", $mobilePhone)
            Try {
                Write-Output "User: $targetUPN has had their mobile number set to: $mobilePhone"
            Catch {
                Write-Output "User: $targetUPN with mobile: $mobilePhone, failed to be set, see exception below"
                Write-Output $_.Exception.Message
        else {
            # AzureAD User MobilePhone is empty, nothing to do here
            Write-Output "AzureAD MobilePhone Property is Null or Empty for $targetUPN)"
Catch {
    Write-Output $_.Exception.Message


SharePoint Online, PowerShell, Get all sites in a site collection and document libraries/lists

Ever wanted a PowerShell script to loop through all of your site collection's webs and then grab all of the document libraries and lists? Try this script out. Big thanks to this article, I used this code but altered it to use one site collection, write to the file at the very end (was running too fast and getting errors due to the file being locked), have an exclusion list and other bits n pieces. Code has been tested against a real environment.

Make sure you install the SharePoint Online Management Shell and the SharePoint Online Client Components SDK.

Here is a screenshot of the output. Has item counts for each library. Outputs file in same folder as your .ps1 script.

function connectToO365{ 
    $adminUrl = ""
    $userName = "ADMIN"
    $password = ConvertTo-SecureString "PASSWORD" -AsPlainText -Force
    Import-Module 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll'
    $credentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $password
    $SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $password)
        Connect-SPOService -Url $adminUrl -Credential $credentials
        write-host "Info: Connected succesfully to Office 365" -foregroundcolor green
        write-host "Error: Could not connect to Office 365" -foregroundcolor red
        Break connectToO365
    #create HTML file
    $filePath = create-outputfile

    #add start HTML information
    $global:textToWrite += "
    <h1>Site structure</h1>
    <table border='0' style='font-family: Calibri, sans-serif; padding: 5px;'>
            <th style='background-color:#454545; color:white'>URL</th>
            <th style='background-color:#454545; color:white'>Type</th>
            <th style='background-color:#454545; color:white'>Template</th>
            <th style='background-color:#454545; color:white'>Item Count</th>
    $global:textToWrite += "<tr style='background-color:#95B9C7'><td>$($url)</td><td>Site Collection</td><td></td><td></td></tr>"
    write-host "Info: Found $($url)" -foregroundcolor green
    $AllWebs = Get-SPOWebs($url)

    $global:textToWrite += "

    #finally, write everything to file
    add-content -value $textToWrite -path $filePath
function create-outputfile(){ 
    $date = get-date -format dMMyyyyhhmm
    $filePath = "$($PSScriptRoot)\Output$($date).html"
    if (!(Test-Path -path $filePath)){
        #create file
        New-Item $filePath -type file | out-null 
        write-host “File created: $($filePath)” -foregroundcolor green
        write-host "Output file already exists, wait 1 minute" -foregroundcolor yellow
        Break create-outputfile
    return $filePath
function Get-SPOWebs($url){ 
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($url)
    $context.Credentials = $SPOcredentials
    $web = $context.Web
        foreach($list in $web.lists){
            if ($excludeLists -notcontains $list.Title)
                write-host "List included " $list.Title -foregroundcolor green
                $global:textToWrite += "<tr><td><span style='margin-left:$($pixelslist)px'>$($list.title)</td><td></td><td></td><td>$($list.itemcount)</td></tr>"
                write-host "List excluded " $list.Title -foregroundcolor blue
        $pixelsweb = $pixelsweb + 15
        $pixelslist = $pixelslist + 15
        foreach($web in $web.Webs) {
            $global:textToWrite += "<tr style='background-color:#999999'><td><span style='margin-left:$($pixelsweb)px'>$($web.url)</td><td>Web</td><td>$($web.webtemplate)</td><td></td></tr>"
            write-host "Info: Found $($web.url)" -foregroundcolor green
        write-host "Could not find web" -foregroundcolor red

write-host "Kicking Off" -foregroundcolor green

$excludeLists = @("Master Page Gallery",
                "User Information List",
                "Theme Gallery",
                "Style Library",
                "Solution Gallery",
                "Reusable Content",
                "Reporting Templates",
                "Reporting Metadata",
                "Long Running Operation Status",
                "List Template Gallery",
                "Content and Structure Reports",
                "Cache Profiles",
                "Workflow History",
                "Web Part Gallery",
                "Form Templates",
                "Workflow Tasks",
                "Suggested Content Browser Locations",
                "Site Template Gallery",
                "Variation Labels",
                "Content type publishing error log",
                "Converted Forms"

# create variable to write to, later add to file
$textToWrite = ''

#go do all the things

Write-Host "Completed!" -foregroundcolor Yellow


Copy new Email and Details From Outlook 365 to SharePoint Online Document Library, Logic Apps: Mail Enable Office 365 SharePoint Online

Parent Post – Requirements and InformationCopy new Email and Details From Outlook 365 to SharePoint Online Document Library, Microsoft Flow and Logic Apps: Mail Enable Office 365 SharePoint Online

Related Post – Microsoft FlowCopy new Email and Details From Outlook 365 to SharePoint Online Document Library, Microsoft Flow: Mail Enable Office 365 SharePoint Online

How to create a Logic App to pass an email from Outlook 365 to a SharePoint Online Document Library

  1. Go to your SharePoint Online site
  2. Create a document library to receive the emails
  3. Go to and login as the account you use to manage Azure
  4. Click New + at the top left
  5. Type in "Logic App", click "Logic App" in the Results
  6. Click "Create", enter the details for your Logic App
  7. Click Create
  8. Wait till the deployment is completed
  9. Navigate to your Logic App – you can do this by finding it under "All Resources" or clicking the notification message once deployment is completed
  10. Click on "Blank Logic App" under Templates
  11. Click "Office 365 Outlook" under connectors
  12. Click "Office 365 Outlook (When a new email arrives)"
  13. Click Sign in, log in with the email account you will be receiving emails to
  14. I've left most stuff as default, feel free to add any extra required filters. For the frequency, every time the "check for items" is run, you will be charged money. Doing it once an hour works out pretty cheap. Check out for details on calculating costs. I have left 3 minutes for development. MAKE SURE you set "Include Attachments" to yes, or the attachments part will error
  15. Click "+ New step" and "Add an action"
  16. Type in "Content Conversion" and click on "Content Converstion – Html to text" – NOTE: we are adding this step as generally emails are in HTML and this shows as HTML markup when you add the Body of the email into a .txt file in SharePoint. Converting to plain text means we can add just the text and not HTML markup from the Body
  17. In the "Content" field, enter "Body" by double clicking the value "Body" under "When a new email arrives -> Body" as seen below
  18. Click "+ New step" and "Add an action"
  19. Search for SharePoint and click "SharePoint – Create file"
  20. Sign into SharePoint with the account that you will use to upload the emails. Don't forget about accounts with expiring passwords, you will need to come update the app when the password expires
  21. Enter the Site Address for your site collection or subsite, then select the Folder Path as your document library
  22. For the File Name we will enter the From field "_" and the utcNow() function. This will make the file name easy to identify by who it is from but also unique based on the utc date and time. You will find all of the email fields under "Dynamic content" and functions such as utcNow() under "Expression". Scroll down to "Date and time" section, double click on utcNow() which will enter it into the expression field, then click OK
  23. Ensure you type in ".txt" at the end of the file name. The type of file is not decided for you and .docx does not work (throws an error that it can't open the document)
  24. For the "File Content" field you can enter a mixture of dynamic and static content. I have entered a number of the email fields due to the fact that I can't assign these to metadata. Note that "Dynamic content" pop up box groups available information by the action it comes from, e.g. below we have "Html to text" and "When a new email arrives". You'll also notice there is a "See more" button which will show more hidden fields. You can also just search dynamic content and it will filter the list so you can quickly find values
  25. Below you can see what I have chosen for the File Content. Notice that I have used "The plan text content." from the "Html to text" group instead of the Body field
  26. Now we need to add any attachments from the email. Click "New Step" -> "Add an Action"
  27. Search for SharePoint and click "SharePoint – Create file". This will automatically log you into the same account used earlier for the first SharePoint step
  28. Enter the site URL and the document library. Under file name, click "Name (Attachment name)"
  29. This will convert your create file action into an "For each" action as it will need to loop through each attachment
  30. Let's make the "File Name" more useful, add the From field, "_ATT_" (to signify it's an attachment), utcNow() and Name field. When the item is added to the document library it should now look similar to the main email and group better, especially if you set your default view to sort by created date descending and then by File Name, you will be able to tell quickly that the email has attachments associated with it
  31. For the "File Content" field, enter "Content (Attachment content)"
  32. Your final attachment loop should look like the above
  33. Save your Logic App, you're now ready to test it!
  34. Click Run to start watching for emails (it will check on your trigger time set at the start, mine is 3 minutes)
  35. Create an email and add a couple of attachments. Send this to the email address you setup for the email trigger to watch
  36. It will take a few moments for the email to get picked up.
  37. Once it has successfully run, I can see my email plus two attachments in my document library
  38. If we open and view the txt file

ContentByQuery not working with OrderBy

I had some issues where I put a content by query web part in a page and when I added the OrderBy clause, it just stopped showing anything with no errors. I ended up putting the whole query on one line with no spaces and it started working. Not that it worked with spaces and line breaks as a normal where query, but only stopped working when I added the orderby. Also if your data isn't showing, check the data mapping view fields :).  


<Publishing:ContentByQueryWebPart runat="server" 
            	        Title="Executive Team Update"
				        ItemXslLink="{{SITE_COLLECTION_URL}}/Style Library/site/stylesheets/itemstyle.xsl"
                        QueryOverride="<OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy><Where><Eq><FieldRef Name='ContentType' /><Value Type='Computed'>Executive Team Update Page</Value></Eq></Where>" />


Creating an administrator token in Yammer

Update: October 2017, this is all still relevant! Tested myself this month on a project.

Create an Admin access token

  1. Sign into Yammer as Yammer Admin via
  2. Go to and register a new app.

Register a New App – Required Fields:


Application Name:

Token Requestor App


Organization name

Support e-mail:

An email address, which users of your app can contact for support.


Your organization’s website.

Redirect URL:


  1. Copy your Client ID, Redirect URI from the Application Information page.

  1. Paste this url into your browser, where client_id, redirect uri are the values obtained from step 4 above (replace including the brackets):[:client_id]&redirect_uri=[:redirect_uri]

  1. Copy the “code=” value from the URL created.
  2. Paste this url into your browser, where client_id, client secret are obtained in step 4 above. Code is the code from step 6 (replace including the brackets).[:client_id]&client_secret=[:client_secret]&code=[:code]

  1. Copy the “token:” value from the resulting JSON. Store it e.g. in Notepad.

You have your admin token! 

Thanks to Roland Oldengarm for putting together these instructions: