Deep Dive into Microsoft 365 PowerShell Scripting

Deep Dive into Microsoft 365 PowerShell Scripting


Microsoft 365 lets administrators manage user accounts, licenses, settings, and more online via a web-based administrative console. Although the console provides a user-friendly interface for managing Microsoft 365, it can be complex when it comes to handling multiple users and groups, configuring settings, and automating tasks, especially when managing large environments. 


Powered by the '.NET Framework', PowerShell uses a command-line and scripting language environment to ensure speed, automation, and additional capabilities that let IT admins streamline their operations to gain granular control over your configurations and  manage M365 environment more efficiently. 


Once connected to the Microsoft 365 environment, users can leverage PowerShell to automate and manage various tasks within the environment like generate reports and analytics on user activity, mailbox usage, and SharePoint site usage, configure multi-factor authentication, and implement data loss prevention policies.


Although PowerShell's basics are relatively easy to grab, there are numerous advanced scripting techniques that users can use to advance their skills. In this article, we will take a deep dive into Microsoft 365 PowerShell scripting and how it helps IT admins.


I. Uncovering hidden information in Microsoft 365 admin center


While the Microsoft 365 admin center provides valuable information to users, it is not capable of providing access to all of the information that Microsoft 365 stores about users, licenses, mailboxes, and sites. Fortunately, PowerShell for Microsoft 365 lets you uncover hidden information that is not visible in the admin center.


Let us consider a scenario where you are requested to verify whether a user account has been assigned a license for Microsoft Teams. You check the Microsoft 365 admin center but are unable to find the required information. 


Once you are connected to the Microsoft 365, you can check if the user account has been assigned a license for Microsoft Teams by running the cmdlet - 


Get-MsolUser -UserPrincipalName user@example.com | Select-Object DisplayName, Licenses


In addition to information about licenses assigned to the user, the output will include information about Microsoft Teams licenses. Search for the "Microsoft Teams" product in the list of licenses. 


If the user has a license for Microsoft Teams, it will be listed under the Licenses property. If they do not have a license for Microsoft Teams, it will not be listed.


Using PowerShell for Microsoft 365, you can easily verify whether a user account has been assigned a license for Microsoft Teams, even if the information is not readily visible in the Microsoft 365 admin center.


II. Manage bulk operations


IT administrators may find themselves spending a significant amount of time and effort on the management of bulk operations in Microsoft 365. However, PowerShell for Microsoft 365 makes it easy to streamline and automate multi-user, multi-group, cross-site operations. Now let us look at some scenarios where PowerShell scripts lets IT admins:


  1. To add multiple users to a distribution group:


  1. Import-Csv "C:\users.csv" | ForEach-Object { Add-DistributionGroupMember -Identity "Marketing Group" -Member $_.UserPrincipalName }


Using a CSV file titled "users.csv", this command facilitates the bulk addition of several users to the "Marketing Group" distribution group. The CSV file should have a "UserPrincipalName" column with a list of email addresses.


  1. To remove multiple users from a Microsoft 365 group:


  1. Import-Csv "C:\users.csv" | ForEach-Object { Remove-MsolGroupMember -GroupObjectId "Marketing Group ID" -GroupMemberObjectId (Get-MsolUser -UserPrincipalName $_.UserPrincipalName).ObjectId }


Using a CSV file titled "users.csv", this command facilitates the bulk addition of several users to the "Marketing Group" distribution group. The CSV file should have a "UserPrincipalName" column with a list of email addresses. You will need to replace "Marketing Group ID" with the actual object ID of the group.


  1. Set mailbox permissions for multiple users:


  1. $users = Get-Content "C:\users.txt"
  2. ForEach ($user in $users) {
  3.    Add-MailboxFolderPermission -Identity "$user:\Calendar" -User "Manager" -AccessRights Editor
  4. }


By reading the usernames from a text file called "users.txt", this command sets mailbox permissions for multiple users. By running this command, the "Manager" user is granted access to the "Calendar" folder of every user's mailbox.


III. Automate routine tasks


IT administrators can significantly reduce their workload by automating routine tasks in Microsoft 365. With PowerShell for Microsoft 365, you can automate repetitive tasks and improve productivity of your entire organization. Here are some PowerShell scripts and scenarios that demonstrate automating routine tasks in Microsoft 365.


  1. Automate user onboarding:


  1. $licenses = "EnterprisePack"
  2. $newuser = New-MsolUser -DisplayName "John Doe" -UserPrincipalName "johndoe@contoso.com" -FirstName "John" -LastName "Doe" -LicenseAssignment $licenses -UsageLocation US
  3. $newuserpassword = Read-Host -AsSecureString "Enter password for new user"
  4. Set-MsolUserPassword -UserPrincipalName $newuser.UserPrincipalName -NewPassword $newuserpassword


This script creates a new user with a specific display name, user principal name, assigns a license to the user and also prompts the administrator to enter a password for the new user using the Set-MsolUserPassword cmdlet.


  1. Automate group membership management:


  1. $groupname = "Marketing Group"
  2. $members = Get-Content "C:\users.txt"
  3. $group = Get-MsolGroup -SearchString $groupname
  4. ForEach ($member in $members) {
  5.    $user = Get-MsolUser -UserPrincipalName $member
  6.    Add-MsolGroupMember -GroupObjectId $group.ObjectId -GroupMemberObjectId $user.ObjectId
  7. }

This script automates the management of group memberships in Microsoft 365 by reading a list of usernames from a text file and adding each user to a specific group. The script uses the Add-MsolGroupMember cmdlet to add each user to the group.



  1. Automate license assignment:


  1. $users = Get-MsolUser
  2. ForEach ($user in $users) {
  3.    Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -AddLicenses "EnterprisePack"
  4. }


This script uses the Set-MsolUserLicense cmdlet to automate the process of assigning a specific license to each user in the organization in Microsoft 365.


IV. Filter data


A key aspect of managing Microsoft 365 is filtering data. IT administrators can easily retrieve specific data from their environment by using PowerShell for Microsoft 365's powerful filtering capabilities. Here are some examples on how to filter data using PowerShell in the Microsoft 365 environment.


  1. Filter users by license type:


  1. Get-MsolUser | Where-Object { $_.Licenses.AccountSkuId -eq "ENTERPRISEPACK" }


The script uses the Where-Object cmdlet to filter the users by their license type that helps IT admins retrieve the list of users in the organization who have been assigned the "ENTERPRISEPACK" license. 


  1. Filter groups by member count:


  1. Get-MsolGroup | Where-Object { $_.Members.Count -gt 20 }


This script retrieves a list of all groups in the organization that have more than 20 members. It uses the Where-Object cmdlet to filter the groups by their member count.


  1. Filter SharePoint sites by site owner:


  1. Get-SPOSite | Where-Object { $_.Owner -eq "johndoe@contoso.com" }


The script use Where-Object cmdlet to filter the sites to find the list of sites that are owned by the user "johndoe@contoso.com".



V. Manage across server products


The PowerShell for Microsoft 365 Management Console offers a unified interface for managing Microsoft 365 servers, such as Exchange Online, SharePoint Online, and Teams. The following examples illustrates how PowerShell scripts aid IT admins to manage across server products using PowerShell for Microsoft 365:


  1. Granting permissions to a SharePoint site and adding the user to a Microsoft Teams team:


  1. Connect-SPOService -Url https://contoso-admin.sharepoint.com
  2. Set-SPOSite -Identity "https://contoso.sharepoint.com/sites/marketing" -Owner "johndoe@contoso.com"
  3. Add-TeamUser -GroupId "5c5f5d43-2d0e-4a8a-83b5-7cefbab48f11" -User "johndoe@contoso.com"


In this script, the owner of the SharePoint site "https://contoso.sharepoint.com/sites/marketing" is set to "johndoe@contoso.com" and the same user is added to the Microsoft Teams team with group ID "5c5f5d43-2d0e-4a8a-83b5-7cefbab48f11".


The Connect-SPOService cmdlet is used to connect to SharePoint Online before running the Set-SPOSite cmdlet to set the site owner. The Add-TeamUser cmdlet is then used to add the user to the Teams team.


  1. Retrieving mailbox statistics and setting mailbox properties:


  1. Connect-ExchangeOnline -UserPrincipalName admin@contoso.com
  2. Get-MailboxStatistics -Identity "johndoe@contoso.com" | Select-Object DisplayName,TotalItemSize
  3. Set-Mailbox -Identity "johndoe@contoso.com" -EmailAddressPolicyEnabled $true


Using the administrator user "admin@contoso.com" credentials, this script connects to Exchange Online and retrieves mailbox statistics for the user "johndoe@contoso.com", which includes their display name and total item size. The Select-Object cmdlet is used to filter the output only to show the display name and total item size. The Set-Mailbox cmdlet is then used to enable the email address policy for the same user.


  1. Retrieving team and channel information from Microsoft Teams:


  1. Connect-MicrosoftTeams
  2. Get-Team | Select-Object DisplayName,Visibility
  3. Get-TeamChannel -GroupId "5c5f5d43-2d0e-4a8a-83b5-7cefbab48f11" | Select-Object DisplayName,Description


The first step in this script is to connect to Microsoft Teams using the Connect-MicrosoftTeams cmdlet. The script then proceeds to retrieve the display name and visibility of all teams in the organization. Afterwards, the Get-TeamChannel cmdlet is used to retrieve the display name and description of the channel belonging to the team with group ID "5c5f5d43-2d0e-4a8a-83b5-7cefbab48f11".



In conclusion, PowerShell scripting is a valuable tool for managing Microsoft 365 environments, providing an effective means of carrying out administrative tasks including user and group management, licensing, and settings. With a simple, user-friendly syntax, PowerShell makes it easy to run commands and automate tasks. The Microsoft 365 PowerShell module further enhances this capability, providing a range of cmdlets and APIs for managing different aspects of the Microsoft 365 environment. By leveraging PowerShell scripting, IT administrators can optimize their daily tasks and streamline their management of Microsoft 365, ensuring that their organization operates at peak efficiency.



    • Related Articles

    • Managing Microsoft 365 SharePoint sites and content with PowerShell

      Managing Microsoft 365 SharePoint sites and content can be a challenging task, especially when dealing with large amounts of data. To simplify this process, administrators can take advantage of PowerShell scripting to automate various management ...
    • Microsoft 365 Exchange Online - Shared Mailboxes & PowerShell

      Introduction Overview of Shared Mailboxes A shared mailbox in Microsoft 365 Exchange Online allows multiple users to access and manage emails, contacts, and calendar events from a single mailbox. It is commonly used by teams that need to collaborate ...
    • Microsoft 365 Exchange online - Shared Mailboxes & PowerShell

      Introduction Overview of Shared Mailboxes A shared mailbox in Microsoft 365 Exchange Online allows multiple users to access and manage emails, contacts, and calendar events from a single mailbox. It is commonly used by teams that need to collaborate ...
    • Managing Microsoft 365 licenses using PowerShell

      Managing licenses for Microsoft 365 can be a daunting task, especially when you have a large number of users. However, PowerShell provides a powerful and efficient way to manage licenses in Microsoft 365. In this article, we will walk you through the ...
    • How to automate user management in Microsoft 365 with PowerShell

      Introduction: Managing users in Microsoft 365 can be a time-consuming task, especially for larger organizations. With PowerShell, however, you can automate many of the tasks involved in user management, making the process faster and more efficient. ...