Skip to main content

Getting Started with Microsoft Graph PowerShell SDK: A Comprehensive Guide

ยท 15 min read
marvika
Digital Workplace enthusiast

Hey there! If you're looking to supercharge your IT administration tasks and harness the full potential of Microsoft Graph PowerShell SDK, you've come to the right place! In this comprehensive guide, I'll walk you through everything you need to get started, especially focusing on device management and automation with Intune.

Whether you're an IT pro or just someone who's passionate about PowerShell (aren't we all?), this guide is packed with insights and practical steps to help you automate tasks and manage devices like a pro.

So, grab your favorite beverage โ˜•๏ธ, and let's dive into the world of Microsoft Graph PowerShell SDK together!

Getting Started with Microsoft Graph PowerShell SDK


๐Ÿš€ Why Use Microsoft Graph PowerShell SDK?โ€‹

Before we get our hands dirty, let's chat about why the Microsoft Graph PowerShell SDK is such a powerful tool.

  • Unified API Endpoint: Imagine interacting with a ton of Microsoft 365 services through a single API endpoint. Yep, it's as convenient as it sounds!
  • Automation: Say goodbye to repetitive tasks. Automate them and save time (and sanity).
  • Device Management: Gain superpowers in managing devices across your organization, especially with Intune.
  • Scalability: Whether you're managing a small team or a massive organization, your scripts can scale effortlessly.
  • Integration: Seamlessly blend with other Microsoft services and tools, creating a harmonious IT ecosystem.

By tapping into the Microsoft Graph PowerShell SDK, you're setting yourself up to modernize IT management processes and unlock the full potential of automation. Trust me, your future self will thank you!


๐Ÿ“ Understanding Microsoft Graph PowerShell SDKโ€‹

What is Microsoft Graph?โ€‹

In simple terms, Microsoft Graph is your gateway to data and intelligence in Microsoft 365. It provides a unified API endpoint to interact with various services like:

  • Microsoft Entra ID (Azure Active Directory): Manage users, groups, and organizational relationships.
  • Intune: Configure and manage devices, applications, and policies.
  • Microsoft Teams: Handle teams, channels, and messaging.
  • OneDrive: Access and manage files and folders.
  • SharePoint: Work with sites, lists, and content.

Think of it as the central hub connecting all the Microsoft services you know and love. By leveraging Microsoft Graph, you can build applications and scripts that interact with user data at scale.

What is Microsoft Graph PowerShell SDK?โ€‹

The Microsoft Graph PowerShell SDK is a collection of PowerShell modules that provide cmdlets (commands) to interact with Microsoft Graph. Here's what you can do with it:

  • Perform CRUD Operations: Create, read, update, and delete resources across Microsoft 365 services.
  • Automate Tasks: Reduce manual workload by automating administrative and operational tasks.
  • Access Advanced Features: Utilize cool functionalities like batch processing and app-only authentication.

The best part? It simplifies the complexities of making HTTP requests to the Microsoft Graph API. So, you can focus on scripting and automation without sweating the technical stuff.


๐Ÿ“‹ Prerequisitesโ€‹

Alright, let's make sure we've got everything we need before we jump in.

1. Technical Requirementsโ€‹

  • PowerShell Version:
    • Windows PowerShell 5.1 or higher (comes pre-installed on Windows 10 and later).
    • PowerShell 7 (cross-platform). I highly recommend this for the latest features and because it works on macOS and Linux too!
  • Internet Connectivity: We'll need this to install modules and connect to Microsoft Graph.

2. Microsoft 365 Environmentโ€‹

  • Microsoft 365 Account: An account with the right permissions to access Microsoft Graph.
    • For delegated access: A user account.
    • For app-only access: An app registration with the necessary permissions.
  • Microsoft Entra ID (Azure Active Directory): Access to your organization's Entra ID for app registrations (if you're going the app-only authentication route).

3. Optional Toolsโ€‹

  • Visual Studio Code: Not mandatory, but it's my go-to for script development. It offers features like syntax highlighting, debugging, and IntelliSense. Plus, it's free!

๐Ÿ›  Installing the Microsoft Graph PowerShell SDKโ€‹

Let's get this show on the road! Installing the SDK is straightforward.

Step 1: Install the SDK Modulesโ€‹

There are two primary modules:

  • Microsoft.Graph: Contains cmdlets for Microsoft Graph REST API v1.0. This is what you want for production environments.
  • Microsoft.Graph.Beta: Contains cmdlets for the beta endpoints. Only use this for testing new features that aren't generally available yet.

Install the Microsoft.Graph Moduleโ€‹

Open up PowerShell and run:

Install-Module Microsoft.Graph -Scope CurrentUser -Repository PSGallery -Force

Quick Breakdown:

  • -Scope CurrentUser: Installs the module for your user account, so no admin rights needed.
  • -Repository PSGallery: Tells PowerShell where to find the module.
  • -Force: Skips any prompts and forces the installation.

It might take a few minutes, so hang tight!

Install the Microsoft.Graph.Beta Module (Optional)โ€‹

If you're feeling adventurous and want to play with beta features:

Install-Module Microsoft.Graph.Beta -Scope CurrentUser -Repository PSGallery -Force

Just a heads-up: Beta features can be unstable and are subject to change. Use them wisely!

Step 2: Verify Installationโ€‹

Let's make sure everything installed correctly:

Get-Module -ListAvailable -Name Microsoft.Graph*

You should see the modules listed. If not, double-check the installation steps.

Step 3: Update Existing Modules (Optional)โ€‹

Already had the modules installed? Keep them up to date with:

Update-Module Microsoft.Graph

๐Ÿ” Authentication Methodsโ€‹

To interact with Microsoft Graph, we'll need to authenticate. There are two main ways to do this:

1. Delegated Access (User Authentication)โ€‹

  • When to Use: When you're running scripts interactively and can sign in.

  • Scenario: You're performing administrative tasks and need to act as a user.

  • Permissions: Based on the signed-in user's permissions.

  • How to Connect:

    Connect-MgGraph -Scopes "User.Read.All", "DeviceManagementConfiguration.Read.All"

This will prompt you to sign in and grant the specified permissions.

2. App-Only Access (Entra ID App Authentication)โ€‹

  • When to Use: For scripts that run unattended, like scheduled tasks.

  • Scenario: Automation processes that need higher privileges or run without user interaction.

  • Permissions: Based on what you've granted to the app registration in Entra ID.

  • How to Connect:

    Connect-MgGraph -ClientId "your-client-id" -TenantId "your-tenant-id" -CertificateThumbprint "your-cert-thumbprint"

This method uses an app registration and a certificate for authentication.


๐Ÿ“ Setting Up Delegated Authenticationโ€‹

Let's set up user authentication so you can perform actions on behalf of a user.

Step 1: Determine Required Permission Scopesโ€‹

First, figure out what permissions you need. Common ones include:

  • User.Read.All: Read all users' full profiles.
  • DeviceManagementConfiguration.Read.All: Read Intune device configurations.

You can find more scopes in the Microsoft Graph permissions reference.

Step 2: Connect to Microsoft Graphโ€‹

Run:

Connect-MgGraph -Scopes "User.Read.All", "DeviceManagementConfiguration.Read.All"

You'll be prompted to sign in. Use an account with the necessary permissions.

Step 3: Verify Connectionโ€‹

Check your connection:

Get-MgContext

This will display your current session info, including granted scopes.


๐Ÿ›ก Setting Up App-Only Authentication (Entra ID App Registration)โ€‹

For those automation tasks that need to run without user interaction, app-only authentication is your friend.

Step 1: Register an Application in Entra IDโ€‹

  1. Go to Azure Portal: Navigate to Entra ID > App registrations.
  2. Create a New Registration:
    • Click New registration.
    • Name: Give it a meaningful name (e.g., "Graph PowerShell App").
    • Supported Account Types: Choose Accounts in this organizational directory only.
    • Redirect URI: Leave it blank for app-only authentication.
  3. Register: Hit that Register button!

Step 2: Configure API Permissionsโ€‹

  1. API Permissions: In your app registration, go to API permissions.
  2. Add a Permission:
    • Click Add a permission.
    • Select Microsoft Graph.
    • Choose Application Permissions.
    • Select the permissions you need (e.g., User.Read.All, DeviceManagementManagedDevices.Read.All).
  3. Grant Admin Consent:
    • Click Grant admin consent for [Your Organization].
    • Confirm by clicking Yes.

Remember: Admin consent is crucial for app-only access!

Step 3: Create a Client Secret or Certificateโ€‹

You need credentials for your app to authenticate.

Option A: Client Secretโ€‹

  1. Certificates & Secrets: Go to Certificates & secrets.
  2. New Client Secret:
    • Click New client secret.
    • Description: Name it something memorable.
    • Expires: Choose an expiration period (shorter is more secure).
  3. Add: Click Add and copy the secret value immediately.

Pro Tip: Store your client secret securely, like in Azure Key Vault.

  1. Generate a Certificate:

    • Use a self-signed certificate or get one from a certificate authority.

    • For self-signed:

      New-SelfSignedCertificate -CertStoreLocation "Cert:\CurrentUser\My" -Subject "CN=GraphPowerShellApp"
  2. Export the Certificate:

    • Export it and note the thumbprint.
  3. Upload Certificate:

    • In Certificates & secrets, click Upload certificate.
    • Select your certificate file.

Certificates are more secure than client secrets!

Step 4: Connect Using App-Only Authenticationโ€‹

Depending on your method:

Using Client Secretโ€‹

Connect-MgGraph -ClientId "your-client-id" -TenantId "your-tenant-id" -ClientSecret "your-client-secret"

Using Certificateโ€‹

Connect-MgGraph -ClientId "your-client-id" -TenantId "your-tenant-id" -CertificateThumbprint "your-cert-thumbprint"

Step 5: Verify Connectionโ€‹

Check your connection:

Get-MgContext

It should show that you're authenticated as an application.


๐Ÿ” Exploring Microsoft Graph Cmdletsโ€‹

Now the fun begins! Let's explore the cmdlets available.

Finding the Right Cmdletsโ€‹

Not sure which cmdlet to use? Try:

Find-MgGraphCommand -Uri 'deviceManagement/managedDevices'

This will list all cmdlets related to managed devices.

Getting Help on Cmdletsโ€‹

Need more info on a cmdlet?

Get-Help Get-MgUser -Detailed

This provides detailed info, including examples.

Don't forget to run Update-Help occasionally!


๐Ÿ“ฆ Working with Intune Managed Devicesโ€‹

Let's dive into some practical examples.

Example 1: Retrieve All Managed Devicesโ€‹

# Retrieve all managed devices
$devices = Get-MgDeviceManagementManagedDevice -All

# Display device names and operating systems
$devices | Select-Object DeviceName, OperatingSystem

Example 2: Filtering Devicesโ€‹

Get compliant Windows devices:

$windowsCompliantDevices = Get-MgDeviceManagementManagedDevice -Filter "complianceState eq 'compliant' and operatingSystem eq 'Windows'"

$windowsCompliantDevices | Select-Object DeviceName, ComplianceState, OperatingSystem

Example 3: Looping Through Devicesโ€‹

Retrieve associated users:

foreach ($device in $devices) {
# Retrieve user details
$user = Get-MgUser -UserId $device.UserPrincipalName -Property DisplayName

# Output device and user information
Write-Host "Device: $($device.DeviceName), User: $($user.DisplayName)"
}

Example 4: Remote Actionsโ€‹

Restart a device:

# Restart a device
Invoke-MgDeviceManagementManagedDeviceRestart -ManagedDeviceId $device.Id

Always ensure you have the necessary permissions and that the action is appropriate!


๐Ÿ›  Advanced Scripting Techniquesโ€‹

Let's level up your scripting skills!

Handling Paginationโ€‹

For large datasets:

$allDevices = Get-MgDeviceManagementManagedDevice -All

Using OData Queriesโ€‹

Filter, sort, and select data efficiently.

  • Filter:

    $iosDevices = Get-MgDeviceManagementManagedDevice -Filter "operatingSystem eq 'iOS'"
  • Select:

    $selectedProperties = Get-MgDeviceManagementManagedDevice -Select "DeviceName,OperatingSystem"
  • OrderBy:

    $sortedDevices = Get-MgDeviceManagementManagedDevice -OrderBy "DeviceName"

Batch Processingโ€‹

Optimize performance by batching requests.

Example: Batch Processing Top 10 Usersโ€‹

Step 1: Retrieve Top 10 Users

# Retrieve top 10 users
$users = Get-MgUser -Top 10

Step 2: Create Batch Requests

# Initialize an array to hold batch requests
$batchRequests = @()
$counter = 1

foreach ($user in $users) {
# Create a request to get the user's manager
$request = @{
id = "$counter"
method = "GET"
url = "/users/$($user.Id)/manager"
}
$batchRequests += $request
$counter++
}

# Prepare the batch body
$batchBody = @{
requests = $batchRequests
} | ConvertTo-Json -Depth 5

Step 3: Send the Batch Request

# Send the batch request
$response = Invoke-MgGraphRequest -Method POST -Uri 'https://graph.microsoft.com/v1.0/$batch' -Body $batchBody -ContentType 'application/json'

Step 4: Process the Response

# Process the responses
foreach ($res in $response.responses) {
if ($res.status -eq 200) {
$manager = $res.body
Write-Host "User: $($users[$res.id - 1].DisplayName), Manager: $($manager.displayName)"
} else {
Write-Host "Failed to get manager for User: $($users[$res.id - 1].DisplayName). Status: $($res.status)"
}
}

Full Script Example

# Retrieve top 10 users
$users = Get-MgUser -Top 10

# Initialize batch requests
$batchRequests = @()
$counter = 1

foreach ($user in $users) {
$request = @{
id = "$counter"
method = "GET"
url = "/users/$($user.Id)/manager"
}
$batchRequests += $request
$counter++
}

# Create batch body
$batchBody = @{
requests = $batchRequests
} | ConvertTo-Json -Depth 5

# Send batch request
$response = Invoke-MgGraphRequest -Method POST -Uri 'https://graph.microsoft.com/v1.0/$batch' -Body $batchBody -ContentType 'application/json'

# Process responses
foreach ($res in $response.responses) {
if ($res.status -eq 200) {
$manager = $res.body
Write-Host "User: $($users[$res.id - 1].DisplayName), Manager: $($manager.displayName)"
} else {
Write-Host "Error for User: $($users[$res.id - 1].DisplayName). Status: $($res.status)"
}
}

Explanationโ€‹

  • Retrieve Users: We use Get-MgUser -Top 10 to get the top 10 users.
  • Prepare Batch Requests: For each user, we create a request to get their manager. We assign a unique id to each request, starting from 1.
  • Send Batch Request: Use Invoke-MgGraphRequest to send the batch request to the $batch endpoint.
  • Process Responses:
    • We use the id from each response to match it back to the original user.
    • If the status is 200, we output the user's name and their manager's name.
    • If there's an error, we output the user's name and the status code.

Note on Batch Requestsโ€‹

  • Limitations: The maximum number of requests in a batch is 20.
  • Relative URLs: The url in each request should be relative to the version (e.g., /v1.0 is omitted).

๐Ÿค” Common Issues and Troubleshootingโ€‹

We all hit snags sometimes. Here are some common issues and how to tackle them.

Batch Request Errorsโ€‹

  • Incorrect URL: Ensure URLs in batch requests are relative and correctly formatted.
  • JSON Formatting: Use ConvertTo-Json with the right -Depth.
  • Content-Type Header: Set ContentType to 'application/json'.

Authentication Failuresโ€‹

  • Invalid Credentials: Double-check your ClientId, TenantId, and ClientSecret or CertificateThumbprint.
  • Insufficient Permissions: Verify that the app registration has the necessary API permissions.
  • Consent Issues: Ensure admin consent has been granted.

Cmdlet Not Foundโ€‹

  • Module Not Imported: Import the module with Import-Module Microsoft.Graph.
  • Incorrect Version: Verify you're using the correct module.
  • Cmdlet Name Changes: Use Find-MgGraphCommand to locate the correct cmdlet.

API Throttlingโ€‹

  • Too Many Requests: Implement retry logic with exponential backoff.
  • Optimize Code: Reduce unnecessary calls.

๐Ÿ“ข Best Practicesโ€‹

To wrap things up, here are some tips to keep you on the right track.

  • Use Least Privilege: Only request the permissions you need.
  • Secure Credentials: Store secrets securely, like in Azure Key Vault.
  • Follow Microsoft Guidelines: Stay updated with Microsoft Graph throttling guidance and service limits.
  • Error Handling and Logging: Use try-catch blocks and log important events.
  • Optimize Performance: Use server-side filtering and pagination.
  • Test Scripts: Always test in a non-production environment first.
  • Stay Updated: Regularly update the SDK modules.
  • Documentation and Comments: Document your scripts for clarity.

๐ŸŽฏ Wrapping Upโ€‹

Phew! That was a lot to cover, but you're now equipped to start using the Microsoft Graph PowerShell SDK like a pro.

Next Steps:

  • Explore More Cmdlets: Check out cmdlets for other services like SharePoint, Teams, and Outlook.
  • Automate Tasks: Identify tasks you can automate to save time.
  • Build Custom Tools: Create scripts and tools tailored to your organization's needs.

๐Ÿ“ Additional Resourcesโ€‹


โ“ Frequently Asked Questionsโ€‹

Q1: Can I use the SDK with PowerShell Core (PowerShell 7)?โ€‹

Absolutely! The SDK is compatible with PowerShell 7, and I recommend using it for the latest features and cross-platform support.

Q2: How do I update the SDK modules?โ€‹

Just run:

Update-Module Microsoft.Graph

Remember to restart your PowerShell session afterward.

Q3: Is it safe to use beta cmdlets in production?โ€‹

I wouldn't recommend it. Beta cmdlets access preview features that might change. Use them for testing and development only.

Q4: How can I contribute to the SDK?โ€‹

You can submit issues, feedback, or pull requests on the GitHub repository. Contributions are always welcome!

Q5: Can I use the SDK to manage other Microsoft 365 services?โ€‹

Yes! The SDK covers a wide range of services, including SharePoint, Teams, OneDrive, Outlook, and more.


๐Ÿ“ˆ Benefits of Using Microsoft Graph PowerShell SDKโ€‹

  • Unified Management: Manage multiple services from one place.
  • Automation: Save time by automating tasks.
  • Scalability: Handle large operations with ease.
  • Batch Processing: Optimize performance.
  • Community Support: Benefit from a strong community and official support.
  • Cross-Platform Compatibility: Use it on Windows, macOS, and Linux.

๐Ÿ’ก Final Thoughtsโ€‹

Embracing the Microsoft Graph PowerShell SDK opens up a world of possibilities. From automating mundane tasks to managing devices and services efficiently, it's a tool that every IT professional should have in their arsenal.

So, what are you waiting for? Dive in, experiment, and see how the SDK can transform your IT management experience.

Happy scripting! ๐ŸŽ‰