Post a #MicrosoftTeams channel chat message from #PowerShell using Graph API

Implementing Microsoft Teams is 10% IT, 10% governance and the rest is a cultural change. As part of the governance process, I have long seen the need to post the first chat message in a Team channel reminding the members of some cultural etiquette scenarios as part of a governance process. Up until now, December 2018, this was not possible unless you created an Incoming Webhook which required an administrator to log in to a Team which meant it was not something you could do during an automated creation.

Good news, you can now use the Graph API to post messages to channels without the webhook. This is still part of the beta API as of December 2018 and is not intended for production, yet. Here is what you need to do

Prerequisite: you need to create an Azure AD App registration with the correct permissions

  1. Log on to https://portal.azure.com with a GA administrator
  2. Navigate to Azure Active Directory
  3. go to App registration (Preview)
  4. Click + New registration
  5. Call it PowerShelltoTeamsGraphAPI
  6. Leave Redirect URI blank
  7. Go to Authentication and under Redirect URIs choose urn:ietf:wg:oauth:2.0:oob
  8. Click Save
  9. Go to API permissions to grant the required group read and write permissions
  10. Click + Add a permission
  11. Choose Microsoft Graph, Delegated permissions and choose Group.Read.All and ReadWrite.All (remember you need to expand Group)
  12. Click Grant admin Consent from  and click Yes
  13. You now have admin consent granted for your tenant
  14. Navigate to Overview
  15. Copy the Application (client) ID
  16. we are going to use it in the next step when logging on
  17. Check out the references pictures below

You are now ready to connect to the Graph API via PowerShell. The connection code is from a more thorough blog post by my MVP colleague Alexander Holmeset. $clientId is the client ID you copied in the prerequisites

#Connect Graph, use the client ID we created earlier in the lab called PowerShelltoTeamsGraphAPI in Azure AD under app registrations
#Source: https://alexholmeset.blog/2018/10/10/getting-started-with-graph-api-and-powershell/
$clientId = "bb808f16-b6ef-44aa-8218-2520aaff461e"
$redirectUri = "urn:ietf:wg:oauth:2.0:oob"
$resourceURI = "https://graph.microsoft.com"
$authority = "https://login.microsoftonline.com/common"
$AadModule = Import-Module -Name AzureADpreview -ErrorAction Stop -PassThru
$adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
[System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
# Get token by prompting login window.
$platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Always"
$authResult = $authContext.AcquireTokenAsync($resourceURI, $ClientID, $RedirectUri, $platformParameters)
$accessToken = $authResult.result.AccessToken

#Validate that you have access by getting a list of all Office 365 Groups in your tenant
$apiUrl = 'https://graph.microsoft.com/v1.0/Groups/'
$Data = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get
($Data | select-object Value).Value

Then you need to get the group ID and Id of the channel you want to post to. In this example, I use the Microsoft Teams PowerShell module and I want to post to a Team called TMDemo in the General channel. This can, of course, be done as part of a governance creation process

Connect-MicrosoftTeams

#I assume you only have one TMDemoXX Group
$TeamGroupID = (Get-Team | Where-Object {$_.displayname -match "TMDemo"}).GroupId
$TeamChannelID = (Get-TeamChannel -GroupId $TeamGroupID | Where-Object {$_.displayname -match "general"}).Id

Now you are ready to post to the channel, you are connected without errors, we have the Team you are posting to and have chosen a channel. There is one more thing, you also need to be a member of the Team in order to post. Make sure you get added, and then remove the admin user when you are finished posting.

#connect to teams channels and post a message
$apiUrl = "https://graph.microsoft.com/beta/teams/$TeamGroupID/channels/$TeamChannelID/chatThreads"
#add your admin user as member of the team
Add-TeamUser -User $UserName -GroupId $TeamGroupID
$body = @{
"rootMessage" = @{
    "body" = @{
        "contentType" = 1;
        "content" = '<h1>Welcome to this project. All project related discussions happen in the respective channels in our Team. We look forward to working with you and remember, General channel is used for announcements, wins and off-topic discussion</h1>'
        }
      }
}
$bodyJSON = $body | ConvertTo-Json
$Data = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Post -Body $bodyJSON -ContentType 'application/json'
#remove your admin user from the team
Add-TeamUser -User $UserName -GroupId $TeamGroupID

You have now successfully posted to a channel directly from PowerShell. Congratulations! Log in to your Team an see the result. I think this is great stuff and will definitely be part of my governance processes moving forward graph1<

The best Microsoft Ignite to date

I had a blast at Microsoft Ignite 2018! Here are some reasons why I think it was the best to date:

  • The product groups were accessible and always available for feedback. If you went to the different product group booth you would find prominent members available to chat and discuss their products.
  • Less walking distance, since everything was organized in the same building. This is a great improvement over all other the Microsoft Ignite’s the previous years
  • The focus om community engagement was apparent this year with Community hours and available podcast booths and locations. Even more community members got to share their experience in breakout sessions, meetup sessions, and theater sessions. The community hours had even more people from the product groups join and you got to ask your burning questions and have a great discussion
Ignitecommunity

Microsoft Ignite 2018 group photo with the Microsoft Teams Product Group and MVP’s

This is at least my experience and I may be biased as I got to have a great time delivering three theater sessions, a meetup, guest two podcasts and spend time at the Microsoft Teams booth. But still, compared to the previous years, the vibe during this year Microsoft Ignite was great. If you are thinking of attending next year, make sure you register as soon as possible, for it is going to be awesome. You can pre-register for November 4-8, 2019, in my favorite vacation location, Orlando

Links to my session recordings and slide decks

THR2137 – OneNote Life Hacks

IgniteOLF.png

THR2138 – Stream meetings with Microsoft Teams Live Events

Igniteliveevents

THR2241 – Meetings best practices in Microsoft Teams

Ignitemeetings

Podcast: Skype for Business & Microsoft Teams MVP Roundtable

pod1.png

Podcast: Microsoft Teams news – Live Podcast Discussion

pod2

I also had the pleasure of bringing all of CloudWay AS  to Orlando this year and had great fun together with Jan Ketil Skanke and Alexander Holmeset. I think networking is a big part of conferences such as Microsoft Ignite, that is why we co-hosted Norwegian networking event at Bahama Breeze together with KPMG, Pexip and Microsoft Norway. Read about our activities here

CW1Ignite18V1

Speaking at Microsoft Ignite 2018

I am so proud to return as a speaker for the fourth time at Microsoft Ignite 2018, at my favorite vacation spot, Orlando, FL.

29542728_10155933429450622_4000566362420889272_n

I will share my experience with Microsoft Teams meeting best practices in two expo theater sessions. I will again share my passion for personal productivity using OneNote in a third expo theater session. I will team up with featured speaker, Brian Ricks, and other Teams/Skype MVP’s for ask us anything on troubleshooting Teams and Skype in my first ever meetup.

THR2138V5

Check out my Teams Live Events session

I am scheduled to be at the Microsoft Teams booth during happy hour on Monday so if you have any burning questions or want to hang out and chat, look me up. I would love to whiteboard some migration scenarios or Teams lifecycle scenarios :)

Microsoft Ignite is a huge event for networking with your peers, that is why I am happy that my company is encouraging that by being a co-host for Norsk Aften on Tuesday.

This is going to be fun! See you there :)

Microsoft Teams Direct Routing GA

Today Microsoft Teams Direct Routing was announced as General Available. This is the means for you to bring your own SIP trunk to Microsoft Teams using only a standard SBC. Today AudioCodes and Ribbon are certified SBC’s for Direct Routing and more are in the works. There are three flavors to Direct Routing

Hosted in Azure!

Yes you read correct. AudioCodes has a certified SBC that now is supported in Azure, which means you can run your Direct Routing SBC in Azure as an appliance.

DRGA6.PNG

Installed in your datacenter connected to your PBX or SIP trunk

With Direct Routing you do not need any Skype for Business or Teams components installed in your datacenter to provide voice for your Teams users. All you need is a certified SBC, a public IP address and a public certificate to connect. Read my blogpost on infrastructure requirements for setting up Direct Routing in your datacenter

DRGA2.png

Hosted by a partner

One SBC can connect to multiple Office 365 tenants making this scenario scalable. This means you can consume native Microsoft Teams services from your own tenant and have a service provider host your voice connectivity.

DRGA3

Thoughts

I think Direct Routing will make Cloud Voice mainstream and it can be combined with Calling Plans where available, which means that you can freely choose how to consume voice. Being able to install the SBC in Azure means that anyone can now host and conenct their own sip trunk to Office 365. With the ability to either get this hosted or set up with next to no on-premises infrastructure you have a solution that can be consumed by most customer types from SMB to Enterprise.

References

Microsoft Teams Direct Routing explained

Microsoft Teams Direct Routing is General Available as of June 28, 2018. This is the means for you to bring your own SIP trunk to Microsoft Teams. To be clear, this will only give your Teams users PSTN connectivity, your Skype for Business Online users still needs to use CCE or Skype for Business Server hybrid to get PSTN connectivity.

The goal of this article is to explain the basic around Direct Routing from an infrastructure point of view.

Licenses

  • You need a Phone System License  per user, which is part of Office 365/Microsoft 365 E5 or add-on for Office 365/Microsoft 365 E3
    • Phone System is not available as add-on for Office 365 Business Premium or Microsoft 365 Business
  • To get a phone number in Teams meetings, you need the Audioconferencing license per user, which is part of E5 and can added as add-on for E3 and Business SKU’s

Firewall ports and protocols

  • To connect a sip trunk to Microsoft Teams, a SIP proxy is used.
    • From your SBC to the SIP proxy you need always to use port 5061
      • From SIP proxy to your SBC you can choose any port between 1024 – 65 6536
      • I prefer to use 5061 since it is the same port as SIP proxy and it may be simpler in the long run
      • Traffic needs to be open both ways
    • You can limit the connectivity to the pstnhub.microsoft.com addresses specified below and the IP addresses they resolve to
      • you should always use sip.pstnhub.microsoft.com as primary as it is a Global FQDN
      • sip-all.pstnhub.microsoft.com is mentioned in the documentation and can be a possible source DNS name
  • Media range is UDP between the ports 49 152 – 53 247

DirectRouting4

SBC requirements

TeamsDirectRoutingV3

 

 

Media Bypass internally

  • The advantage of media bypass in a Direct Routing scenario where server is in the cloud is that media stays local and the media path is more optimal
  • Media bypass is supported by AudioCodes and Ribbon
    • needs to be configured specifically on SBC and enabled in Office 365
    • both vendors support ICE light which is used for connectivity checks when finding optimal media path
  • The clients need to be able to resolve and connect the public IP of the SBC
    • traffic needs to be open both ways, same media ports are used
    • requires hair pinning on NAT device

DirectRoutingMB1.PNG

Media Bypass externally

  • Media bypass is possible from clients logged on outside the corporate network
  • The client needs to resolve the SBC FQDN and connect to the IP
    • This results in allowing any IP as source ip on the media port range on the SBC
    • Since only TLS connections are allowed, I think this is something that can be considered
  • If the client cannot connect to the IP it will relay media via the SIP Proxy

DirectRoutingMBext1

Migrating to Direct Routing

Since CCE or Skype for Business Server cannot provide voice for Microsoft Teams, the only viable migration path is to introduce a SBC or configure the current SBC to connect to Microsoft Teams. From there you can start moving users by routing specific numbers and number series over to the new SIP trunk.

If you use direct SIP trunk with your Skype for Business Server today, then you can test Direct Routing by implementing a SBC and connect it to Microsoft Teams. Then provide a SIP trunk from Skype for Business using the inter trunk routing feature in Skype for Business Server, which allows you to move some test numbers to the SBC and Microsoft Teams. When you are ready to move to Microsoft Teams, you can switch the PSTN SIP trunk to go directly to the SBC.

pathtothecloud

Summary

When you have the correct approach from an infrastructure point of view, then you are ready to create PSTN usages and voice policies in Office 365. After that, users need to be enabled for enterprise voice and get assigned a number. Then you are ready to succeed with Microsoft Teams Direct Routing

References

 

Talking Teams automation and OneNote productivity at the Microsoft Campus this August at TechMentor!

Wow! I am going to speak at a conference at the Microsoft Headquarters in Redmond! This is bucket list check for sure. I am soo looking forward to this and hope the attendees will learn a thing or two about Microsoft Teams and get inspired to do more with OneNote in my two sessions.

SPECIAL OFFER: As a speaker, I can extend $500 savings on the 5-day package. Register here: http://bit.ly/RDSPK09_reg

How to Administer Microsoft Teams Like a Boss

This session will help you learn how to take control of Microsoft Teams using PowerShell. You’ll be able to find activities across all workloads to create PowerBI reports and use the information to decommission, archive, or expire inactive teams.

You will learn:

  • How to administer Microsoft Teams using PowerShell
  • Advanced activity reporting on usage using PowerShell and PowerBI
  • How to use advanced activity reporting to decommission, archive or expire Teams

OneNote LifeHack: 5 Steps for Succeeding with Personal Productivity

So you’re using OneNote as your primary note taking tool? Without any structure, you might lose track of all your notes. This session will help you learn how to get structured using OneNote to dump all your thoughts, ideas, e-mails and notes that are either actionable or something you want to find later. You’ll learn five steps to get started with a robust framework from using the sections correctly, take notes with your mobile device, use Microsoft Flow to send e-mail to OneNote from any device, and the Pomodoro Technique to prioritize and induce flow in a busy workday. The magic is to collect all information in one section regardless of the platform.

You will learn:

  • A framework for productivity
  • How to use the GTD methodology and a practical context with OneNote
  • How to use the Pomodoro Technique

Amplify your knowledge at TechMentor Redmond — bring the issues that keep you up at night and prepare to leave this event with the answers, guidance and training you need.  Register now: http://bit.ly/RDSPK09_reg 

Slides and demo oneliners from NIC2018 now online

At Nordic Infrastructure Conference 2018 in Oslo, I had the honor of talking about Microsoft Teams and OneNote in two packed sessions. I got some awesome feedback after my sessions and heard that people learned something. That’s the reason I do these talks and want to continue to speak at conferences like this. You can download all slides from the conference via GitHub, which I realize is a super way to share content after a conference.

Download my slides and PowerShell oneliners from my Control Microsoft Teams like a Boss session

TimelapsStaleHansenV3

Download my slides from my OneNote LifeHack session

DVBLk0wWAAE5NJS

My company, CloudWay had a booth at NIC and we had a blast talking secure productivity and give away thousands of mobility swag :)

DSC_0101

How I create Microsoft Teams in PowerShell, January 2018

This is how I choose to create Microsoft Teams using PowerShell in the period of January 2018 as demoed in my NICconf session. This will probably change in the future so I need to specify the time this actually worked for me :)

  • I create the Office 365 Group in Exchange because then I can specify the email address and I also like to remove it from global addressbook since it is primarily used for Microsoft Teams
  • Then I Teams enable the group and typically it is created for projects so I create typical channels I want to use in the project, typically it is an Office 365 migration and deployment projects
  • Typically I leave it up to the group owners to add the members themselves in Microsoft Teams, but I use Teams PowerShell to add the owners and optionally members, because it is simpler to do it using Teams
  • The Microsoft Teams PowerShell module is based on Microsoft Graph and everything is in the context of your admin account, so in order to administer the Teams, you need to be an owner of those Teams
  • Be aware of that it can take up to 24 hours until members and channels are added to the Microsoft Teams because this is Microsoft Graph and the SLA is 24 hours to sync members over from Azure AD. Typically this should happen within 15 minutes
    • This is how it is as of January 2018
#Create the Office 365 Group
New-UnifiedGroup –DisplayName NICDemo96 –Alias NICDemo96 –EmailAddresses "NICDemo96@M365x963508.onmicrosoft.com" -owner GA-sha256@M365x963508.onmicrosoft.com -RequireSenderAuthenticationEnabled $False -Verbose
#This is optional, but may be a good practice initially since Office 365 Groups may clutter your Global Addressbook
Set-UnifiedGroup –Identity NICDemo96 –HiddenFromAddressListsEnabled $true
#Create the Team, provide the GUID object ID to specify the Group
$group = New-Team -Group (Get-UnifiedGroup NICDemo96).ExternalDirectoryObjectId -Verbose

#Check your Teams, will only list teams you are a member of
Get-Team

#Add Channels to the Team
New-TeamChannel -GroupId $group.GroupId -DisplayName "1 Adoption" -Verbose
New-TeamChannel -GroupId $group.GroupId -DisplayName "2 Deployment" -Verbose
New-TeamChannel -GroupId $group.GroupId -DisplayName "3 Operations" -Verbose
New-TeamChannel -GroupId $group.GroupId -DisplayName "4 Change Management" -Verbose
Set-TeamFunSettings -GroupId $group.GroupId -AllowCustomMemes true -Verbose

#add owners and members, easier to do with Teams cmdlet
$Owners = "PradeepG@M365x963508.onmicrosoft.com","PattiF@M365x963508.onmicrosoft.com","LidiaH@M365x963508.onmicrosoft.com","MiriamG@M365x963508.onmicrosoft.com"
$Users = "IrvinS@M365x963508.onmicrosoft.com","JohannaL@M365x963508.onmicrosoft.com","DebraB@M365x963508.onmicrosoft.com"
ForEach ($Owner in $Owners){Add-TeamUser -GroupId $group.GroupId -User $Owner -Role Owner}
ForEach ($User in $Users){Add-TeamUser -GroupId $group.GroupId -User $User -Role Member -Verbose}

#Check that members are added, know that it could take up to 24 hours until they are actually added to Microsoft Teams
Get-TeamUser -GroupId $group.GroupId
Get-UnifiedGroupLinks NICDemo96 -LinkType owner
Get-UnifiedGroupLinks NICDemo96 -LinkType member

If you want an updated approach, you should check out the Book I am co-authoring that is update weekly by MVP Tony Redmond, to match the ever-changing Microsoft Cloud. The book is called Office 365 for IT-Pros and comes highly recommended.

Share a single document with external user in Microsoft Teams

Guest Access in Microsoft Teams is a great way to collaborate with external Office 365 users in chat, files and existing tabs. Sometimes you may want to collaborate on a single document with an external user without giving them access to your entire team. Turns out, this is disabled by default.

You need to enable it via SharePoint PowerShell, here is how

  • Connect to SharePoint Online via PowerShell
  • list all site collections for your Office 365 Groups and Teams
    • Get-sposite -template GROUP#0 -includepersonalsite:$false
  • Copy the URL you want to change
  • Run the following command to make the change
    • Set-SPOSite -Identity https://tenantname.sharepoint.com/sites/NewTeam -SharingCapability ExternalUserAndGuestSharing
    • The new sharing capability is called ExternalUserAndGuestSharing
      • External user sharing (share by email) and guest link sharing are both enabled
    • The default value is ExistingExternalUserSharingOnly
      • Allow sharing only with the external users that already exist in your organization’s directory

Now you are able to in to a document, click the sharing button, choose specific users and invite those you want to collaborate with on this specific document. It is important that you choose the option “only the people you specify”, then and only then will they be able to work with the document in their desktop client

 

 

 

 

 

References:

 

Microsoft Teams Preview and Office 365 Groups member mismatch and how to fix it

Office 365 Groups are at the core for next generation Office 365 services such as Planner, Microsoft Teams and Modern SharePoint Teamsites. At the time of writing (Teams preview before March 2017) I have discovered the following regarding Office 365 Groups and membership especially in an active Microsoft Teams environment, where you are adding new members directly in the Teams client.

The Short story

Microsoft Teams in preview (before march 2017) did not add new members to the Office 365 Groups in Exchange, only to the corresponding  Azure AD Group. The Azure AD Group is used to give access to SharePoint documents and adding a new Teams member gives access to the SharePoint Site. This would result in mismatch in member-count in these two groups that can be confusing for users when navigating around the different Office 365 Groups interfaces

The Long story, understanding the different groups

Creating Office 365 Groups

  • When creating an Office 365 Group a corresponding Azure AD Group also gets created
    • The Azure AD Group is used for Group write back with Azure AD Connect and permissions in SharePoint Teamsites
      • The Group write back option is only necessary if you have a hybrid Exchange environment and users hosted on-premises that needs to be able to resolve the distribution email address and its members
      • It may also be necessary for Skype for Business hybrid environments in order to be able to add the Office 365 Groups as group in the Skype contactlist
    • If you crate the Office 365 Group in GUI from Outlook, members gets added to that Azure AD Group
    • If you create the Office 365 Group using PowerShell with New-UnifiedGroup (this still applies post March 2017) and and use the -members option, members will not get added to the Azure AD Group and you get a mismatch in member count
      • New-UnifiedGroup -Members
      • Only the Office 365 Group Owner will get added to the Azure AD Group as member and this is an issue for the Group Write Back with AADC
      • A corresponding SharePoint TeamSite gets created with a member of the group with a SharePoint license logs on to either Office 365 Groups or creates a Microsoft Teams team
    • If you create the group in PowerShell and with New-UnifiedGroup without adding members and add the members using Add-UnifiedGroupLinks, then members will get added to the corresponding Azure AD Group
Recommended method to create Office 365 Groups via PowerShell

Make sure you are logged in to Exchange Online PowerShell before you start creating the group

$Owner = "stale@msunified.net"
$Users = "julia@msunified.net","Skype.buddy@msunified.net"
$alias = "MyNewOffice365Group"
New-UnifiedGroup –DisplayName $alias –Alias $alias –EmailAddresses "$alias@msunified.net" -owner $Owner -Verbose
#This is optional, but may be a good practice initally since Office 365 Groups may clutter your Global Addressbook
Set-UnifiedGroup –Identity $alias –HiddenFromAddressListsEnabled $true
#Add the member to the group
Add-UnifiedGroupLinks $alias -LinkType member -Links $users
#Validate that the members where added ok
Get-UnifiedGroupLinks $alias -LinkType member
#If you want to validate that the AD group is updated ok, run the script below without $alias=$null

Adding members to existing Office 365 Groups

  • Adding members using the Exchange Online cmdlet Add-UnifiedGroupLinks results in users getting added to both the Office 365 Group and Azure AD Group, all is good
    • If this is also a Microsoft Teams enabled group then the members will get added to the team as well within 24 hours (or so)
  • Adding members using the web UI as a user results in users getting added to both the Office 365 Group and Azure AD Group, all is good
  • Adding members from the SharePoint Teamsite UI resulted (before March 2017) in users only getting added to the Azure AD Group and you have a mismatch of user count between Azure AD and Office 365
  • Adding users from the Microsoft Teams client (before March 2017) would result in users only getting added to the Azure AD Group that gives full write access to all the corresponding SharePont Teamsite documents
    • This resulted in a mismatch between Azure AD Group and Office 365 Group and if users are expect to see the group under Groups in Outlook they will not
    • You would also get a mismatch in the memberlist in Microsoft Teams and Office 365 Groups on the web
      • if the user tried to access the Exchange components of the group they will get added to the memberlist, but not until they actively add the group or go via SharePoint Teamsite to the groupconversation button on the top right corner

Consequences

  • If you are not a member of the Office 365 Group, you are not a part of the distribution group and you will not get see the Group in either Outlook or Outlook Web App
  • If you are not added to the Azure AD Group you will not be part of the group that gets synced back to Active Directory and part of the on-premises distribution group for users hosted on Exchange Server
  • If you are not part of the Azure AD Group you will not be visible in the Graph API as there is not way to resolve member from an Office 365 Group via the API, only members from the corresponding Azure AD Group (at the time of writing, may change in the future)

Workarounds

  • Add the member in the web UI for Groups then it will get added to the Exchange part and Azure AD part of the Office 365 Group
  • Detect and remedy the different user memberships using PowerShell by detecting and adding the missing users to either Office 365 Groups or Azure AD Group

How to detect mismatch in member-count in Office 365 Groups and Azure AD Group

Below is a simple example on how to list all the groups that have a member-count mismatch between Office 365 Groups and Azure AD Groups. It is always the Azure AD group that has the most and correct set of members so that is why we add those members to the Exchange part of the Office 365 Group.

Before you run the example you need to install the latest MSOnline PowerShell V1 module and be logged in to Exchange Online PowerShell module

Find all groups with mismatch in member-count
$alias=$null
#find groups that have mismatching member-count in Office 365 groups and Azure AD groups
$Groups = @()
#Get all Office 365 Groups
$UnifiedGroup = get-unifiedgroup $alias
    ForEach ($Group in $UnifiedGroup){
        #Get the members of the group
        $UnifiedGroupLink=Get-UnifiedGroupLinks -Identity $Group.name -LinkType member | Select-Object -ExpandProperty PrimarySmtpAddress
        #If there are members in the group, check the corresponding Azure AD Group and find the members. Add the result in custom Powershell object
        if (($UnifiedGroupLink).count -ne 0){
            $AADGroup= Get-MsolGroup -GroupType DistributionList -All | Where-Object {$_.Emailaddress -eq $Group.PrimarySmtpAddress}
            $TempGroups = @()
            $TempGroups = New-Object PSObject -Property @{
                Emailaddress=$Group.PrimarySmtpAddress
                O365Members= $UnifiedGroupLink
                O365membercount= ($UnifiedGroupLink).count
                AADGUID=($AADGroup).ObjectId
                AADmembers=Get-MsolGroupMember -GroupObjectId ($AADGroup).ObjectId | Select-Object -ExpandProperty EmailAddress
                AADmembercount=(Get-MsolGroupMember -GroupObjectId ($AADGroup).ObjectId | Select-Object -ExpandProperty EmailAddress).count
            }
            #If there is a mismatch in the membercount, add the group to the final output variable and write the group to the console
            if($TempGroups.O365membercount -ne $TempGroups.AADmembercount){$Groups += $TempGroups; $TempGroups}
            $TempGroups
        }
}
#list all groups with mismatch
$Groups
#count the number of groups with a mismatch
Write-Host "Number of groups mismatching groups"($Groups).count
List all the members not present in the Office 365 Group
#Find all members that are present i the Azure AD group and needs to be added to the Office 365 Group
foreach ($CurrentGroup in $Groups){
    write-host
    write-host "Checking Group"$CurrentGroup.Emailaddress
    $NewMembers = $CurrentGroup.AADmembers | Where {$CurrentGroup.O365Members -NotContains $_} # Shows what items in $CurrentGroup.O365Members are missing in $CurrentGroup.AADmembers
    $NewMembers

}
Add the missing members to the Office 365 Group
#Add the users from the Azure AD group to the Office 365 group, the users added will not get a welcome mail.
foreach ($CurrentGroup in $Groups){
    write-host
    write-host "Checking Group"$CurrentGroup.Emailaddress
    $NewMembers = $CurrentGroup.AADmembers | Where {$CurrentGroup.O365Members -NotContains $_} # Shows what items in $CurrentGroup.O365Members are missing in $CurrentGroup.AADmembers
    Add-UnifiedGroupLinks $CurrentGroup.emailaddress -LinkType member -Links $NewMembers -Verbose
    Get-UnifiedGroupLinks $CurrentGroup.emailaddress -LinkType member

}