Office365 powershell

If you manage a Microsoft 365 tenancy then you have the choice to use the wide range of Admin centres available to you or Powershell to make changes and perform tasks. In some cases, the information you may be after can be scattered across different admin centres or changes needed to perform a certain task are made in more than one admin centre. For example, to view mailbox details, you need to use the Exchange admin centre, to audit mailbox activities you will need the security and compliance centre and to view mailbox statistics you will need the Microsoft admin centre. By using Powershell you can view all of this information and make changes all in one place and even have the ability to easily extract data from your tenancy to allow for reporting. PowerShell is by far the best tool to use to manage, report, audit, and analyze your Microsoft 365 Environment.   In this article, I’ll show you a list of the most useful Office365 PowerShell cmdlets for system administrators.

Before you start let’s Connect to your Office 365 instance with PowerShell

First, we need to install the Office 365 module for Windows PowerShell and connect it to the Office 365 instance. Take the following steps:

1. Open Powershell – Open the Start menu (Press Win on the keyboard). Start typing powershell then click Windows PowerShell in the search results or just press Enter to run it.

2. Import the Online Services PowerShell module for Microsoft Azure Active Directory and Office 365:

Install-Module -Name AzureAD
Install-Module -Name MSOnline

3. Enter your Office 365 admin credentials:

$Cred = Get-Credential

4. Create a remote PowerShell session:

$O365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Cred -Authentication Basic -AllowRedirection

5. Import the session commands into the local Windows PowerShell session:

Import-PSSession $O365

6. Connect to all Office 365 services:

Connect-MsolService –Credential $O365

Once we have imported the modules for Windows PowerShell, we are ready to manage our Office 365 instance.

List of Useful Office365 Powershell Commands

Getting a list of available Office365 PowerShell cmdlets

To get a list of all available Office365 PowerShell commands, we need to run the Get-Command cmdlet:

Get-Command -module MSOnline

We can also get the list of cmdlets for Azure Active Directory:

Get-Command -module AzureAD

Getting a list of all Office 365 users with PowerShell

If you need to provide a list of Office 365 users and licenses, use the Get-MsolUser cmdlet. It’ll retrieve all users with a valid license in the Office 365 tenant, along with the DisplayName, City, Department and ObjectID parameters.

Get-MsolUser | Select DisplayName, City, Department, ObjectID

To see the number of account licenses, you need to run the following cmdlet:

Get-MsolAccountSku

To list the available services, run the following script:

Get-MsolAccountSku | select -ExpandProperty ServiceStatus

Creating a new user in Office 365 with PowerShell

To create a new user, we use the New-MsolUser command:

New-MsolUser -UserPrincipalName [email protected] -DisplayName "Johnathan Brown"  -FirstName “Johnathan” -LastName “Brown”

The system will output the user’s password and license status data.

Removing a user from all SharePoint sites with PowerShell

To remove a user from all SharePoint sites at once, we use the following command:

Get-SPOSite | ForEach {Remove-SPOUser -Site $_.Url -LoginName " [email protected]"}

Changing a password in Office 365 with PowerShell

If you need to change the password for an account, use the Set-MsolUserPassword cmdlet. You can either specify a new password as in the example below or omit the -NewPassword parameter to have the system automatically generate a random password.

Set-MsolUserPassword -UserPrincipalName [email protected] -NewPassword P@SSw0rd!

Managing group membership in Office 365 with PowerShell

We can also manage Office 365 groups using PowerShell cmdlets. To retrieve a list of all groups in Office 365, simply use the command Get-MsolGroup. To add users to a group, use the Add-MsolGroupMember command:

Add-MsolGroupMember -GroupObjectId 6c64d8e5-a43f-4a2b-c5ca-873bebc08dda -GroupMemberObjectId a56cae92-a8b9-4fd0-acfc-6773a5c1c767 -GroupMembertype user

GroupObjectId is the hexadecimal ID of the group, which you can get from the Get-MsolGroup command. GroupMemberObejctId is the user object ID, which you can find by running this command:

Get-MsolUser | Select ObjectID.

To remove a user from a group, use the Remove-MsoGroupMember cmdlet.

Creating a SharePoint site collection with PowerShell

We can also create a SharePoint site collection using PowerShell:

New-SPOSite -Url "https://enterprise.sharepoint.com/sites/NewSite" -Owner "[email protected]" -StorageQuota "100" -Title "New Site"

Get Archive Mailbox in Exchange Online: 

Archiving offers an additional mailbox to the user’s primary mailbox. So, the admin can enable archiving to the mailbox when it requires more storage. 

To get archive enabled mailboxes,  

Get-Mailbox –ResultSize Unlimited –Archive

To view archive mailboxes size, 

Get-Mailbox –ResultSize Unlimited –Archive | Get-MailboxStatistics| Select DisplayName,TotalItemSize

List Shared Mailboxes: 

A shared mailbox is a type of user mailbox, but users can’t directly login to it by using a username and Password. To access the shared mailbox, users must have certain permissions such as full access, send as, and send on behalf on the shared mailbox. 

To list shared mailboxes in your organization, use the RecipientTypeDetails filter with the value SharedMailbox. 

Get-ExoMailbox –ResultSize Unlimited –RecipientTypeDetails SharedMailbox

Get Mailbox Permission Report: 

Like shared mailboxes, user mailboxes also can be delegated with full access, send as, and send on behalf permissions. To identify users with each permission, execute the following cmdlets. 

To get users with Full Access permission on mailboxes, 

Get-Mailbox | foreach {(Get-MailboxPermission -Identity $_.userprincipalname | where{ ($_.AccessRights -contains "FullAccess") -and ($_.IsInherited -eq $false) -and -not ($_.User -match "NT AUTHORITY") }) | select Identity,AccessRights,User}

To get users with Send-as permission, 

Get-Mailbox | foreach {(Get-RecipientPermission -Identity $_.userprincipalname | where{ -not (($_.Trustee -match "NT AUTHORITY") -or ($_.Trustee -match "S-1-5-21"))}) | select Identity,trustee}

To get mailboxes with Send-on-behalf permission,  

Get-Mailbox –ResultSize Unlimited | Where {$_.GrantSendOnBehalfTo -ne $null} | Select UserprincipalName,GrantSendOnBehalfTo

Identify Inactive Mailboxes: 

Inactive mailboxes can be identified by using the mailbox’s last logon time or last activity time. 

The Get-MailboxStatistics cmdlet helps you to get mailboxes’ last logon time and last activity time. 

Get-Mailbox -ResultSize Unlimited |Foreach{Get-MailboxStatistics -Identity $_.UserPrincipalName | Select DisplayName,LastLogonTime,LastUserActionTime}

Get Mailbox Forwarding Using PowerShell 

Email forwarding allows admins/users to forward email from the mailbox to another mailbox automatically. 

To list mailboxes configured with automatic email forwarding, 

Get-mailbox -ResultSize Unlimited| where {$_.ForwardingAddress -ne $Null} | select DisplayName,ForwardingAddress

The above cmdlet lists mailboxes in which email forwarding is configured through ForwardingAddress. 

Get Mailbox Folder Permission: 

When you don’t want to delegate the entire mailbox, use the ‘folder permission’ feature to grant access to a specific folder only. 

To view folders available in the mailbox, run the Get-MailboxFolder along with the mailbox’s identity. 

Get-MailboxFolder -Identity [email protected] -GetChildren

To view assigned permission on a specific mailbox folder, use the Get-MailboxFolderPermission cmdlet as follows: 

Get-MailboxFolderPermission -Identity "[email protected]:\To me"

The above example returns the list of user permissions for the ‘To me’ folder in admin’s mailbox. 

Creating reports in Office 365 with PowerShell

PowerShell is a great tool for making different reports. Here are some useful Office 365 reports done via PowerShell:

  • Details about all mailboxes:
Get-mailbox | get-MailboxStatistics
  • A list of all mailboxes that haven’t been logged into during the last 30 days:
Get-Mailbox –RecipientType 'UserMailbox' | Get-MailboxStatistics | Sort-Object LastLogonTime | Where {$_.LastLogonTime –lt ([DateTime]::Now).AddDays(-30) } | Format-Table DisplayName, LastLogonTime
  • A report on the highest volume senders and recipients:
Get-MailTrafficTopReport
  • A report on all groups and their members:
function Get-AllO365Members
{
    Try
    {   
     $O365Groups=Get-UnifiedGroup
        foreach ($O365Group in $O365Groups) 
        { 
            Write-Host "Group Membership: " $O365Group.DisplayName -ForegroundColor Green
            Get-UnifiedGroupLinks –Identity $O365Group.Identity –LinkType Members
            Write-Host
        } 
    }
    catch [System.Exception]
    {
        Write-Host -ForegroundColor Red $_.Exception.ToString()   
    } 
}
Get-AllO365Members

Leave a Reply

Your email address will not be published. Required fields are marked *