Microsoft 365 / Microsoft Graph PowerShell: export users to CSV and manage licenses
Microsoft Graph PowerShell lets you query Microsoft 365 users and automate account and license administration. Start with installing the required modules → connecting with read permissions → confirming the target organization → exporting users to a CSV (comma-separated values) file. The read-only exercise and the account or license change examples below require different permissions and have different effects, so run them separately.
What is Microsoft Graph PowerShell?
Microsoft Graph is an API (Application Programming Interface, an interface for communication between programs) that handles data from Microsoft Entra ID, Teams, SharePoint, and more. The Graph PowerShell SDK (Software Development Kit) allows you to use this API through PowerShell commands. The current name of the directory service, previously referred to as Azure Active Directory or Azure AD in older documents, is Microsoft Entra ID.
Installing Graph does not mean you can use all Microsoft 365 management commands. Some tasks, such as Exchange Online–specific management commands, require separate modules and connections. This article covers Interactive Delegated Authentication using the Microsoft Graph v1.0 module. App-only authentication for unattended scheduled tasks requires separate design considerations such as app permissions and certificates and is different from running scheduled tasks using the same user login examples.
Requirements and Module Installation
Microsoft recommends PowerShell 7 or later. Perform the following exercises in a supported PowerShell 7 environment. Windows PowerShell 5.1 requires separate .NET Framework, PowerShellGet, and other prerequisites, and modules installed in one version are not automatically installed in another version. First, check SDK installation requirements.
- Open PowerShell on an organization-approved administration PC. Check its version with
$PSVersionTable.PSVersion. - In the Microsoft Entra admin center, check the target tenant ID under Entra ID → Overview. This is especially important if your account has access to multiple organizations.
- Confirm admin consent for Graph permissions and your own administrative role. Use the company or school account of your organization instead of a regular Microsoft personal account.
- Create a restricted folder to store the result files. Since the user list contains names and account addresses, do not use public storage or public web folders.
To install only the modules needed for the current user scope, run as follows. If an installation confirmation message appears, check the repository and packages. Installing the full Microsoft.Graph module is also possible, but for this exercise, the submodules below are sufficient.
Install-Module -Name Microsoft.Graph.Authentication,Microsoft.Graph.Users,Microsoft.Graph.Identity.DirectoryManagement,Microsoft.Graph.Users.Actions -Scope CurrentUser -Repository PSGallery
After installation, check the available versions and command names using the following command. At this step, it does not connect to organizational data.
Get-Module -ListAvailable Microsoft.Graph.Authentication,Microsoft.Graph.Users,Microsoft.Graph.Identity.DirectoryManagement,Microsoft.Graph.Users.Actions | Select-Object Name,Version
Get-Command Connect-MgGraph,Get-MgUser,Get-MgSubscribedSku,Set-MgUserLicense
If modules or scripts are blocked due to the execution policy, first check the execution policy section. Do not treat a policy error as an issue like a 403 permission error.
Distinguishing connection permissions and admin roles
Delegated authentication is a method that works on behalf of the logged-in user. -Scopes is the Graph permission scope requested by the app, and it must also meet the role/target scope of the logged-in admin and admin consent. Simply writing a name in -Scopes does not automatically approve that permission or create an admin role.
| Tasks | Graph permissions requested in the example | Additional checks |
|---|---|---|
| View user list and specified attributes | User.Read.All |
Administrator consent and limitation of attributes to query |
| Query subscription SKUs and user licenses | LicenseAssignment.Read.All |
Roles supported by the API, such as Directory Readers |
| Create cloud users | User.Create |
Administrator consent and user management permissions and targets |
| Assign and revoke licenses | LicenseAssignment.ReadWrite.All |
Supported roles, such as License Administrator |
For read practice, there is no need to request group modification permissions or full directory write permissions together. Delegated versus application permissions and administrator consent requirements can be checked in Microsoft Graph permissions reference.
To test individual query commands, connect as shown below. The tenant ID you enter should be the actual value confirmed in your organization, and after logging in, check Account·TenantId·Scopes. The login method may use a browser or Windows authentication window depending on the installed version and environment.
$tenantId = Read-Host 'Target tenant ID'
Connect-MgGraph -TenantId $tenantId -Scopes 'User.Read.All' -ContextScope Process
Get-MgContext | Select-Object Account,TenantId,AuthType,Scopes
-ContextScope Process limits the authentication context to the current PowerShell process. When Connect-MgGraph is called without explicit scopes, inspect the actual context rather than assuming its permission is always User.Read. To change accounts or scopes, run Disconnect-MgGraph and reconnect with the required scopes. See the Graph PowerShell authentication guide.
Full example of user lookup and CSV saving
Get-MgUser -All continuously retrieves user lists returned in pages. However, this does not mean it automatically receives all properties. Select-Object * only expands the properties of objects already received, and values not included in the default return must be requested from the server with -Property. This difference is explained in Get-MgUser description.
Save the following full code as UTF-8 with m365-users-report.ps1. The script reads user information, creates a CSV with timestamps in the same folder, and disconnects the session. It does not change accounts or licenses. If you have done previous connection practice, first terminate it with Disconnect-MgGraph and then run this.
param(
[Parameter(Mandatory)]
[Guid]$TenantId
)
$ErrorActionPreference = 'Stop'
$connected = $false
$file = Join-Path $PSScriptRoot ("m365-users-{0}.csv" -f (Get-Date -Format 'yyyyMMdd-HHmmss'))
try {
Connect-MgGraph -TenantId $TenantId.ToString() -Scopes 'User.Read.All' -ContextScope Process -NoWelcome
$connected = $true
$context = Get-MgContext
if ($context.TenantId -ne $TenantId.ToString()) {
throw 'The connected tenant does not match the requested tenant.'
}
$properties = 'Id','DisplayName','UserPrincipalName','Mail','AccountEnabled','UsageLocation','AssignedLicenses'
$users = @(Get-MgUser -All -Property $properties)
if ($users.Count -eq 0) {
throw 'No users were returned. Check the connection and permissions.'
}
$report = @($users | Select-Object Id,DisplayName,UserPrincipalName,Mail,AccountEnabled,UsageLocation,
@{Name='AssignedSkuCount';Expression={ @($_.AssignedLicenses | Where-Object { $null -ne $_ }).Count }})
$report | Export-Csv -Path $file -NoTypeInformation -Encoding utf8BOM -NoClobber
Write-Host ("Saved: {0} / User count: {1}" -f $file, $report.Count)
$report | Select-Object -First 5 | Format-Table DisplayName,UserPrincipalName,AssignedSkuCount -AutoSize
}
finally {
if ($connected) {
Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null
}
}
After moving to the folder where the file is located in PowerShell, execute as follows. Adjust the file path to the actual saved location, and paste your organization's tenant ID into the input field.
$targetTenant = Read-Host 'Target tenant ID'
.\m365-users-report.ps1 -TenantId $targetTenant
If successful, the CSV path and the number of users will be displayed, and the first five users will be shown on the screen. Compare the number of rows in the file with the number of users on the screen, and check the display name, login address, usage location, and license of one known test account against the admin center. AssignedSkuCount represents the number of assigned product SKUs, not the number of individual services or purchased seats.
Even if there are users with an empty Mail, do not immediately assume query failure. The login name, UserPrincipalName, and the email address are different attributes. Even if AccountEnabled is true, actual login or service use may be restricted due to licenses, policies, or risk assessments. Do not conclude from this report alone that a user has recently logged in or is performing work normally.
If no results are returned or CSV generation fails, do not mark it as completed. Check permissions for the output path, files with the same name, file locks, and error messages. Since the report reflects the query results at the time of execution, if accounts have changed, run it again for comparison, and manage previous files according to your organization's retention policy.
Querying license products and user assignments
SKU (Stock Keeping Unit) is the unit used here to distinguish licensed products. SkuPartNumber is the product identification string, and SkuId is the product globally unique identifier (GUID) used in Graph commands. When changing a user's assignment, distinguish it so that you do not enter the subscription object ID or service plan ID instead of the SKU ID.
The entire CSV script disconnects at the end, so when executing the individual commands below, reconnect each time. In addition to read permissions, the role supported by that operation is required to query subscription SKUs. Check Roles and Permissions for Subscription SKU Query API.
$tenantId = Read-Host 'Target tenant ID'
Connect-MgGraph -TenantId $tenantId -Scopes 'User.Read.All','LicenseAssignment.Read.All' -ContextScope Process
Get-MgContext | Select-Object Account,TenantId,Scopes
Get-MgSubscribedSku -All | Select-Object SkuPartNumber,SkuId,CapabilityStatus,ConsumedUnits,@{Name='EnabledUnits';Expression={$_.PrepaidUnits.Enabled}}
$userId = Read-Host 'User principal name (UPN) or object ID to inspect'
Get-MgUserLicenseDetail -UserId $userId -All | Select-Object SkuPartNumber,SkuId,ServicePlans
ConsumedUnits is the number of consumed licenses, and PrepaidUnits.Enabled is the units provided as available. Since there may be suspended, warning states, and product conditions, do not immediately interpret the simple difference as the billed quantity or remaining seats for all products. Actual purchase and billing details should be separately confirmed through Subscription, Billing, and License Quantity Reconciliation Procedure.
Get-MgUserLicenseDetail includes licenses directly assigned and inherited from groups. You cannot distinguish the cause of the assignment from this result alone. For group-based assignments, additionally check the admin center or assignment status information. In User License Details API, you can also verify delegated permissions and supported roles.
Execute user and license change operations separately.
The following example shows an operation that modifies organizational data. Do not run it in batch immediately after the read report; reconnect with the necessary permissions after preparing an approved test user and records before the changes. The -WhatIf option below allows you to preview the operation you want to execute and is not a mock test that verifies all server validations, permissions, and license conditions.
Create a cloud test user.
Use this method only for cloud-managed users. In a synchronized organization, first determine whether accounts must be created in the source directory. Choose a unique user principal name (UPN, the sign-in name) within a domain verified in the tenant, and a temporary password that satisfies its password policy. Creating a member user differs from inviting an external collaboration guest. Review the user creation API requirements and permissions, including the least-privileged creation permission User.Create, and confirm the administrative role and target scope.
Disconnect-MgGraph
$tenantId = Read-Host 'Target tenant ID'
Connect-MgGraph -TenantId $tenantId -Scopes 'User.Create','User.Read.All' -ContextScope Process
Get-MgContext | Select-Object Account,TenantId,Scopes
$upn = Read-Host 'Test user UPN to create (verified domain)'
$nickname = Read-Host 'Mail nickname (for example, graph-test01)'
$securePassword = Read-Host 'Temporary password that meets policy' -AsSecureString
$params = @{
AccountEnabled = $true
DisplayName = 'Graph test user'
UserPrincipalName = $upn
MailNickname = $nickname
PasswordProfile = @{
Password = [System.Net.NetworkCredential]::new('', $securePassword).Password
ForceChangePasswordNextSignIn = $true
}
}
try {
New-MgUser -BodyParameter $params -WhatIf
}
finally {
$params.PasswordProfile.Password = $null
Remove-Variable securePassword
}
After verifying inputs and targets, to actually create the user, remove -WhatIf from the code and run it again. Do not hard-code passwords in command line strings or script files. Since SDK requests require plain text password values, do not use debug output or request body logging for this task, and deliver temporary passwords through the organization's approved channels.
After creation, verify the account again using Get-MgUser -UserId $upn -Property Id,DisplayName,UserPrincipalName,AccountEnabled. Simply creating a user does not automatically complete app licenses, mailboxes, or group memberships. Deleting a test account also requires data review similar to deleting a business account. Check offboarding and data handover procedures, then review and organize the target and recoverable scope in the admin center.
Reclaim directly assigned licenses
Before reclaiming, check the user, product, whether it was directly or group assigned, and data retention requirements. In this example, -RemoveLicenses passes an array of SKU ID strings, but does not include a hash table in @{SkuId=...} format. Use -AddLicenses @() together when there are no additional products to add. Check Set-MgUserLicense syntax.
Disconnect-MgGraph
$tenantId = Read-Host 'Target tenant ID'
Connect-MgGraph -TenantId $tenantId -Scopes 'LicenseAssignment.ReadWrite.All' -ContextScope Process
Get-MgContext | Select-Object Account,TenantId,Scopes
$userId = Read-Host 'Test user UPN or object ID for license removal'
$skuId = [Guid](Read-Host 'Verified SkuId to remove')
Set-MgUserLicense -UserId $userId -AddLicenses @() -RemoveLicenses @($skuId.ToString()) -WhatIf
Actual changes are executed by removing -WhatIf after approval and target verification. Consent and support roles such as License Administrator for LicenseAssignment.ReadWrite.All are required. For group-based assignment, do not attempt to handle it solely with the user direct reclaim command; review the original group assignment. Permissions, roles, and request format of the license assignment API serve as the standard.
After the change, reconnect with the necessary read permissions and compare the license details with the management center. During rollback, you need to verify the remaining seats, usage locations, and previously suspended service plans to reassign to the original configuration. Do not assume that reattaching the license will undo all previously executed data deletions. It is important to complete storage and handover before reclaiming.
Check the Windows execution policy and rollback
Execution policies are conditions for running scripts and modules. If a blocking error occurs in Windows, check the effective policy and values by scope.
Get-ExecutionPolicy
Get-ExecutionPolicy -List
Only if the organizational policy allows and the current user scope needs changes, record the previous values and review RemoteSigned. If settings are already allowed, do not change them just to match the format. If MachinePolicy and UserPolicy of the organizational group policy take precedence, check with the person in charge and do not bypass.
$previousUserPolicy = Get-ExecutionPolicy -Scope CurrentUser
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned
Get-ExecutionPolicy -List
To restore to the original value in the same session after work, execute as follows. If you need to restore in a new window, use the actual values recorded earlier. RemoteSigned does not mean that you trust all code received from the internet. Check the scope and priority of execution policies.
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy $previousUserPolicy
Common errors and task termination
| Symptoms | Verification Sequence |
|---|---|
| Command Not Recognized | Check the running PowerShell version and the module installation location. Get-MgUser is in Microsoft.Graph.Users. Use Get-Command to locate the command and distinguish between installation and import errors. |
| 403 or Insufficient Privileges | Verify the connected account, tenant, scopes, admin consent, and supported roles for the API. Do not add full write permissions by default. |
| Cannot Find User or Object | Check the organization and UPN/object ID, and deletion/synchronization status. Ensure that the account name is not from a different tenant. |
| Property is Empty | Distinguish whether the property was requested with -Property, whether the account actually has a value, and whether the property requires separate permissions. |
| Login Blocked | Record error codes and timestamps, and check conditional access, multifactor authentication (MFA), allowed authentication methods, and login logs. Do not disable security policies for successful login. |
Recording the installation version, detailed command errors, request ID, and occurrence time together can help with reproduction and support requests. Even when using the method in Graph PowerShell Error Diagnosis, do not share logs containing tokens, passwords, or personal information as-is.
After finishing individual command exercises, disconnect and check the storage location of the result files. Logging out is different from undoing account or license changes that have already been performed.
Disconnect-MgGraph




