fbpx
Active Directory & Office 365 Reporting Tool

Top 15 Office 365 PowerShell Commands (Users, Groups, Licensing). As a Windows PowerShell user, I am aware that using PowerShell for Office 365 administration may seem complicated to a lot of Office 365 users. 

However, in my experience, despite of this, Windows PowerShell is an extremely useful tool for managing Office 365. For example, instead of sifting through the myriad of options available in the Office 365 portal, administrators can easily obtain what they require by entering a few lines of code. It is therefore imperative to learn of a few handy commands that can go a long way in streamlining your Office 365 experience.

With that in mind, let’s learn the top 15 Office 365 PowerShell commands that can be handy in simplifying Office 365 tasks.

Top 15 Office 365 PowerShell Commands (Users, Groups, Licensing)

Image source: Pixabay

1. Creating Classifications for Microsoft 365 Groups

When users in your organization create a Microsoft 365 Group, you can give them the option of assigning a sensitivity label. It is important to note that once sensitivity labels are enabled, users who create groups will no longer have access to the classification labels they were previously using.

Microsoft recommends using sensitivity labels instead of the previous groups’ classification feature. You can create classifications that the users in your organization can set when they create a Microsoft 365 Group. For example, you can allow users to set “Standard”, “Secret”, and “Top Secret” on groups that they create. Here are the appropriate Azure Active Directory cmdlets for creating group classifications.

This command below creates a classification list:

				
					$setting["ClassificationList"] = "Low Impact, Medium Impact, High Impact"
				
			

You can use the settings attribute ClassificationDescriptions to define each classification. The syntax is as follows:

				
					$setting["ClassificationDescriptions"] ="Classification:Description,Classification:Description"
				
			

Example command:

				
					$setting["ClassificationDescriptions"] = "Low Impact: General communication, Medium Impact: Company internal data , High Impact: Data that has regulatory requirements"
				
			

Alternatively, execute this command when creating a new group with classification:

				
					New-UnifiedGroup  -Classification  -AccessType 
				
			

After enabling these settings, the group owner will now be able to select a label from a drop down menu and save it from the Edit group page in both Outlook on the Web and Outlook.

2. Giving Users Permission to Send as the Microsoft 365 Group

Image Source: Unsplash

When this setting is enabled, members of a Microsoft 365 group can use any version of Outlook or Outlook on the web to compose and reply to emails in the name of the group. 

To do so, use the Add-RecipientPermission and Get-RecipientPermission cmdlets to enable your Microsoft 365 groups option to “Send As.”

To send an email to the group address, users need to visit the group, compose a new email, and then edit the “Send As” field to read “Group.”

You can also do this via The Exchange Admin Center. To modify a group’s permissions for a certain user, run the following script with the appropriate substitutions for the group’s and the user’s aliases. This script requires access to Exchange Online PowerShell, which is obtained by connecting to Exchange Online.

PowerShell:

				
					$groupAlias = ""
$userAlias = ""
$groupsRecipientDetails = Get-Recipient -RecipientTypeDetails groupmailbox -Identity $groupAlias
Add-RecipientPermission -Identity $groupsRecipientDetails.
Name -Trustee $user
Alias -AccessRights SendAs

				
			

Once this command has been run and executed, users can go to Outlook or Outlook on the web and send as the group by entering the group’s email address in the From field.

3. Using PowerShell to retrieve a Complete List of Office 365 Users

Use the Get-MsolUser cmdlet to compile a list of Office 365 users and their associated licenses. This command returns the Department, DisplayName, City, and ObjectID for each user in the Office 365 tenant who has a valid license.

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

Often when managing Office365, you may need to view the total number of account licenses. To do so, run the following cmdlet:

				
					Get-MsolAccountSku
				
			

In case you’d like to view a list of the available services, you need to run the following script:

				
					Select "Get-MsolAccountSku | -ExpandProperty ServiceStatus"
				
			

4. Hiding Microsoft 365 Groups from the Global Address List (GAL)

Microsoft allows you to specify whether or not a Microsoft 365 Group is displayed in the GAL or in other company wide distribution lists. 

For instance, if for some reason, you don’t want a certain group to appear in the global address list. To remove the group’s entry from the address list, you need to run the following Set-Unified Group cmdlet.

				
					Set-UnifiedGroup -Identity "Legal Department" -HiddenFromAddressListsEnabled $true
				
			

Run Office 365 Reports using InfraSOS (100's of Reports)

Try us out for Free, Access to all features. – 200+ AD Report templates Available. Easily customise your own AD reports.

5. Ensuring that only Internal Users can message Microsoft 365 Groups

Image Source: Pixabay

Microsoft 365 Group’s settings can be adjusted to prevent messages from users outside the group’s organization. This setting ensures that no one outside of your organization is able to send an email to your group via email. 

When this setting is enabled, any messages sent to your group by users outside of the group are ignored.

To do so, run the following Set-UnifiedGroup cmdlet command.

				
					Set-UnifiedGroup -Identity "Internal senders only" -RequireSenderAuthenticationEnabled $true
				
			

6. Modifying the Microsoft 365 Group's Display Name

The Microsoft 365 Group’s name is specified in the display name. This is the name that appears in the Exchange or Microsoft 365 control panel. By using the Set-UnifiedGroup command, you can change the group’s display name or give a new one to an existing Microsoft 365 Group.

To do so please run this command:

				
					Set-UnifiedGroup -Identity "mygroup@contoso.com" -DisplayName "My new group"
				
			

7. Viewing licensed Microsoft 365 Users

Your Microsoft 365 organization’s licensing options may allow for some, all, or no licenses to be issued to user accounts. PowerShell for Microsoft 365 allows you to easily identify which employees have valid licenses and which do not.

Run the following command to view the licenses available in the tenant:

				
					Connect-Graph -Scopes User.Read.All, Organization.Read.All

				
			

Execute this command to view the license details of a specific account:

				
					Get-MgUserLicenseDetail -UserId ""
				
			

For example:

				
					Get-MgUserLicenseDetail -UserId "belindan@litwareinc.com"
				
			

Run this command to see a complete list of all user accounts in your organization that have been given access to one of your licensing plans (licensed users).

				
					Get-MgUser -Filter 'assignedLicenses/$count ne 0' -ConsistencyLevel eventual -CountVariable licensedUserCount -All -Select UserPrincipalName,DisplayName,AssignedLicenses | Format-Table -Property UserPrincipalName,DisplayName,AssignedLicenses
Write-Host "Found $licensedUserCount licensed users."

				
			

Run this command to view a list of user accounts in your organization that have an E5 license.

				
					$e5Sku = Get-MgSubscribedSku -All | Where SkuPartNumber -eq 'SPE_E5'
Get-MgUser -Filter "assignedLicenses/any(x:x/skuId eq $($e5sku.SkuId) )" -ConsistencyLevel eventual -CountVariable e5licensedUserCount -All
Write-Host "Found $e5licensedUserCount E5 licensed users."

				
			

8. Viewing Unlicensed Users

To view unlicensed users, run the following command:

				
					Get-MgUser -Filter 'assignedLicenses/$count eq 0' -ConsistencyLevel eventual -CountVariable unlicensedUserCount -All
Write-Host "Found $unlicensedUserCount unlicensed users."

				
			

Execute this command to see a list of all user accounts (other than guest accounts) in your organization that have not been allocated any of your licensing plans (unlicensed users).

				
					Get-MgUser -Filter "assignedLicenses/`$count eq 0 and userType eq 'Member'" -ConsistencyLevel eventual -CountVariable unlicensedUserCount -All
Write-Host "Found $unlicensedUserCount unlicensed users (excluding guests)."

				
			

9. Integrating MailTips into Microsoft 365 Groups

Office 365 allows mail tips to be displayed whenever an email is being sent to a Microsoft 365 Group.

To do so you need to use the Set-Unified Group cmdlet:

				
					Set-UnifiedGroup -Identity "MailTip Group" -MailTip "This group has a MailTip"
				
			

Office 365 allows you to also define alternative translations for the MailTip via the MailTipTranslations setting. 

For example, if you’d like the Spanish version, you can get it by executing the following command:

				
					Set-UnifiedGroup -Identity "MailaTip Group" -MailTip "This group has a MailTip" -MailTipTranslations "@{Add="ES:Esta caja no se supervisa."
				
			

10. Changing a password in Office 365 with PowerShell

As an administrator or regular user of Office 365, you may be required to change your password, either because your account has been compromised or because you want to use a more secure password.

Office365 makes this possible with the Set-MsolUserPassword command which is used to modify an existing password. The system generates a random password if you don’t want to bother with trying to come up with one, or you specify a new password like in the example below.

				
					Set-MsolUserPassword -UserPrincipalName JSmith@Netwrixqcspa.onmicrosoft.com -NewPassword P@SSw0rd!
				
			

11. Managing Office 365 Group Membership

Office 365 gives administrators the capability to manage Office 365 membership by using Powershell. Often as an admin you may need to get a list of all groups. For this you need to use the Get-MsolGroup command. This command allows you to get a complete list of Office 365 groups. 

Additionally, you can use the Add-MsolGroupMember command to add a user in a group:

				
					Add-MsolGroupMember -GroupObjectId 5b61d9e1-a13f-4a2d-b5ba-773cebc08eec -GroupMemberObjectId a56cae92-a8b9-4fd0-acfc-6773a5c1c767 -GroupMembertype user
				
			

By using the Get-MsolGroup command, you can also determine the group’s hexadecimal ID, which is represented by GroupObjectId. You can also find the GroupMemberObjectId which is the user object ID, by executing this command:

				
					Get-MsolUser | Select ObjectID.
				
			

Finally, as an administrator, if you want to remove a user from a group, you can do so with the Remove-MsoGroupMember cmdlet.

12. Creating Reports in Office 365

PowerShell is used to generate a wide variety of reports in Office 365. Here are the following useful Powershell commands for creating Office 365 reports.

Getting detailed analysis of all mailboxes:

				
					Get-mailbox | get-MailboxStatistics
				
			

If you would like to see a complete list of inactive mailboxes that haven’t been accessed in the last 30 days, you can do so by using the following command:

				
					Get-Mailbox –RecipientType 'UserMailbox' | Get-MailboxStatistics | Sort-Object LastLogonTime | Where {$_.LastLogonTime –lt ([DateTime]::Now).
AddDays(-30) } | Format-Table DisplayName, LastLogonTime

				
			

To get a report of the top senders and receivers, execute the following command:

				
					Get-MailTrafficTopReport
				
			

Run the following script to get a report of all groups and their memberships:

				
					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 

				
			

It is important to note that the new MS Graph Reporting API has now replaced the majority of the Powershell reports cmdlets.

Therefore, you may need to head over to the Office 365 Security & Compliance Center to get some reports.

13. Removing User from all sites with PowerShell

Sometimes as an administrator, you may need to remove a user from Office 365. For this use the following command to permanently delete a user from all sites:

				
					Get-SPOSite | ForEach {Remove-SPOUser -Site $_.Url -LoginName " JSmith@enterprise.onmicr
				
			

14. Establishing a Connection to an Office 365 Instance

To begin working with Office 365, the Windows PowerShell module must be downloaded and installed. Follow the following steps to do so.

First, get the Microsoft Online Services Sign In Assistant for IT Professionals RTW and set it up on your computer.

The second step is to install the Online Services PowerShell module for Azure Active Directory and Office 365 on your computer:

This can be done by executing this command:

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

				
			

The next step is to provide your administrator credentials for Office 365:

				
					$Cred = Get-Credential

				
			

The fourth step is to create a remote Powershell session. To do so run the following command:

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

The next step is to import the session commands into the local Windows PowerShell session:

				
					Import-PSSession $O365

				
			

Finally, connect to all Office 365 services with: 

				
					Connect-MsolService –Credential $O365

				
			

After the necessary Windows PowerShell modules have been imported, you can now begin managing Office 365.

15. Connecting to Exchange Online and SharePoint Online with PowerShell

Office365 allows you establish a connection to either Microsoft Exchange Online or Microsoft SharePoint Online. Connecting to Exchange Online through PowerShell is quite similar to connecting to Office 365. To do so run the following code:

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

				
			

On the other hand, connecting to SharePoint Online works a little differently. You’ll need to install the SharePoint Online Management Shell add-on before you manage your SharePoint Online tenant. Once that is done, you then execute the following PowerShell script:

				
					$admin="Admin@enterprise.onmicrosoft.com" $orgname="enterprise" $userCred = Get-Credential -UserName $admin -Message "Type the password." Connect-SPOService -Url https://$orgname-admin.sharepoint.com -Credential $userCred
				
			

Top Office 365 PowerShell Commands (Users, Groups, Licensing) Conclusion

Powershell is an extremely powerful tool to manage Office 365. Management in Office 365 with PowerShell is as quick and simple as it is on Microsoft Windows Server. 

However, while modifications can be easily made with Powershell, it’s always recommended that you keep an audit trail of any and all modifications made to your Office 365 environment. This is helpful in troubleshooting in case you encounter problems down the road.

InfraSOS-AD-Tools

Try InfraSOS for FREE

Invite your team and explore InfraSOS features for free

Josiah Mutuma

Josiah Mutuma

Josiah is a tech security expert and has been a writer for over 5 years. Follow this blog to learn more on Microsoft and Cyber security.

Comment (1)

  1. John Donovan
    February 12, 2024

    Hi Josiah, do you know a PowerShell script that can get your current security setting on you M365 tenant for Teams, OneDrive and SharePoint? and send it to a txt file?

    Thanks
    John

Leave a comment

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