/

Using Microsoft Graph API with Windows PowerShell to Monitor and Manage Microsoft 365 Clients

by Ann Conte, IT Technical Writer
Using Microsoft Graph API with Windows PowerShell to Monitor and Manage Microsoft 365 Clients blog banner image
Using Microsoft Graph API with Windows PowerShell to Monitor and Manage Microsoft 365 Clients blog banner image

Try our #1 rated endpoint management platform on G2

NinjaOne dashboard screenshot

Automate the Hardest Parts of IT

Key Points

  • Microsoft Graph API is a unified REST endpoint that provides programmatic access to Microsoft 365 services including Intune, Microsoft Entra ID, Exchange Online, and Teams.
  • MSPs and enterprise IT teams use Microsoft Graph API for device compliance monitoring, license usage auditing, automated policy enforcement, alert-triggered remediation workflows, and cross-tenant reporting dashboards.
  • Before connecting to the Microsoft Graph PowerShell SDK, you need a Microsoft 365 tenant with global admin or delegated admin access, the SDK installed with PowerShell 5.1 or later, and appropriate permission scopes granted for the operations you intend to perform.
  • Device compliance status, non-compliant device lists, and individual device details can all be retrieved with Get-MgDeviceManagementManagedDevice queries; remote wipe and lock actions can be triggered with Invoke-MgDeviceManagement commands.
  • Policies pushed via Microsoft Graph can be validated at the endpoint level by checking HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PolicyManager\current\device\ in the Windows Registry; device enrollment status is verified with dsregcmd /status.
  • Microsoft Graph authentication tokens should be protected using Local Group Policy to disable credential storage and restrict PowerShell execution to signed scripts only.

Microsoft Graph API is a unified endpoint that gives administrators programmatic access to various Microsoft 365 services, such as Intune, Microsoft Entra (formerly known as Azure AD), Exchange Online, Teams, and so much more, using Windows PowerShell.

It has many different use cases, especially in enterprise environments. Microsoft Graph API can be used for:

  • Device compliance and health monitoring
  • License usage and assignment
  • Automated policy and group management
  • Alerting and remediation workflows
  • Cross-tenant reporting for MSP dashboards

Prerequisites:

  • You must be a Microsoft 365 tenant with global admin or delegated admin access.
  • You need to register Microsoft Graph with Microsoft Entra (formerly known as Azure AD).
  • You may need Intune and Microsoft Entra Premium licenses for some actions.
  • You will need a GPO baseline to protect your authentication tokens and ensure that your script executions are secure.

For a quick visual overview, watch our video guide: Using Microsoft Graph API with Windows PowerShell to Monitor and Manage Microsoft 365 Clients.

How to install Microsoft Graph PowerShell SDK

Prerequisites:

  • It’s recommended that you use Windows PowerShell 7 or later for this. Windows PowerShell 5.1 is the minimum requirement. (Check your PowerShell Version )
  • You need to have .NET Framework 4.7.2 or later installed.
  • PowerShellGet should be updated to the latest version. To do that, type Install-Module PowerShellGet in Windows PowerShell and press Enter.
  • The execution policy must be set to remote signed or less restrictive. To check if you have the correct policy, type Get-ExecutionPolicy in Windows PowerShell and press Enter.To change the execution policy to remote signed, type Set-ExecutionPolicy -ExecutionPolicy RemoteSigned, and press Enter.

Steps:

  1. Open the Start Menu and search for Windows PowerShell.
  2. Right-click Windows PowerShell > Run as administrator.
  3. Type Install-Module Microsoft.Graph -Scope CurrentUser -Repository PSGallery -Force and press Enter.

Note: This change will only apply to the current user profile. If you want to install Microsoft Graph PowerShell SDK in all user profiles, change the -Scope to AllUsers.

  1. Confirm the installation when prompted.

How to connect to Microsoft Graph PowerShell SDK

  1. Type Connect-MgGraph -Scopes “User.Read.All”,”DeviceManagementManagedDevices.Read.All”,”Directory.Read.All” in Windows PowerShell and Press Enter to connect.

Note: This will give you access to the whole graph. You can change the permissions according to your needs by editing the permissions indicated after -Scopes. To check all available permissions, you can type Find-MgGraphCommand -command Get-MgGroup.

  1. If you’re already logged in, proceed to the next step. If you’re not, follow the prompts to log in.
  2. You can also use Get-MgContext to retrieve specific details, such as Client ID, tenant ID, scopes consented to, and more.

Note: You can use -TenantID for multi-tenant access and -ClientID for registered applications.

How to retrieve device information and compliance status

To list all of your Intune-managed devices, type this command and press Enter:

Get-MgDeviceManagementManagedDevice |
Select DisplayName, ComplianceState, OperatingSystem

If you want to find non-compliant devices within that list, type this command and press Enter:

Get-MgDeviceManagementManagedDevice |
Where-Object {$_.ComplianceState -ne “compliant”}

You can also find specific devices by searching for them by name:

Get-MgDeviceManagementManagedDevice -ManagedDeviceId <GUID>

Change <GUID> to the device ID you’re searching for.

How to monitor user activity and licensing

To list all users alongside their licensing details, type this command and press Enter:

Get-MgUser | Select-Object DisplayName, UserPrincipalName, AssignedLicenses

To find unlicensed users, type this command and press Enter:

Get-MgUser | Where-Object { !$_.AssignedLicenses }
Retrieve sign-in activity (requires AuditLog.Read.All):
Get-MgAuditLogSignIn -Top 50 | Select UserDisplayName, UserPrincipalName, Status, AppDisplayName

How to automate remediation and policy enforcement

If a device is lost or compromised, you can wipe its details from Microsoft Graph by typing this command and pressing Enter:

Invoke-MgDeviceManagementManagedDeviceWipe -ManagedDeviceId <GUID>

Replace <GUID> with the device ID of the lost or compromised device.

If you want to lock a device remotely:

Invoke-MgDeviceManagementManagedDeviceRemoteLock -ManagedDeviceId <GUID>

Replace <GUID> with the device ID of the lost or compromised device.

If you want to assign a compliance policy, type this command and press Enter:

New-MgDeviceManagementCompliancePolicyAssignment -CompliancePolicyId <PolicyID> -Target @{ “@odata.type” = “#microsoft.graph.groupAssignmentTarget”; “groupId” = “<EntraGroupId>” }

Change <PolicyID> to the Policy ID of the policy you want to assign. Change <EntraGroupId> to the group you want to assign the policy to.

These commands are useful if you wish to set up automated remediation across different environments. You can also trigger these automatically when your system receives an alert from your endpoint management tool.

How to validate policies at the endpoint level (Windows Registry, CMD)

You can verify whether the policies that were issued using Microsoft Graph were applied successfully by checking the Windows Registry.

For example, you can go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PolicyManager\current\device\ in the Windows Registry and see if the policies have been applied (e.g., Defender, Encryption Policy).

You can also use Command Prompt to enroll the device in an MDM to further monitor its status.

  1. Open Command Prompt as an administrator.
  2. Type this and press Enter: start ms-device-enrollment:?mode=mdm

To verify the join/enrollment status, type: dsregcmd /status

How to secure token usage with Local Group Policies and endpoint controls

You can use Local Group Policies to protect Microsoft Graph authentication tokens and PowerShell automation on your managed devices by following these steps:

  1. Open the Local Group Policy editor.
  2. Navigate to Computer Configuration > Windows Settings > Security Settings > Local Policies > Security Options
  3. Find Do not allow storage of passwords and credentials for network authentication and double-click.
  4. Set to Enabled.
  5. Click Apply > OK.
  6. Navigate to Computer Configuration > Administrative Templates > Windows Components > Windows PowerShell.
  7. Find Turn on Script Execution and double-click.
  8. Set to Enabled.
  9. Click the dropdown menu and select Allow only signed scripts.
  10. Click Apply > OK.

Additional considerations when using Microsoft Graph API

  • You can use Graph Explorer to test the API online without installing it on your devices.
  • Make sure to apply application permissions for background jobs and multi-tenant scripts.
  • You can apply rate limiting and retry logic for production scripts.
  • You can use Microsoft Entra ID conditional access policies to restrict Graph usage in unmanaged devices.

Troubleshooting Microsoft Graph API

IssuePossible CausesFixes
The Microsoft Graph fails.There are missing permissions, meaning that the tenant is not allowed to execute that command.Give that tenant the appropriate permissions. Alternatively, you can use an administrator account with full permissions.
The device is not visible in the query.This means the device is not managed in Intune, or is not properly synced.Check the Microsoft Endpoint Management (MEM) enrollment and the Microsoft Entra (formerly AAD) device status.
You hit the API rate limit.There are too many concurrent queries.Use the -Top command and batching.
The Registry values on a specific policy are missing.The policy was not applied.Validate group targeting and trigger sync to apply the change to the device.

NinjaOne services

NinjaOne complements the Microsoft Graph API in several ways by:

Monitor your managed devices using Microsoft Graph API

Microsoft Graph API is a powerful tool that gives administrators centralized and automated control of Microsoft 365 accounts under their organization using Windows PowerShell. After installing and connecting to it using PowerShell, you can use it to monitor users and device compliance, automate device actions and policy assignments.

You can validate these policy assignments by checking the Windows Registry and using Command Prompt. You can also enhance your workflows further using NinjaOne’s automation and visibility features.

Related Articles: 

Quick-Start Guide

NinjaOne’s capabilities with Microsoft Graph API and Windows PowerShell:

Microsoft Graph API Integration

NinjaOne does support integration with Microsoft Graph API and PowerShell, particularly for:

  1. Service Principal Authentication (SPA):
    • NinjaOne offers Service Principal Authentication for Microsoft 365 backups
    • Requires a global admin during initial setup
    • Supports various scopes and permissions for different Microsoft 365 services
  2. PowerShell Integration:
    • NinjaOne provides PowerShell modules and scripts for API interactions
    • Supports OAuth 2.0 authorization flow
    • Offers sample scripts for automating tasks like:
      • Vulnerability management
      • Token generation
      • API request handling

Key Considerations

  • The integration allows monitoring and managing Microsoft 365 clients
  • Supports operations like:
    • Backup and restore
    • User management
    • Device information retrieval
    • Authorization and token management

FAQs

Microsoft Graph API (via the Microsoft Graph PowerShell SDK) is the current, unified interface for all Microsoft 365 services and provides access to Intune, Entra ID, Exchange Online, Teams, and SharePoint through a single, consistent API. Azure AD PowerShell (the AzureAD and MSOnline modules) was the legacy approach for identity and directory management only. Any scripts or automation that use the AzureAD or MSOnline modules must be migrated to Graph SDK equivalents before they stop working in your tenant.

The minimum required permission scopes for Intune device management via Microsoft Graph are DeviceManagementManagedDevices.Read.All for read-only compliance and status data, DeviceManagementManagedDevices.ReadWrite.All for remote actions (wipe, lock), and DeviceManagementConfiguration.ReadWrite.All for creating and assigning compliance policies. For user and licensing queries, User.Read.All is required for sign-in audit log access, AuditLog.Read.All must be granted.

Yes. You can use the -TenantId parameter in Connect-MgGraph to specify a customer tenant, or register a multi-tenant application in Microsoft Entra ID that customers explicitly grant consent to through an admin consent URL. RMM platforms like NinjaOne can also automate Microsoft Graph script execution across all managed tenants simultaneously, eliminating manual per-client connection steps.

The Microsoft Graph PowerShell SDK wraps the Microsoft Graph REST API in PowerShell cmdlets. The SDK handles authentication, token refresh, pagination, and error handling automatically, making it significantly easier for IT admins and MSPs.

When you exceed the Graph API rate limit, the API returns a 429 Too Many Requests response with a Retry-After header indicating how long to wait. In production scripts, implement retry logic that catches 429 responses, reads the Retry-After value, sleeps for the specified duration, and retries the request. For bulk operations, use the -Top parameter to limit result set sizes, use the Microsoft Graph Batch API ($batch endpoint) to combine multiple requests into a single call, and stagger script execution schedules across tenants so they do not all run simultaneously.

You might also like

Ready to simplify the hardest parts of IT?