/
/

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

Microsoft Graph API is a unified endpoint that gives administrators programmatic access to different 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’re going to 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.

📌 Recommended deployment strategies:

Click to Choose a Method

💻

Best for Individual Users

💻💻💻

Best for Enterprises

Install Microsoft Graph PowerShell SDK
Connect to Microsoft Graph PowerShell SDK
Retrieve device information and compliance status
Monitor user activity and licensing
Automate remediation and policy enforcement
Validate policies at the endpoint level (Windows Registry, CMD)
Secure token usage with GPO and endpoint controls

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” = “<AADGroupId>” }

Change <PolicyID> to the Policy ID of the policy you want to assign. Change <AADGroupId> 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 validate if 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 your 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, typedsregcmd /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 that the device is not managed in Intune, or it’s 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 being made.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

You might also like

Ready to simplify the hardest parts of IT?