Most of the points in Azure and Office 365 you can administrate with their management web portals, but for some stuff and details you had to use the PowerShell or CLI, not to mention if you want to automate some processes.

Azure PowerShell documentation

Azure PowerShell is a set of cmdlets for managing Azure resources directly from the PowerShell command line. Azure PowerShell is designed to make it easy to learn and get started with, but provides powerful features for automation. Written in .NET Standard, Azure PowerShell works with PowerShell 5.1 on Windows, and PowerShell 7.x and higher on all platforms.

Azure Command-Line Interface (CLI) documentation

The Azure command-line interface (Azure CLI) is a set of commands used to create and manage Azure resources. The Azure CLI is available across Azure services and is designed to get you working quickly with Azure, with an emphasis on automation.

Choosing the right tooling for Azure and side by side Azure CLI and PowerShell commands

If you want an entirely cross-platform tooling that will work exactly the same on Mac, Linux, and Windows, use the Azure CLI. In general, the Azure CLI tends to be shorter, easier to remember commands, and it is much easier to pick up this language than PowerShell. The PowerShell commands can get quite lengthy.

Manage Microsoft 365 with PowerShell

In the following post I want to put some basic cmdlets together you could really need for your daily work.

I will update and add further cmdlets to this post consistently, so far I will start with the basics and a few user cmdlets.

Managing Azure Ressources



Get-Alias -Name *AzAccount* | Select Name,ReferencedCommand


Azure Cloud Shell – Managing Azure Ressources

Overview of Azure Cloud Shell

Azure Cloud Shell is an interactive, authenticated, browser-accessible shell for managing Azure resources. It provides the flexibility of choosing the shell experience that best suits the way you work, either Bash or PowerShell.

You can access the Cloud Shell in three ways:

Azure CLI: az Login , az account show

az login
az login -u <myUsername>

# login directly to an different tenant as the default if multiple assigned to this account.
az login -u <myUsername> -t <customerTenantId-or-Domain>

How to Change Tenants?
az account set --subscription <customerSubscriptionId>

Azure PowerShell: Get-AzSubscription

PowerShell Modules/APIs to manage Azure and Office 365

To manage Azure AD and Office 365 you can choose currently between three PowerShell modules/APIs MSOnline, Azure AD and Microsoft Graph.

Microsoft Graph PowerShell is the new one and should be used now!

The first PowerShell module to manage Azure AD was the MSOnline V1 PowerShell module with the -Msol cmdlets like Get-MSolUser

Till September 2020, Azure Active Directory PowerShell for Graph (AzureAD) was the recommended PowerShell module from Microsoft to manage Azure AD.

The Azure Active Directory PowerShell for Graph module can be downloaded and installed from the PowerShell Gallery, The gallery uses the PowerShellGet module. The PowerShellGet module requires PowerShell 3.0 or newer and requires one of the following operating systems:

Windows 10 Windows 8.1 Pro Windows 8.1 Enterprise Windows 7 SP1 Windows Server 2016 TP5 Windows Server 2012 R2 Windows Server 2008 R2 SP1

PowerShellGet also requires .NET Framework 4.5 or above. You can install .NET Framework 4.5 or above from here.

Install-Module -Name AzureAD

Azure Active Directory PowerShell for Graph: Version release history

You will also find a reference to all cmdlets for the Azure Active Directory PowerShell for Graph module under

Now as mentioned above since September 2020 the Azure AD Graph API is also deprecated.
Azure AD Graph API is now deprecated. We will continue to provide technical support and security updates but will no longer provide feature updates. Starting June 30th, 2022, we will end support for Azure AD Graph and will no longer provide technical support or security updates. Apps using Azure AD Graph after this time will no longer receive responses from the Azure AD Graph endpoint.

So therefore you should now use the new Microsoft Graph and Microsoft Graph PowerShell Module.

Install the new Microsoft Graph PowerShell Module

The modules are also available on the PowerShell Gallery.

Install-Module -Name Microsoft.Graph
Connect-MgGraph -Scopes “User.Read.All”,”Group.ReadWrite.All”

Get started with the Microsoft Graph PowerShell SDK

Overview of Microsoft Graph

Microsoft Graph is the gateway to data and intelligence in Microsoft 365. It provides a unified programmability model that you can use to access the tremendous amount of data in Microsoft 365, Windows 10, and Enterprise Mobility + Security. Use the wealth of data in Microsoft Graph to build apps for organizations and consumers that interact with millions of users.

What’s in Microsoft Graph?

Microsoft Graph exposes REST APIs and client libraries to access data on the following Microsoft cloud services:

  • Microsoft 365 services: Delve, Excel, Microsoft Bookings, Microsoft Teams, OneDrive, OneNote, Outlook/Exchange, Planner, SharePoint, Workplace Analytics.
  • Enterprise Mobility and Security services: Advanced Threat Analytics, Advanced Threat Protection, Azure Active Directory, Identity Manager, and Intune.
  • Windows 10 services: activities, devices, notifications, Universal Print (preview).
  • Dynamics 365 Business Central.

To find out more, see Major services and features in Microsoft Graph.

Conclusion about the different PowerShell Modules to manage Azure and Office 365

So as now Microsoft Graph PowerShell is the up to date module to manage Azure AD and Office 365, I will focus on these cmdlets but also list some old ones.

The Microsoft Graph module has introduced a prefix to all the Microsoft Graph cmdlets to reduce the chance of conflicts with existing modules.

So for example instead calling Get-User, you will now need to use with the Microsoft Graph module Get-MgUser.

Get started with the Microsoft Graph PowerShell SDK

Microsoft Graph REST API v1.0 reference

Login/Logout Azure AD with PowerShell

MSOnline (Microsoft Azure Active Directory Module for Windows PowerShell module)


Azure Active Directory PowerShell for Graph module



Microsoft Graph PowerShell

Connect-MgGraph -Scopes “User.Read.All”,”Group.ReadWrite.All”

Each API in the Microsoft Graph is protected by one or more permission scopes. The user logging in must consent to one of the required scopes for the APIs you plan to use

Use the Connect-MgGraph command to sign in with the required scopes

You can add additional permissions by repeating the Connect-MgGraph command with the new permission scopes.

Microsoft Graph permissions reference

Connect to all Microsoft 365 services in a single PowerShell window

When you use PowerShell to manage Microsoft 365, you can have multiple PowerShell sessions open at the same time. You might have different PowerShell windows to manage user accounts, SharePoint Online, Exchange Online, Skype for Business Online, Microsoft Teams, and the Security & Compliance center.

This scenario isn’t optimal for managing Microsoft 365, because you can’t exchange data among those windows for cross-service management. This article describes how to use a single instance of PowerShell to manage Microsoft 365 accounts, Skype for Business Online, Exchange Online, SharePoint Online, Microsoft Teams, and the Security & Compliance Center.

This article currently only contains the commands to connect to the Worldwide (+GCC) cloud. Notes provide links to articles about connecting to the other Microsoft 365 clouds.

Set-ExecutionPolicy RemoteSigned

Follow these steps to connect to all the services in a single PowerShell window when you’re using just a password for sign-in.

Login Azure AD

$credential = Get-Credential

Run this command to connect to Azure AD by using the Azure Active Directory PowerShell for Graph module.

Connect-AzureAD -Credential $credential

Connect to a specific tenant if your user is assigned to multiple tenants

Connect-AzureAD -Credential $credential -TenantId “”

change the tenant with the same user

Connect-AzureAD -TenantId “”

Or if you’re using the Microsoft Azure Active Directory Module for Windows PowerShell module, run this command.

Connect-MsolService -Credential $credential

PowerShell Core doesn’t support the Microsoft Azure Active Directory Module for Windows PowerShell module and cmdlets with Msol in their name. You must run these cmdlets from PowerShell.

Run these commands to connect to SharePoint Online. Specify the organization name for your domain. For example, for “”, the organization name value is “litwareinc”.

Connect to SharePoint Online

First install the Microsoft Online SharePoint PowerShell module if not already done.
Install-Module -Name Microsoft.Online.SharePoint.PowerShell

$orgName=”<for example, litwareinc for>”
$credential = Get-Credential
Connect-SPOService -Url https://$ -Credential $Credential

Run these commands to connect to Skype for Business Online. A warning about increasing the WSMan NetworkDelayms value will appear the first time that you connect. Ignore it.

Skype for Business Online Connector is currently part of the latest Teams PowerShell module. If you’re using the latest Teams PowerShell public release, you don’t need to install the Skype for Business Online Connector.

Connect to Skype for Business Online

Import-Module MicrosoftTeams
$credential = Get-Credential
$sfboSession = New-CsOnlineSession -Credential $credential
Import-PSSession $sfboSession

Migrating from Skype for Business Online Connector to the Teams PowerShell module

Skype for Business Online Connector connections will be rejected starting May 17, 2021. Please contact Microsoft Support for help and support for migrating to Teams PowerShell Module.

How to Migrate
Install the latest Teams PowerShell module. For steps, see Install Microsoft Teams PowerShell.

Uninstall Skype For Business Online Connector. To do this, in Control Panel, go to Programs and Features, select Skype for Business Online, Windows PowerShell Module, and then select Uninstall.

In your PowerShell scripts, change the module name that’s referenced in Import-Module from SkypeOnlineConnector or LyncOnlineConnector to MicrosoftTeams.

When using Teams PowerShell Module 2.0 or later, update your scripts that refers New-CsOnlineSession to Connect-MicrosoftTeams.

Import-PsSession is no longer required to establish a Skype for Business Online Remote PowerShell Session as that is done implicit when using Connect-MicrosoftTeams.

!!! Important !!!

If you’re using the latest Teams PowerShell public preview release, you don’t need to install the Skype for Business Online Connector!

The Skype for Business Online commands have been merged with the Teams PowerShell module since version 1.1.6.

If you’re using the Public Preview version of Teams PowerShell, we strongly recommend that you first uninstall Skype for Business Online Connector.

You can find the latest preview version at PowerShell Gallery or in PowerShell by running “Find-Module MicrosoftTeams -AllowPrerelease -AllVersions”

Install-Module -Name MicrosoftTeams -AllowPrerelease -Force

Microsoft Teams PowerShell Overview

Comparison how to connect with Skype for Business online connector vs. Teams PowerShell Module 2.0 and later

# When using the Skype for Business online connector

     # Establishing a session
     Import-Module SkypeOnlineConnector [LyncOnlineConnector]
     $credential = Get-Credential
     $SkypeSession = New-CsOnlineSession -Credential $credential
     Import-Session $SkypeSession

     # Example getting tenant details

     # Disconnecting and closing the Session 
     Get-PsSession $SkypeSession | Remove-PsSession

# When using Teams PowerShell Module 2.0 or later

     # Establishing a session
     Import-Module MicrosoftTeams
     $credential = Get-Credential
     Connect-MicrosoftTeams -Credential $credential

     # Example getting tenant details

     # Disconnecting and closing the Session  

Run these commands to connect to Teams PowerShell.

Connect to Teams

Import-Module MicrosoftTeams
$credential = Get-Credential
Connect-MicrosoftTeams -Credential $credential

# Disconnect from the Microsoft Teams environment.

To connect to Microsoft Teams clouds other than Worldwide, see Connect-MicrosoftTeams.

Sign in using MFA and modern authentication
If your account uses multi-factor authentication, use the steps in this section.

Connect-MicrosoftTeams -AccountId <UPN>

Run this command to connect to Exchange Online.

To connect to Exchange Online for Microsoft 365 clouds other than Worldwide, see Connect to Exchange Online PowerShell.

Connect to Exchange Online

If not already installed, you first need to install the Exchange Online PowerShell module.
Install-Module -Name ExchangeOnlineManagement

To force to upgrade to a new release
Install-Module -Name ExchangeOnlineManagement -Force

Import-Module ExchangeOnlineManagement
$credential = Get-Credential
Connect-ExchangeOnline -Credential $credential -ShowProgress $true

Alternatively, run these commands to connect to the Security & Compliance Center.

$acctName=”<UPN of the account, such as>”
Import-Module ExchangeOnlineManagement
Connect-IPPSSession -UserPrincipalName $acctName

# Disconnect the remote PowerShell session

Here are the commands for all the services except Security & Compliance Center in a single block when you use the Azure Active Directory PowerShell for Graph module. Specify the name of your domain host and run them all at the same time.

Connect to All services

$orgName="<for example, litwareinc for>"
$credential = Get-Credential
Connect-AzureAD -Credential $credential
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
Connect-SPOService -Url https://$ -credential $credential
Import-Module MicrosoftTeams
$sfboSession = New-CsOnlineSession -Credential $credential
Import-PSSession $sfboSession
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -Credential $credential -ShowProgress $true
Import-Module MicrosoftTeams
Connect-MicrosoftTeams -Credential $credential

User management with PowerShell

So as now Microsoft Graph PowerShell is the up to date module to manage Azure AD and Office 365, I will focus on this cmdlets but also list some old ones.

Manage Microsoft 365 user accounts, licenses, and groups with PowerShell


To display the full list of user accounts

List user accounts with errors.
Get-MsolUser -HasErrorsOnly

To retrieve the errors on user object
$errors = (get-msoluser -userprincipalname “”).Error
$errors | foreach-object {“`nService: “+ $_.ErrorDetail.Name.split(“/”)[0]; “Error Message: “+ $_.ErrorDetail.ObjectErrors.ErrorRecord.ErrorDescription}

List specific user
Get-MsolUser -UserPrincipalName | fl UserPrincipalName,ObjectId

For the list of unlicensed users
Get-MsolUser -UnlicensedUsersOnly

View accounts based on a common property
Get-MsolUser | Where {$_.UsageLocation -eq $Null}
Get-MsolUser | Where {$_.City -eq “Stuttgart”}

To see all of the properties for user accounts, use the Select cmdlet and the wildcard character (*) to display them all for a specific user account
Get-MsolUser -UserPrincipalName | Select *

Azure Active Directory PowerShell for Graph module

List specific user

Get-AzureADUser -SearchString | fl UserPrincipalName,OnPremisesSecurityIdentifier,ObjectId

$user = Get-AzureADUser -ObjectId

Change UPN
Get-AzureADUser -ObjectId <ObjectID of the User> | fl
Set-AzureADUser -ObjectId <ObjectID of the User> -UserPrincipalName John.Nokes@domain.tld

Change Displayname
Get-AzureADUser -ObjectId <ObjectID of the User> | fl
Set-AzureADUser -ObjectId <ObjectID of the User> -Displayname ‘John Nokes’

alternative instead of each time copying the ObjectID you can use a variable:

$user = Get-AzureADUser -ObjectId John.Nokes@domain.tld
$user.DisplayName = ‘John Nokes’
Set-AzureADUser -ObjectId John.Nokes@domain.tld -Displayname $user.Displayname

Check which Recipient Object (User, Group, all mail enabled objects) have assigned a specific Email Alias (Proxy)
Get-Recipient | where {$_.EmailAddresses -match “user@domain.tld”} | fL Name, RecipientType,emailaddresses

List Azure AD User SIDs by using Azure AD PowerShell module

$credential = Get-Credential
Connect-AzureAD -Credential $credential

function Convert-ObjectIdToSid
    param([String] $ObjectId)

    $d=[UInt32[]]::new(4);[Buffer]::BlockCopy([Guid]::Parse($ObjectId).ToByteArray(),0,$d,0,16);"S-1-12-1-$d".Replace(' ','-')

# Get and convert all Azure Users:
Get-AzureADUser | ForEach { [pscustomobject] @{ Name= $_.DisplayName; Sid=Convert-ObjectIdToSid($_.ObjectId)}}

#Get and convert Azure User with the UPN
Get-AzureADUser -SearchString | ForEach { [pscustomobject] @{ Name= $_.DisplayName; Sid=Convert-ObjectIdToSid($_.ObjectId)}}


Microsoft Graph PowerShell

List all users in Tenant


List specific user

Get-MgUser -Filter “displayName eq ‘Marcus Rath'”
Get-MgUser -Filter “UserPrincipalName eq ‘'”

List the user’s joined Teams

$user = Get-MgUser -Filter “UserPrincipalName eq ‘'”
$team = Get-MgUserJoinedTeam -UserId $user.ID

or limit the output of Teams with
$team = Get-MgUserJoinedTeam -UserId $user.ID -Filter “displayName eq ‘Sales and Marketing’

List Team channels

Get-MgTeamChannel -TeamId $team.Id
$channel = Get-MgTeamChannel -TeamId $team.Id -Filter “displayName eq ‘General'”

or with the comparison operator -like

Get-MgUserJoinedTeam -UserId $user.ID | Where-Object {$_.DisplayName -like “Team*”}

Changing the primary email address / Alias of an Microsoft 365 Group (Unified Group)

Get-UnifiedGroup -Identity <groupname> | fl

Set-UnifiedGroup -Identity <groupname> -PrimarySmtpAddress “teams-group@domain.tld”

Set-UnifiedGroup -Identity <groupname> -alias “teams2-group@domain.tld”

# Remove proxy/alias
Set-UnifiedGroup -Identity <groupname> -emailaddresses @{remove=”teams2-group@domain.tld”}

Overview of Microsoft 365 Groups (Unified Groups) for administrators

Skype for Business Online

Get-CsOnlineUser -Identity jdoe

Set-CsUser -Identity jdoe

Exchange Online

List all Mailboxes sorted by size

Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Select-Object DisplayName, @{Name="TotalItemSizeGB"; Expression={[math]::Round(($_.TotalItemSize.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1GB),0)}}, ItemCount | Sort-Object -Property TotalItemSizeGB -Descending

Company Settings


self-service sign-up enable/disable

The following command will allow users to perform self-service sign-up, but only if those users already have an account in Azure AD (in other words, users who would need an email-verified account to be created first cannot perform self-service sign-up)

Set-MsolCompanySettings -AllowEmailVerifiedUsers $false -AllowAdHocSubscriptions $true

Manage Teams


New-CsOnlinePSTNGateway -Fqdn -SipSignalingPort 5061 -MaxConcurrentSessions 100 -ForwardCallHistory $true -MediaBypass $true -Enabled $true

Manage Exchange Online


Get-Mailbox -Identity <UserPrincipalName> | fl

Get-Mailbox -Identity | fl ExchangeGUID,Name,Alias,UserPrincipalName,DisplayName,EmailAddresses,PrimarySmtpAddress,Identity






Management Exchange Online Hybrid Relationship


This cmdlet is available in on-premises Exchange and in the cloud-based service. Some parameters and settings may be exclusive to one environment or the other.

Use the Get-OrganizationRelationship cmdlet to retrieve settings for an organization relationship that has been created for federated sharing with other federated Exchange organizations or for hybrid deployments with Exchange Online.


This cmdlet is available in on-premises Exchange and in the cloud-based service. Some parameters and settings may be exclusive to one environment or the other.

Use the Get-IntraOrganizationConnector cmdlet to view the settings of Intra-Organization connectors.

Connect-MsolService -Credential $cred
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri -Credential $cred -Authentication Basic –AllowRedirection
Import-PSSession $session

Get-OrganizationRelationship -Identity "O365 to On-premises"

#delete with
Remove-OrganizationRelationship -Identity "O365 to On-premises"

# Gracefully disconnect from Azure Active Directory
Remove-PSSession $Session

Manage SharePoint Online

Lock and unlock sites

Get-SPOSite -Identity <SiteURL> | fl LockState
Set-SPOSite -Identity <SiteURL> -LockState Unlock

Where: SiteURL is the URL of the site that you want to lock or unlock and State is one of the following values:

  • Unlock to unlock the site and make it available to users.
  • ReadOnly to prevent users from adding, updating, or deleting content. A message will appear on the site stating that the site is under maintenance and is read-only.
  • NoAccess to prevent users from accessing the site and its content. If you’ve provided a NoAccessRedirectUrl value for your organization (below), traffic will be redirected to the URL you specified. If you haven’t set this URL, a 403 error will be displayed.

If the site was closed and made read-only through a site closure policy, the PowerShell command to unlock the site will not work.

Set-SPOTenant -NoAccessRedirectUrl ''

For more info about the LockState parameter, see Set-SPOSite. For more info about the NoAccessRedirectUrl parameter, see Set-SPOTenant.


PowerShell Comparison Operators

About Comparison Operators