Managing Microsoft 365 with the Microsoft Graph PowerShell SDK

July 20, 2023
8 min read

 

Microsoft Graph is a powerful developer platform that links various services and devices in the Microsoft 365 environment. It simplifies data integration and service interoperability, resulting in a seamless digital environment. To work with Microsoft Graph, you can use PowerShell, a task-based command-line shell and scripting language. Utilizing Graph and PowerShell enhances the Microsoft 365 environment, improves system management, and increases efficiency.

Microsoft Graph is at the center of the Microsoft 365 ecosystem, and it is an essential tool for managing and integrating Microsoft 365’s cloud-based services. Graph is a RESTful web API that lets you access data within the Microsoft Cloud, including user data, office documents, emails, calendar events, and more. By connecting multiple services and their related data, Graph enables the development of intelligent, productivity-driven applications and processes.

PowerShell is a Microsoft task automation and configuration management framework consisting of a command-line shell and the associated scripting language. Its name does not mislead; it is a powerful tool that helps administrators automate repetitive tasks, manage systems, and access a vast range of information across Microsoft's services.

The Microsoft Graph PowerShell SDK is a vital tool. It allows you to use PowerShell to manage resources in Microsoft 365 via the Microsoft Graph API. With this, administrators can efficiently perform tasks such as managing users, configuring system settings, or even automating everyday tasks—all from the command line.

Setting up the Environment

You must ensure a few prerequisites before using Microsoft Graph PowerShell. You'll need PowerShell 5.1 or higher installed on your machine. It's available as a default in most Windows operating systems, but if you're using a different platform like macOS or Linux, you'll need to install PowerShell Core.

Next, ensure you have the necessary permissions. As an administrator, you must have access rights to install modules and make changes. If you are not an admin, you'll need to get the necessary permissions from your system administrator.

The last few steps are:

  • Open your PowerShell console. Ensure you're running it as an administrator.
  • Set your execution policy to allow the installation of PowerShell modules. To do this, enter the command:

Set-ExecutionPolicy Unrestricted

  • Install the module using PowerShell's package manager, PowerShellGet. Enter the command:

Install-Module -Name PowerShellGet -Force

  • With PowerShellGet installed, you can now install the Microsoft Graph PowerShell SDK. Use the command:

Install-Module -Name Microsoft.Graph

Once you've completed these steps, you've successfully installed the Microsoft Graph PowerShell SDK. Now you can start managing Microsoft 365 via the Microsoft Graph PowerShell SDK.

Authenticating with Microsoft Graph PowerShell SDK

Authentication is a crucial step because it ensures secure access to your data. It validates your identity and assigns appropriate permissions based on your user account's associated roles and privileges. Without authentication, unauthorized users could access sensitive data, making your system vulnerable. Microsoft Graph uses Azure Active Directory for authentication, offering robust security and a wide range of configurable options. 

Firstly, ensure you have the Microsoft Graph PowerShell SDK module installed. Once confirmed, open your PowerShell console, and import the Microsoft Graph module using the command:

Import-Module Microsoft.Graph

Secondly, you must connect to your Microsoft Graph using the Connect-MgGraph cmdlet. This command opens a new window prompting you to sign into your Microsoft 365 account. It's essential to use an account with the required permissions to access the data you need.

Thirdly, enter your Microsoft 365 credentials and respond to the authentication prompts. This process may include multi-factor authentication, depending on your account settings.

The window closes once you successfully login and returns you to the PowerShell console. It's important to remember that each PowerShell session requires authentication. So, if you open a new PowerShell console or the current session expires, you must repeat this authentication process.

Connecting to Microsoft Graph this way requires you to pass the necessary permissions called scopes. Scopes in the Connect-MgGraph command refer to the app's permissions to access resources and perform specific operations in the Microsoft Graph API. They dictate what access the token will have when sent to Microsoft Graph.

User.Read allows the app to sign in the user and read the user's profile. In contrast, Mail.Read permits the app to read the user's mail. Specifying the proper scopes is critical to ensure the necessary level of access while maintaining the security and privacy of the data.

# Scopes to Manage Users and Groups with Full Read Write Access
$scopes = @(
"User.ReadWrite.All"
“Directory.ReadWrite.All"
"Group.ReadWrite.All"
)
# Scopes to Create Teams
$scopes = @(
"Team.Create"
“Group.ReadWrite.All"
)
# Scopes to Manage SharePoint Online Sites and Files
$scopes = @(
"Sites.FullControl.All"
"Sites.Manage.All"
"Sites.ReadWrite.All"
"Files.ReadWrite.All"
"Files.ReadWrite.AppFolder"
)

You can also use an app registration within Azure Active Directory that contains all the required permissions, allowing you to connect using a client ID, tenant ID, and certificate thumbprint.

Connect-MgGraph ` 
-ClientId "978aeedd-afce-7d86d85b1314" ` 
-TenantId "b93c547e-b3f7-aa29cd6ee3dc" ` 
-CertificateThumbprint "0C21DA5EDDDFF9802A"

A screenshot of Microsoft Graph permissions for an app registration
Figure 1: Microsoft Graph permissions for an app registration. Used with permission by Microsoft. View Full Size

 

By ensuring proper authentication, you maintain a secure environment, limit access only to authorized users, and mitigate potential risks. With authentication complete, you're ready to start exploring the many features of the Microsoft Graph PowerShell SDK.

Managing Users and Groups

When using Microsoft 365, managing users and groups is an essential administrative duty. It includes creating new users, updating user information, managing group membership, and deleting users or groups as needed. Luckily, the Microsoft Graph PowerShell SDK makes these tasks much more straightforward.

To create a new user with the SDK, use the New-MgUser command. You'll need to provide several parameters such as userPrincipalName, accountEnabled status, display name, and password. For example:

$password = @{ Password = 'Password' }
New-MgUser `
-DisplayName 'User Account' `
-PasswordProfile $password `
-AccountEnabled `
-MailNickName 'UserAccount' `
-UserPrincipalName 'user@m365.onmicrosoft.com'

Updating a user or a group is straightforward too. For instance, to change a user's display name, we use the Update-MgUser command:

Update-MgUser ` 
-UserId '5f2db099-011c-429d-8ba3-4158e2bec2ae' ` 
-DisplayName 'New Display Name'

To delete a user or a group, you execute the Remove-MgUser command. For example:

Remove-MgUser -UserId '5f2db099-011c-429d-8ba3-4158e2bec2ae'

Retrieving user and group information is also an essential part of administration. With Microsoft Graph PowerShell SDK, we use the Get-MgUser command to retrieve a list of all users and the Get-MgGroup command to retrieve all groups. If you're looking for a specific user or group, you can provide the UserID or GroupID as a parameter, respectively.

# Retrieve All Users
Get-MgUser | Format-List ID, DisplayName, Mail, UserPrincipalName
# Retrieve Users by Filtering
Get-MgUser -ConsistencyLevel eventual -Filter "startsWith(Mail, 'user')"
# Retrieve All Groups
Get-MgGroup | Format-List ID, DisplayName, Description, GroupTypes
# Retrieve Groups by Filtering
Get-MgGroup -ConsistencyLevel eventual `
-Filter "startsWith(DisplayName, 'group')"

The Microsoft Graph PowerShell SDK provides a powerful toolset for managing users and groups within Microsoft 365, enabling administrators to perform their tasks efficiently and effectively.

Managing Mail and Calendar

You can easily use the Microsoft Graph PowerShell SDK to manage your mail and calendar features in Microsoft 365. This tool allows administrators and developers to automate tasks like sending emails, scheduling events, and managing calendars, saving time and reducing errors.

To send an email using the SDK, use the Send-MgUserMail command. This command requires a UserID parameter and a Message object that includes recipients, subject, and body. For example: 

Send-MgUserMail -UserId 'user@m365.onmicrosoft.com' `
-Message @{ 
Subject = 'Subject'; 
Body = @{ 
ContentType = 'Text'; 
Content = 'Message'};
ToRecipients = @( 
@{ 
EmailAddress = @{
Address = 'user@m365.onmicrosoft.com'
} 
} 
)
}

To schedule a new event, you can use the New-MgUserEvent command. This command requires parameters such as the user's ID, the start and end time of the event, and details like the subject and attendees. For instance: 

New-MgUserEvent `
-UserId 'user@m365.onmicrosoft.com' `
-Start @{DateTime='2023-05-30T10:00:00';TimeZone='UTC'} `
-End @{DateTime='2023-05-30T11:00:00';TimeZone='UTC'} `
-Subject 'Subject' `
-Attendees @{EmailAddress='user@m365.onmicrosoft.com'}

You can also manage calendars using commands like New-MgUserCalendar to create a new calendar, Get-MgUserCalendar to retrieve a user's calendars, and Remove-MgUserCalendar to delete a calendar. You can automate and manage various email and calendar tasks efficiently and effectively within Microsoft 365 by leveraging the Microsoft Graph PowerShell SDK.

Managing Microsoft Teams

Managing Microsoft Teams using the Microsoft Graph PowerShell SDK enables administrators to automate tasks like managing teams, channels, and members, all from the command line. With its powerful capabilities, you can improve efficiency and ensure a more streamlined approach to Teams administration.

To create a new team, you can use the New-MgTeam command. This command requires parameters such as DisplayName, Description, and Visibility. For instance:

$params = @{
"Template@odata.bind" = "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"
DisplayName = "Display Name"
Description = "Description"
Members = @(
@{
"@odata.type" = "#microsoft.graph.aadUserConversationMember"
Roles = @(
"owner"
)
"User@odata.bind" = "https://graph.microsoft.com/v1.0/users('72aa81e3-dacc-46c2-b99a-56d1b7a115c5')"
}
)
}
New-MgTeam -BodyParameter $params

To add a channel to a team, use the New-MgTeamChannel command, specifying the TeamId and DisplayName. For example:

$params = @{
DisplayName = "Display Name"
Description = "Description"
MembershipType = "standard"
}
New-MgTeamChannel `
-TeamId "95acd139-4e67-40b7-baf2-0ed4cfbb3d70" `
-BodyParameter $params

You can use the Add-MgTeamMember command to add a team member. This command requires the TeamId and UserId parameters. For example:

$params = @{
Values = @(
@{
"@odata.type" = "microsoft.graph.aadUserConversationMember"
Roles = @(
"member"
)
"User@odata.bind" = "https://graph.microsoft.com/v1.0/users('2bfc1de4-7887-4b4a-90f3-95264894e319')"
}
)
}
Add-MgTeamMember `
-TeamId "95acd139-4e67-40b7-baf2-0ed4cfbb3d70" `
-BodyParameter $params

If you want to retrieve the list of teams, use the Get-MgTeam command. To fetch the list of channels within a team, use the Get-MgTeamChannel command with the TeamId parameter.

To remove a member from a team, use the Remove-MgTeamMember command, and to delete a team, use the Remove-MgTeam command, each requiring the respective TeamId and UserId parameters.

The Microsoft Graph PowerShell SDK provides a rich set of commands to manage Microsoft Teams effectively, simplifying administration tasks and improving overall productivity.

Conclusion

In this article, you have explored the multifaceted capabilities of the Microsoft Graph PowerShell SDK for managing Microsoft 365. We've covered the setup process and authentication and then delved into the core administrative tasks - managing users and groups, files and drives, mail and calendars, and even Microsoft Teams. We then ventured into more complex operations such as SharePoint site management and advanced Teams administration.

The Microsoft Graph PowerShell SDK offers a robust, efficient, and secure method of administering Microsoft 365 environments. Automating these tasks can enhance productivity, reduce errors, and maintain a more streamlined Microsoft 365 management process.

The SDK's benefits are far-reaching, and its potential applications are vast. Whether you are an IT administrator, a developer, or someone who manages Microsoft 365 resources, mastering this tool can dramatically simplify your workflow and improve your overall efficiency.

Please explore the Microsoft Graph PowerShell SDK further. Dive deep, experiment, and see how to utilize its capabilities to make your Microsoft 365 management tasks more efficient and effective.

Liam Cleary

Liam Cleary

Liam began his career as a computer trainer. He quickly realized that programming, breaking and hacking were much more fun. Liam spent the next few years working within core infrastructure and security services. He is now the founder and owner of SharePlicity, a consulting company focusing on Microsoft 365 and Azure technology. His role within SharePlicity is to help organizations implement Microsoft 365 and Azure technology to enhance internal and external collaboration, document, and records management, automate business processes, and implement security controls and protection. He is a long-time Microsoft MVP and Microsoft Certified Trainer, focusing on architecture, security and crossing the boundary into software development. Over the past few years, his specialty has been security in Microsoft 365, Azure and its surrounding platforms. Liam also creates online training courses for Pluralsight, LinkedIn Learning and Cloud Academy, and he teaches multiple Microsoft certification courses for Opsgility and Microsoft. You can find him at user groups and conferences, teaching classes, offering advice, spending time in the community, teaching his kids how to code, raspberry PI programming, hacking the planet, building Lego robots, or coaching soccer. You may also find him running races in the dark, hiking, or mountain biking at breakneck speeds.