| Export Conditional Access policiesRead-onlyOfficial Microsoft sample | Conditional Access & policies | Backup CA policies and see inclusions and exclusions without clicking through the portal. Details, command and permissionsWhat it doesRetrieves Conditional Access policies from your tenant with Microsoft Graph PowerShell (Get-MgIdentityConditionalAccessPolicy). A JSON export includes user, group, and role inclusions and exclusions. Why admins use itYou get a backup before a change, and a single place to review who is excluded from CA. SourceModules and permissionsMicrosoft.Graph.Identity.SignIns. Scopes documented on these pages: Policy.Read.All and/or Policy.Read.ConditionalAccess. LicenseConditional Access requires Microsoft Entra ID P1 or P2. Confirm current CA licensing when you run it. Last checkedDecember 1, 2026 CaveatsThis is a documented cmdlet and API example, not a standalone .ps1 file. There is no official Graph PowerShell "what-if" sample; use the portal for what-if. Exclusions come from the exported policy objects; there is no separate official exclusions-only script. |
| Export named locationsRead-onlyMicrosoft Learn cmdlet example | Conditional Access & policies | List the IP ranges and countries your Conditional Access policies use as named locations. Details, command and permissionsWhat it doesGet-MgIdentityConditionalAccessNamedLocation lists every named location (IP ranges and countries). The API page also shows a filter for IP-based locations only. Why admins use itReview trusted IP ranges and country lists before you change a location-based policy, and keep a copy. CommandConnect-MgGraph -Scopes "Policy.Read.All"
Get-MgIdentityConditionalAccessNamedLocation | ConvertTo-Json -Depth 10 | Out-File named-locations.json
SourceModules and permissionsMicrosoft.Graph.Identity.SignIns. Least-privileged permission on the API page: Policy.Read.All. LicenseNamed locations are used by Conditional Access, which needs Microsoft Entra ID P1. The API page states no separate license. Last checkedDecember 1, 2026 CaveatsRead-only. Named locations only matter where a policy references them; pair it with the Conditional Access export. |
| Check whether security defaults are onRead-onlyMicrosoft Learn cmdlet example | Conditional Access & policies | Read the security defaults policy and see if IsEnabled is true. Details, command and permissionsWhat it doesGet-MgPolicyIdentitySecurityDefaultEnforcementPolicy returns the identitySecurityDefaultsEnforcementPolicy object, including whether security defaults are enabled. Why admins use itA quick, scriptable check across tenants before you plan Conditional Access. CommandConnect-MgGraph -Scopes "Policy.Read.All"
Get-MgPolicyIdentitySecurityDefaultEnforcementPolicy | Select-Object DisplayName, IsEnabled
SourceModules and permissionsMicrosoft.Graph.Identity.SignIns. Least-privileged permission on the API page: Policy.Read.All. LicenseNo license requirement is stated on the API page. Last checkedDecember 1, 2026 CaveatsRead-only. Changing security defaults is done in the admin center by at least a Conditional Access Administrator. |
| Export tenant authorization settings (who can invite guests, guest role)Read-onlyMicrosoft Learn cmdlet example | Conditional Access & policies | See who can invite guests, what role guests get, and the default user permissions. Details, command and permissionsWhat it doesGet-MgPolicyAuthorizationPolicy returns the tenant's authorizationPolicy, including allowInvitesFrom (who can invite guests), guestUserRoleId (the role guests get) and defaultUserRolePermissions. Why admins use itAnswers "who can invite guests?" and "what can guests see?" without clicking through several admin pages. CommandConnect-MgGraph -Scopes "Policy.Read.All"
Get-MgPolicyAuthorizationPolicy | Select-Object AllowInvitesFrom, GuestUserRoleId, DefaultUserRolePermissions | Format-List
SourceModules and permissionsMicrosoft.Graph.Identity.SignIns. Least-privileged permission on the API page: Policy.Read.All. LicenseNo license requirement is stated on the API page. Last checkedDecember 1, 2026 CaveatsRead-only. guestUserRoleId is a role template ID; the resource page lists which ID means which guest access level. |
| Export cross-tenant access settings (default and partners)Read-onlyMicrosoft Learn cmdlet example | Conditional Access & policies | List the default inbound/outbound B2B settings and every partner organization you configured. Details, command and permissionsWhat it doesGet-MgPolicyCrossTenantAccessPolicyDefault returns the default cross-tenant access settings; Get-MgPolicyCrossTenantAccessPolicyPartner lists partner-specific configurations, including inbound trust settings. Why admins use itShows which partners you trust for MFA or device claims, and any overrides from the defaults. CommandConnect-MgGraph -Scopes "Policy.Read.All"
Get-MgPolicyCrossTenantAccessPolicyDefault | ConvertTo-Json -Depth 10 | Out-File cta-default.json
Get-MgPolicyCrossTenantAccessPolicyPartner -All | ConvertTo-Json -Depth 10 | Out-File cta-partners.json
SourceModules and permissionsMicrosoft.Graph.Identity.SignIns. Least-privileged permission on both API pages: Policy.Read.All. LicenseNo license requirement is stated on these API pages. Last checkedDecember 1, 2026 CaveatsRead-only. See the cross-tenant access guide before changing trust settings. |
| Export authentication strength policiesRead-onlyNot tested against a live tenant | Conditional Access & policies | List built-in and custom authentication strengths and the method combinations each one allows, before you use a strength in Conditional Access. Details, command and permissionsWhat it doesLists built-in and custom authentication strength policies, including the allowed method combinations. This is the catalog of strengths you can require in Conditional Access, not a backup of the Conditional Access policies themselves (see Export Conditional Access policies) and not the Authentication methods policy that turns methods on or off (see Export the Authentication methods policy). Requirements- Module: Microsoft.Graph.Identity.SignIns
- Connect-MgGraph scopes (least privilege):
Policy.Read.AuthenticationMethod (the List API also allows Policy.Read.All as a higher privileged permission) - Least-privileged admin role: Security Reader (the API also lists Conditional Access Administrator and Security Administrator)
- License: Conditional Access and authentication strength require Microsoft Entra ID P1
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-11-27
Command# Read-only. Not tested against a live tenant.
# List authentication strength policies (built-in and custom).
# Docs: GET /policies/authenticationStrengthPolicies
Import-Module Microsoft.Graph.Identity.SignIns
Connect-MgGraph -Scopes "Policy.Read.AuthenticationMethod"
$policies = Get-MgPolicyAuthenticationStrengthPolicy -All
$report = $policies | ForEach-Object {
[pscustomobject]@{
Id = $_.Id
DisplayName = $_.DisplayName
Description = $_.Description
PolicyType = $_.PolicyType
RequirementsSatisfied = $_.RequirementsSatisfied
AllowedCombinations = ($_.AllowedCombinations -join '; ')
CreatedDateTime = $_.CreatedDateTime
ModifiedDateTime = $_.ModifiedDateTime
}
}
$report | Sort-Object PolicyType, DisplayName |
Export-Csv -Path ".\authentication-strength-policies.csv" -NoTypeInformation -Encoding UTF8
$report | Format-Table DisplayName, PolicyType, RequirementsSatisfied -AutoSize
Sample output columns- Id: Policy object ID (use this value in a Conditional Access grant control)
- DisplayName: Strength name, for example Multifactor authentication or Phishing-resistant MFA
- Description: Policy description
- PolicyType:
builtIn or custom - RequirementsSatisfied: For example
mfa - AllowedCombinations: Method combinations that satisfy the strength, joined with
; - CreatedDateTime, ModifiedDateTime: When the policy was created or last changed
Gotchas- This export does not tell you which Conditional Access policies use a strength. Pair it with Export Conditional Access policies.
-All pages through the full list. The built-in set is small; custom policies add to it.- The List API example also shows a filter on
allowedCombinations, for example allowedCombinations/any(x:x has 'sms, password').
Microsoft Learn sources |
| MFA and authentication methods registration reportRead-onlyOfficial Microsoft sample | MFA & auth methods | See who still has no MFA method registered before you tighten Conditional Access. Details, command and permissionsWhat it doesGet-MgReportAuthenticationMethodUserRegistrationDetail returns per-user registration details, including whether the user is MFA-capable. That is the official bulk report, instead of calling authentication methods one user at a time. Why admins use itGives a tenant-wide answer to who still has no MFA method registered. SourceModules and permissionsMicrosoft.Graph.Reports. Permissions documented on the API and cmdlet pages include AuditLog.Read.All. LicenseThe Authentication Methods Activity page states a Microsoft Entra ID P1 or P2 license is required to access Usage and insights. Confirm the same license bar still applies to this Graph report when you run it. Last checkedDecember 1, 2026 Caveats"MFA capable" is not the same as "protected by a Conditional Access policy that requires MFA." Use this with the CA policy export, not instead of it. This is a documented cmdlet example, not a standalone .ps1 file. |
| Per-user MFA state reportRead-onlyOfficial Microsoft sample | MFA & auth methods | See who is still enabled or enforced for per-user MFA when you move to Conditional Access. Details, command and permissionsWhat it doesOfficial Microsoft Entra PowerShell how-to. The reporting section shows how to read per-user MFA state with Connect-Entra (scopes User.Read.All, UserAuthenticationMethod.Read.All, Policy.Read.All), Get-EntraUser, and Get-EntraBetaUserAuthenticationRequirement (PerUserMFAState). It also describes Get-EntraAuthenticationMethodUserRegistrationDetailReport / isMfaCapable as a performant tenant-wide report. Why admins use itNeeded when leaving per-user MFA or Security Defaults and moving enforcement to Conditional Access. SourceMicrosoft Learn: Manage per-user MFA with Microsoft Entra PowerShell (opens in a new tab) Modules and permissionsMicrosoft Entra PowerShell (Connect-Entra). Report scopes: User.Read.All, UserAuthenticationMethod.Read.All, Policy.Read.All. LicenseA P1 requirement is not stated on this how-to (per-user MFA is a directory setting). Confirm current licensing when you run it. Last checkedDecember 1, 2026 CaveatsThe report examples are read-only. The same page also documents Update-EntraBetaUserAuthenticationRequirement, which makes changes (Policy.ReadWrite.AuthenticationMethod); that cmdlet is listed under Related change-making samples. Microsoft Entra PowerShell is the current Microsoft-owned module that sits on Graph. Do not use the retired MSOnline module to read StrongAuthenticationRequirements. The page mentions Get-MsolUser only as the legacy equivalent being replaced. |
| Export the Authentication methods policyRead-onlyMicrosoft Learn cmdlet example | MFA & auth methods | See which sign-in methods are enabled and for whom, before and after a migration. Details, command and permissionsWhat it doesGet-MgPolicyAuthenticationMethodPolicy returns the tenant's authenticationMethodsPolicy, including each method configuration. Why admins use itKeep a copy before you change methods, and confirm what the policy really allows after the per-user MFA and SSPR migration. CommandConnect-MgGraph -Scopes "Policy.Read.AuthenticationMethod"
Get-MgPolicyAuthenticationMethodPolicy | ConvertTo-Json -Depth 10 | Out-File auth-methods-policy.json
SourceModules and permissionsMicrosoft.Graph.Identity.SignIns. Least-privileged permission on the API page: Policy.Read.AuthenticationMethod. LicenseNo license requirement is stated on the API page. Last checkedDecember 1, 2026 CaveatsRead-only. |
| List one user's registered authentication methodsRead-onlyMicrosoft Learn cmdlet example | MFA & auth methods | See what a user has registered (Authenticator, phone, passkey and so on) before you reset or troubleshoot MFA. Details, command and permissionsWhat it doesGet-MgUserAuthenticationMethod lists the authentication methods registered to a user; a UPN can be used as -UserId. Why admins use itFaster than opening the portal when a user says they lost their phone or can't complete MFA. CommandConnect-MgGraph -Scopes "UserAuthenticationMethod.Read.All"
Get-MgUserAuthenticationMethod -UserId user@contoso.com
SourceModules and permissionsMicrosoft.Graph.Identity.SignIns. For other users, the least-privileged permission is UserAuthenticationMethod.Read.All; supported least-privileged roles are Global Reader, Authentication Administrator and Privileged Authentication Administrator. LicenseNo license requirement is stated on the API page. Last checkedDecember 1, 2026 CaveatsRead-only. The API page notes that an Authentication Administrator sees phone numbers masked. |
| Update per-user MFA stateChanges dataOfficial Microsoft sample | MFA & auth methods | Change a user's per-user MFA state with Microsoft Entra PowerShell. Details, command and permissionsWhat it doesDocumented on the same Entra PowerShell page as the per-user MFA report, as Update-EntraBetaUserAuthenticationRequirement with Policy.ReadWrite.AuthenticationMethod. Why admins use itOnly relevant if you still have to change a leftover per-user MFA setting. Microsoft's own page prefers Conditional Access or Security Defaults for enforcement. SourceMicrosoft Learn: Manage per-user MFA with Microsoft Entra PowerShell (opens in a new tab) Modules and permissionsMicrosoft Entra PowerShell. The update cmdlet uses Policy.ReadWrite.AuthenticationMethod. LicenseA P1 requirement is not stated on this how-to. Confirm current licensing when you run it. Last checkedDecember 1, 2026 CaveatsThis makes changes. Do not treat it as a recommended hardening script. Prefer Conditional Access or Security Defaults for enforcement. |
| Create a Temporary Access Pass for a userChanges dataMicrosoft Learn cmdlet example | MFA & auth methods | Issue a time-limited pass so a user can sign in and register Authenticator or a passkey. Details, command and permissionsWhat it doesNew-MgUserAuthenticationTemporaryAccessPassMethod creates a temporaryAccessPassMethod for a user. The API page example sets startDateTime, lifetimeInMinutes and isUsableOnce. Why admins use itOnboarding and recovery without a password or a working MFA method. Command (dry run first)Connect-MgGraph -Scopes "UserAuthenticationMethod.ReadWrite.All"
# Dry run first: confirm the user and preview the call
Get-MgUserAuthenticationMethod -UserId user@contoso.com
New-MgUserAuthenticationTemporaryAccessPassMethod -UserId user@contoso.com -BodyParameter @{ lifetimeInMinutes = 60; isUsableOnce = $true } -WhatIf
Dry run firstList the user's current methods and confirm the Temporary Access Pass policy is enabled (Export the Authentication methods policy), then run the create with -WhatIf before running it for real. SourceModules and permissionsMicrosoft.Graph.Identity.SignIns. Permissions listed on the API page include UserAuthMethod-TAP.ReadWrite.All and UserAuthenticationMethod.ReadWrite.All; supported least-privileged roles are Authentication Administrator and Privileged Authentication Administrator. LicenseNo license requirement is stated on the API page. Last checkedDecember 1, 2026 CaveatsChanges data: creates a credential. Hand the pass over securely; the Temporary Access Pass policy must be enabled first. |
| Users whose only MFA methods are SMS or voiceRead-onlyNot tested against a live tenant | MFA & auth methods | From the authentication methods registration report, list users who are MFA-registered but only appear to have phone-based methods, so you can move them to Authenticator or a passkey. Details, command and permissionsWhat it doesThis uses the same official registration report as MFA and authentication methods registration report (Get-MgReportAuthenticationMethodUserRegistrationDetail). That live script answers "who has no MFA method registered?" This one keeps users who are MFA-registered (isMfaRegistered eq true) and then filters to people who look phone-based, so you can move them off SMS or voice. The v1.0 userRegistrationDetails resource documents methodsRegistered with examples including mobilePhone, email, and passKeyDeviceBound. The List API examples also return microsoftAuthenticatorPush and softwareOneTimePasscode. Preferred second-factor values that are fully enumerated are push, oath, voiceMobile, voiceAlternateMobile, voiceOffice, sms, none, and unknownFutureValue (userRegistrationDetails resource (opens in a new tab)). The script only treats those documented method strings as known. email appears in the resource examples, but it is not treated here as a second-factor MFA method, so it does not exclude a user from this list. Review the raw methodsRegistered column before you act. Requirements- Module: Microsoft.Graph.Reports
- Connect-MgGraph scopes (least privilege):
AuditLog.Read.All - Least-privileged admin role: Security Reader (the List API also lists Security Administrator; the Authentication Methods Activity page lists additional roles that can open the related report)
- License: A Microsoft Entra ID P1 or P2 license is required to access Authentication Methods Activity / Usage and insights (Authentication methods activity (opens in a new tab))
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-11-27
Command# Read-only. Not tested against a live tenant.
# Same report as /scripts#mfa-registration-report, different filter:
# MFA-registered users who do not have documented Authenticator, OTP, or
# passkey methods, and who have mobilePhone and/or a phone preferred method.
# Docs: GET /reports/authenticationMethods/userRegistrationDetails
Import-Module Microsoft.Graph.Reports
Connect-MgGraph -Scopes "AuditLog.Read.All"
# Method strings documented on the v1.0 resource or List API examples
# that indicate a registered method other than SMS/voice phone.
$documentedNonPhoneMethods = @(
'microsoftAuthenticatorPush',
'softwareOneTimePasscode',
'passKeyDeviceBound'
)
$phonePreferred = @('sms', 'voiceMobile', 'voiceAlternateMobile', 'voiceOffice')
$registered = Get-MgReportAuthenticationMethodUserRegistrationDetail -All -Filter "isMfaRegistered eq true"
$report = foreach ($user in $registered) {
$methods = @($user.MethodsRegistered)
$hasDocumentedNonPhone = $methods | Where-Object { $documentedNonPhoneMethods -contains $_ }
$preferred = [string]$user.UserPreferredMethodForSecondaryAuthentication
$hasMobilePhone = $methods -contains 'mobilePhone'
$preferredIsPhone = $phonePreferred -contains $preferred
if (-not $hasDocumentedNonPhone -and ($hasMobilePhone -or $preferredIsPhone)) {
[pscustomobject]@{
UserPrincipalName = $user.UserPrincipalName
UserDisplayName = $user.UserDisplayName
UserType = $user.UserType
IsAdmin = $user.IsAdmin
IsMfaRegistered = $user.IsMfaRegistered
IsMfaCapable = $user.IsMfaCapable
IsPasswordlessCapable = $user.IsPasswordlessCapable
MethodsRegistered = ($methods -join '; ')
PreferredSecondaryMethod = $preferred
LastUpdatedDateTime = $user.LastUpdatedDateTime
}
}
}
$report | Sort-Object UserPrincipalName |
Export-Csv -Path ".\sms-voice-only-mfa-users.csv" -NoTypeInformation -Encoding UTF8
"MFA-registered users in report: $($registered.Count)"
"Users matching the phone-only filter: $($report.Count)"
Sample output columns- UserPrincipalName, UserDisplayName, UserType: Who the row is for
- IsAdmin: Whether the user has an admin role in the tenant
- IsMfaRegistered, IsMfaCapable: Registered for MFA, and capable under current policy
- IsPasswordlessCapable: Whether a policy-allowed passwordless method is registered
- MethodsRegistered: Raw registered-method strings from the report
- PreferredSecondaryMethod:
userPreferredMethodForSecondaryAuthentication (sms, voiceMobile, and so on) - LastUpdatedDateTime: When the report last updated this user (the activity article says the report updates for most users within 36 hours)
Gotchas- This is not "who has no MFA." For unregistered users, use MFA and authentication methods registration report.
isMfaCapable is not the same as "protected by a Conditional Access policy that requires MFA."- Because v1.0 does not publish a complete
methodsRegistered enumeration, a user could have an undocumented strong method and still match this filter, or a voice-only user might be missed if they have neither mobilePhone nor a documented phone preferred method. Always read MethodsRegistered. -All pages the full tenant report and can take a while in large tenants.
Microsoft Learn sources |
| Admins who aren't MFA-capableRead-onlyNot tested against a live tenant | MFA & auth methods | From the authentication methods registration report, list users with an admin role, sorted so admins who aren't MFA-capable come first, with their registered methods and preferred second factor. Details, command and permissionsWhat it doesThe MFA and authentication methods registration report covers every user. This script narrows it to accounts where isAdmin is true, then puts the ones that aren't MFA-capable at the top. isAdmin "indicates whether the user has an admin role in the tenant" and is meant for checking what privileged accounts are registered for (userRegistrationDetails resource type (opens in a new tab)). Requirements- Modules: Microsoft.Graph.Reports
- Connect-MgGraph scopes (least privilege):
AuditLog.Read.All (List userRegistrationDetails (opens in a new tab)) - Least-privileged admin role: Reports Reader, Security Reader, Security Administrator or Global Reader are among the supported roles on the List API.
- License: A Microsoft Entra ID P1 or P2 license is required for Authentication methods activity / Usage and insights (Authentication methods activity (opens in a new tab)).
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-12-02
Command# Read-only. Not tested against a live tenant.
# isAdmin isn't listed as a $filter property on the List API, so it's filtered in memory.
Import-Module Microsoft.Graph.Reports
Connect-MgGraph -Scopes "AuditLog.Read.All"
$admins = Get-MgReportAuthenticationMethodUserRegistrationDetail -All |
Where-Object { $_.IsAdmin }
$report = foreach ($a in $admins) {
[pscustomobject]@{
UserPrincipalName = $a.UserPrincipalName
UserDisplayName = $a.UserDisplayName
IsMfaCapable = $a.IsMfaCapable
IsMfaRegistered = $a.IsMfaRegistered
IsPasswordlessCapable = $a.IsPasswordlessCapable
PreferredSecondFactor = $a.UserPreferredMethodForSecondaryAuthentication
MethodsRegistered = (@($a.MethodsRegistered) -join ';')
LastUpdated = $a.LastUpdatedDateTime
Id = $a.Id
}
}
# Not MFA-capable first, then not passwordless-capable.
$report | Sort-Object IsMfaCapable, IsPasswordlessCapable, UserPrincipalName |
Export-Csv -Path ".\admins-mfa-status.csv" -NoTypeInformation -Encoding UTF8
"Admins found: $($report.Count)"
"Not MFA-capable: $(@($report | Where-Object { -not $_.IsMfaCapable }).Count)"
Sample output columns- UserPrincipalName, UserDisplayName: The admin account
- IsMfaCapable: Registered a strong method that the authentication methods policy allows; False is the first thing to fix
- IsMfaRegistered: Registered a strong method, which the policy may not allow
- IsPasswordlessCapable: Registered a passwordless method (FIDO2, Windows Hello for Business, Authenticator passwordless) allowed by policy
- PreferredSecondFactor: The user's chosen default second factor, for example
push, oath, sms or voiceMobile - MethodsRegistered: All registered methods
- LastUpdated: When the report row was last updated (UTC)
GotchasMicrosoft Learn sources |
| List Global Admins and privileged role assignmentsRead-onlyOfficial Microsoft sample | Admin roles | See who currently holds Global Administrator and other directory roles. Details, command and permissionsWhat it doesLists directory role members, or lists unified role assignments. An official Graph example filters on the Global Administrator role definition ID and expands the principal. Cmdlets include Get-MgDirectoryRole, Get-MgDirectoryRoleMember, and Get-MgRoleManagementDirectoryRoleAssignment. Why admins use it"Who are the Global Admins?" is a standing audit question, and standing privileged roles should stay few. SourceModules and permissionsMicrosoft.Graph.Identity.DirectoryManagement (and Governance cmdlets for unified role assignments). Permissions documented: Directory.Read.All, RoleManagement.Read.Directory. LicenseListing current directory role assignments is a Graph directory-read operation. No extra P1 or P2 sentence was stated on these API pages. Eligible PIM assignments are a different API and do have a stated license (see the PIM item). Last checkedDecember 1, 2026 CaveatsBuilt-in role IDs are stable, but label the role from the role definition rather than hard-coding the GUID. This lists assigned directory roles; eligible PIM assignments are a different API. This is a documented cmdlet and API example, not a standalone .ps1 file. |
| PIM eligible and active role assignmentsRead-onlyOfficial Microsoft sample | Admin roles | List who can activate a privileged role in PIM, not only who currently holds it. Details, command and permissionsWhat it doesLists current PIM assignment schedule instances (active or assigned) and eligibility schedule instances (can activate), using Get-MgRoleManagementDirectoryRoleAssignmentScheduleInstance and Get-MgRoleManagementDirectoryRoleEligibilityScheduleInstance. Why admins use itA Global Admin list is incomplete if people can still activate the role in Privileged Identity Management. SourceModules and permissionsMicrosoft.Graph.Identity.Governance. Least-privileged permissions on the API pages: RoleAssignmentSchedule.Read.Directory (active) and RoleEligibilitySchedule.Read.Directory (eligible). RoleManagement.Read.Directory and RoleManagement.Read.All are listed as higher-privileged alternatives. Supported read roles include Global Reader, Security Reader and Privileged Role Administrator. LicenseMicrosoft's licensing fundamentals page states you need either Microsoft Entra ID Governance licenses or Microsoft Entra ID P2 licenses to use PIM and all of its settings. Last checkedDecember 1, 2026 CaveatsThese are API and cmdlet samples, not a single ready-made .ps1. Combine this with the standing role-assignment report so you can tell assigned from eligible. |
| List directory role definitions, including custom rolesRead-onlyMicrosoft Learn cmdlet example | Admin roles | See every built-in and custom Microsoft Entra role and its permissions. Details, command and permissionsWhat it doesGet-MgRoleManagementDirectoryRoleDefinition lists unifiedRoleDefinition objects; isBuiltIn separates built-in roles from custom ones and supports $filter. Why admins use itReview custom roles and what they grant when you move people off Global Administrator. CommandConnect-MgGraph -Scopes "RoleManagement.Read.Directory"
Get-MgRoleManagementDirectoryRoleDefinition -Filter "isBuiltIn eq false"
SourceModules and permissionsMicrosoft.Graph.Identity.Governance. Least-privileged permission listed for the directory provider: RoleManagement.Read.Directory. LicenseNo license requirement is stated on the API page. Custom roles have their own license row on License requirements. Last checkedDecember 1, 2026 CaveatsRead-only. |
| Directory role members who are guests or external usersRead-onlyNot tested against a live tenant | Admin roles | List Microsoft Entra directory role assignments where the principal is a guest (userType = Guest) or otherwise external. Details, command and permissionsWhat it doesLists directory role assignments whose principal is a guest user. The live scripts List Global Admins and privileged role assignments and PIM eligible and active role assignments inventory role holders but do not isolate guests. Guest users report is a tenant-wide guest list, not role membership. This report reads role assignments (GET /roleManagement/directory/roleAssignments) and then reads each user principal's userType. That assignment API is more complete than listing members of activated directoryRole objects only. Requirements- Modules: Microsoft.Graph.Identity.Governance, Microsoft.Graph.Users
- Connect-MgGraph scopes (least privilege):
RoleManagement.Read.Directory and User.Read.All (Directory.Read.All is also documented as sufficient for both reads) - Least-privileged admin role: Directory Readers (the List roleAssignments API also lists other roles that can call it, including Privileged Role Administrator; the List directory role members API lists Directory Readers among a broader set)
- License: No extra license is stated on the role assignment or user APIs for this read
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-11-27
Command# Read-only. Not tested against a live tenant.
# Tenant-wide directory role assignments, then keep principals whose
# userType is Guest. Uses the role management assignments API rather than
# only activated directoryRole objects.
# Docs: GET /roleManagement/directory/roleAssignments
# GET /users/{id}?$select=userType,displayName,userPrincipalName
Import-Module Microsoft.Graph.Identity.Governance
Import-Module Microsoft.Graph.Users
Connect-MgGraph -Scopes "RoleManagement.Read.Directory","User.Read.All"
$roleDefs = @{}
Get-MgRoleManagementDirectoryRoleDefinition -All | ForEach-Object {
$roleDefs[$_.Id] = $_.DisplayName
}
$assignments = Get-MgRoleManagementDirectoryRoleAssignment -All
# Cache users so a person in several roles is looked up once
$userCache = @{}
$report = foreach ($assignment in $assignments) {
$principalId = $assignment.PrincipalId
if (-not $userCache.ContainsKey($principalId)) {
try {
$userCache[$principalId] = Get-MgUser -UserId $principalId -Property Id, DisplayName, UserPrincipalName, UserType, AccountEnabled
}
catch {
# Not a user (service principal, group, or no access)
$userCache[$principalId] = $null
}
}
$user = $userCache[$principalId]
if ($user -and $user.UserType -eq 'Guest') {
[pscustomobject]@{
RoleName = $roleDefs[$assignment.RoleDefinitionId]
RoleDefinitionId = $assignment.RoleDefinitionId
DisplayName = $user.DisplayName
UserPrincipalName = $user.UserPrincipalName
UserType = $user.UserType
AccountEnabled = $user.AccountEnabled
PrincipalId = $principalId
DirectoryScopeId = $assignment.DirectoryScopeId
AssignmentId = $assignment.Id
}
}
}
$report | Sort-Object RoleName, UserPrincipalName |
Export-Csv -Path ".\guest-directory-role-members.csv" -NoTypeInformation -Encoding UTF8
"Role assignments examined: $($assignments.Count)"
"Guest role members found: $($report.Count)"
Sample output columns- RoleName, RoleDefinitionId: Directory role
- DisplayName, UserPrincipalName, UserType, AccountEnabled: The guest principal
- PrincipalId: Object ID of the user
- DirectoryScopeId:
/ for tenant-wide, or an administrative unit scope - AssignmentId: The role assignment object ID
GotchasGet-MgDirectoryRoleMember returns directoryObject and does not reliably filter on userType; that is why this script resolves each principal with Get-MgUser.- Non-user principals (groups, service principals) are skipped. A group in a role whose members include guests will not be expanded here.
- Eligible-only PIM assignments that are not currently active may not appear in this assignment list; use PIM eligible and active role assignments and then filter guests if you need eligibility as well.
- Looking up each unique principal after
-All on assignments can take time in a large tenant. Results are cached per principal.
Microsoft Learn sources |
| Pending PIM role activation requestsRead-onlyNot tested against a live tenant | Admin roles | List Microsoft Entra role assignment schedule requests that are waiting for approval (status eq PendingApproval). Details, command and permissionsWhat it doesLists Microsoft Entra role assignment schedule requests with status eq 'PendingApproval'. PIM eligible and active role assignments shows who is eligible or active, not the approval queue. Approving or denying a request is a portal action; see Approve or deny a pending PIM role activation. This script only reads the queue. The approval-workflow article documents this filter: GET /roleManagement/directory/roleAssignmentScheduleRequests/filterByCurrentUser(on='approver')?$filter=status eq 'PendingApproval'. The script uses the list cmdlet with the same status eq 'PendingApproval' filter so you can see pending requests in the tenant (subject to your role), not only those assigned to you. Requirements- Modules: Microsoft.Graph.Identity.Governance, Microsoft.Graph.Users
- Connect-MgGraph scopes (least privilege):
RoleAssignmentSchedule.ReadWrite.Directory — this is the least privileged permission the List API documents, including for GET. The script only calls Get-MgRoleManagementDirectoryRoleAssignmentScheduleRequest and does not approve or deny. Do not assume a Read-only scope exists for this API; none is listed on the page. User.Read.All is added only to resolve PrincipalId to a display name; you can omit it and keep the object ID if you prefer. - Least-privileged admin role for read operations: Global Reader, Security Operator, Security Reader, Security Administrator, or Privileged Role Administrator (write operations require Privileged Role Administrator)
- License: Privileged Identity Management requires a license; see License requirements (opens in a new tab)
- Flag: Read-only (GET only)
- Label: Not tested against a live tenant
- Learn checked: 2026-11-27
Command# Read-only GET. Not tested against a live tenant.
# Pending Microsoft Entra role activation requests.
# Docs: GET /roleManagement/directory/roleAssignmentScheduleRequests
# Filter documented on the PIM approval-workflow page.
Import-Module Microsoft.Graph.Identity.Governance
Import-Module Microsoft.Graph.Users
Connect-MgGraph -Scopes "RoleAssignmentSchedule.ReadWrite.Directory","User.Read.All"
$roleDefs = @{}
Get-MgRoleManagementDirectoryRoleDefinition -All | ForEach-Object {
$roleDefs[$_.Id] = $_.DisplayName
}
$pending = Get-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -All `
-Filter "status eq 'PendingApproval'"
$report = foreach ($request in $pending) {
$principalName = $null
try {
$principal = Get-MgUser -UserId $request.PrincipalId -Property DisplayName, UserPrincipalName
$principalName = $principal.DisplayName
}
catch {
$principalName = $request.PrincipalId
}
[pscustomobject]@{
RequestId = $request.Id
Status = $request.Status
Action = $request.Action
RoleName = $roleDefs[$request.RoleDefinitionId]
RoleDefinitionId = $request.RoleDefinitionId
PrincipalId = $request.PrincipalId
PrincipalName = $principalName
Justification = $request.Justification
CreatedDateTime = $request.CreatedDateTime
DirectoryScopeId = $request.DirectoryScopeId
ApprovalId = $request.ApprovalId
TargetScheduleId = $request.TargetScheduleId
}
}
$report | Sort-Object CreatedDateTime |
Export-Csv -Path ".\pending-pim-role-requests.csv" -NoTypeInformation -Encoding UTF8
"Pending approval requests: $($report.Count)"
Sample output columns- RequestId, Status, Action: Request object, usually
PendingApproval and SelfActivate - RoleName, RoleDefinitionId: Role being activated
- PrincipalId, PrincipalName: Who requested activation
- Justification: Requester justification
- CreatedDateTime: When the request was submitted (approvers have 24 hours)
- DirectoryScopeId, ApprovalId, TargetScheduleId: Scope and related IDs
Gotchas- The documented least-privileged Graph permission is a ReadWrite scope even for listing. This sample does not PATCH approvals.
- What you see depends on your role. Delegated approvers can also query
filterByCurrentUser(on='approver') as shown in the approval-workflow article; this script lists requests the signed-in role is allowed to read tenant-wide. - Approvers cannot approve their own activation requests. A request that is not approved within 24 hours expires and must be submitted again.
Get-MgRoleManagementDirectoryRoleDefinition is used only to translate IDs into role names.
Microsoft Learn sources |
| Export administrative units, their members and scoped adminsRead-onlyNot tested against a live tenant | Admin roles | List every administrative unit with membership type, rule, restricted-management flag and member counts, plus who holds a role scoped to each unit. Details, command and permissionsWhat it doesAdministrative units let you give someone a role, such as Helpdesk Administrator, over just one part of the directory. Over time it gets hard to see which units exist, what's in them and who administers them. This script writes two CSVs: one row per unit with member counts, and one row per scoped role assignment. Requirements- Modules: Microsoft.Graph.Identity.DirectoryManagement
- Connect-MgGraph scopes (least privilege):
AdministrativeUnit.Read.All (List administrativeUnits and List members) and RoleManagement.Read.Directory (List scopedRoleMembers and List directoryRoles) - Least-privileged admin role: Global Reader reads all properties of administrative units, including members; Directory Readers reads basic properties and members (List members (opens in a new tab)).
- License: Creating administrative units works with Microsoft Entra ID Free. Each administrator assigned a role over an administrative unit needs Microsoft Entra ID P1, and dynamic membership rules need P1 for each member (License requirements (opens in a new tab)).
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-12-02
Command# Read-only. Not tested against a live tenant.
Import-Module Microsoft.Graph.Identity.DirectoryManagement
Connect-MgGraph -Scopes "AdministrativeUnit.Read.All","RoleManagement.Read.Directory"
# directoryRole id -> name (only activated roles are returned, which covers any role in use)
$roleNames = @{}
Get-MgDirectoryRole -All | ForEach-Object { $roleNames[$_.Id] = $_.DisplayName }
$units = Get-MgDirectoryAdministrativeUnit -All
$unitRows = @(); $roleRows = @()
foreach ($au in $units) {
$members = @(Get-MgDirectoryAdministrativeUnitMember -AdministrativeUnitId $au.Id -All)
$types = $members | Group-Object { $_.AdditionalProperties['@odata.type'] -replace '#microsoft.graph.', '' }
$scoped = @(Get-MgDirectoryAdministrativeUnitScopedRoleMember -AdministrativeUnitId $au.Id -All)
$unitRows += [pscustomobject]@{
AdministrativeUnit = $au.DisplayName
MembershipType = $au.MembershipType
MembershipRule = $au.MembershipRule
RestrictedManagement = $au.IsMemberManagementRestricted
Visibility = $au.Visibility
Users = ($types | Where-Object Name -eq 'user').Count
Groups = ($types | Where-Object Name -eq 'group').Count
Devices = ($types | Where-Object Name -eq 'device').Count
ScopedRoleAssignments = $scoped.Count
Id = $au.Id
}
foreach ($s in $scoped) {
$roleRows += [pscustomobject]@{
AdministrativeUnit = $au.DisplayName
Role = if ($roleNames.ContainsKey($s.RoleId)) { $roleNames[$s.RoleId] } else { $s.RoleId }
Member = $s.RoleMemberInfo.DisplayName
MemberId = $s.RoleMemberInfo.Id
}
}
}
$unitRows | Sort-Object AdministrativeUnit | Export-Csv ".\administrative-units.csv" -NoTypeInformation -Encoding UTF8
$roleRows | Sort-Object AdministrativeUnit, Role | Export-Csv ".\administrative-unit-scoped-roles.csv" -NoTypeInformation -Encoding UTF8
"Administrative units: $($unitRows.Count); scoped role assignments: $($roleRows.Count)"
Sample output columnsadministrative-units.csv - AdministrativeUnit, Id: The unit
- MembershipType, MembershipRule:
dynamic with its rule, or assigned (empty means assigned) - RestrictedManagement: True for restricted management units, whose members need specific permissions to manage
- Visibility:
HiddenMembership or empty (public) - Users, Groups, Devices: Member counts by type
- ScopedRoleAssignments: Number of roles scoped to this unit
administrative-unit-scoped-roles.csv: AdministrativeUnit, Role, Member, MemberId. GotchasMicrosoft Learn sources |
| Export sign-in logsRead-onlyOfficial Microsoft sample | Sign-ins, audit & risk | Export sign-ins with Conditional Access status, failure reasons, and client app, then filter the CSV. Details, command and permissionsWhat it doesGet-MgAuditLogSignIn retrieves sign-in events. The official applied-CA-policies how-to includes a complete CSV export with resource, user, IP, location, CA status (success, failure, or report-only), failure reason, CA details, device, and client app. The analyze-logs page shows a filter for conditionalAccessStatus eq 'failure'. Why admins use itUseful when you are troubleshooting AADSTS errors, users blocked by Conditional Access, or leftover legacy clients. SourceModules and permissionsMicrosoft Graph PowerShell (reports / audit log cmdlets). Scopes observed: AuditLog.Read.All, plus Policy.Read.ConditionalAccess and Directory.Read.All on the applied-CA page. LicenseThe analyze-logs page states a Microsoft Entra ID P1 or P2 license is required for these activity logs. Last checkedDecember 1, 2026 CaveatsDate-bound your queries so they do not time out. There is no separate official "legacy auth report" script; the official CA sign-in export already includes ClientApp. Failed sign-ins can be filtered from this same cmdlet. This is a documented example, not a standalone .ps1 file. |
| Export directory audit logsRead-onlyMicrosoft Learn cmdlet example | Sign-ins, audit & risk | Find who changed a user, group, app, role or policy, and when. Details, command and permissionsWhat it doesGet-MgAuditLogDirectoryAudit lists directory audit events. The API page shows a filter by the initiating user's ID. Why admins use itAnswers "who changed this?" after an unexpected change, and gives you a CSV for an incident timeline. CommandConnect-MgGraph -Scopes "AuditLog.Read.All"
Get-MgAuditLogDirectoryAudit -Top 500 | Select-Object ActivityDateTime, ActivityDisplayName, Category, Result | Export-Csv directory-audits.csv -NoTypeInformation
SourceModules and permissionsMicrosoft.Graph.Reports. Least-privileged permission on the API page: AuditLog.Read.All; supported least-privileged roles are Reports Reader, Security Administrator and Security Reader. LicenseNo license requirement is stated on the API page. Last checkedDecember 1, 2026 CaveatsRead-only. Use -Filter and -Top to keep large tenants manageable. |
| Risky users reportRead-onlyMicrosoft Learn cmdlet example | Sign-ins, audit & risk | List users Microsoft Entra ID Protection flags as risky, with risk level and state. Details, command and permissionsWhat it doesGet-MgRiskyUser lists riskyUser objects from ID Protection. Why admins use itFind users to reset or investigate, including people who reported an MFA prompt as suspicious (they are set to high user risk). CommandConnect-MgGraph -Scopes "IdentityRiskyUser.Read.All"
Get-MgRiskyUser -All | Select-Object UserPrincipalName, RiskLevel, RiskState, RiskLastUpdatedDateTime | Export-Csv risky-users.csv -NoTypeInformation
SourceModules and permissionsMicrosoft.Graph.Identity.SignIns. Least-privileged permission on the API page: IdentityRiskyUser.Read.All; supported least-privileged roles are Global Reader, Security Operator and Security Reader. LicenseFull ID Protection features need Microsoft Entra ID P2 or Microsoft Entra Suite (remediation page). Last checkedDecember 1, 2026 CaveatsRead-only. Dismissing or confirming risk is a separate write action. |
| Risk detections exportRead-onlyMicrosoft Learn cmdlet example | Sign-ins, audit & risk | List the individual risk detections (for example unfamiliar sign-in properties) behind risky users and sign-ins. Details, command and permissionsWhat it doesGet-MgRiskDetection lists riskDetection objects from ID Protection. Why admins use itGives you the evidence behind a risk level when you investigate a user. CommandConnect-MgGraph -Scopes "IdentityRiskEvent.Read.All"
Get-MgRiskDetection -All | Export-Csv risk-detections.csv -NoTypeInformation
SourceModules and permissionsMicrosoft.Graph.Identity.SignIns. Least-privileged permission on the API page: IdentityRiskEvent.Read.All. LicenseThe API page states you must have a Microsoft Entra ID P1 or P2 license to use the risk detection API. Last checkedDecember 1, 2026 CaveatsRead-only. |
| Revoke a user's sign-in sessionsChanges dataMicrosoft Learn cmdlet example | Sign-ins, audit & risk | Invalidate a user's refresh tokens and browser session cookies after a compromise or departure. Details, command and permissionsWhat it doesRevoke-MgUserSignInSession revokes the user's refresh tokens. Learn's emergency access-revocation article disables the account first (Update-MgUser -AccountEnabled:$false), then revokes sessions, then disables the user's registered devices. Why admins use itThe scriptable version of Revoke sessions, for incident response or bulk leavers. Command (dry run first)Connect-MgGraph -Scopes "User.RevokeSessions.All"
# Dry run first
Revoke-MgUserSignInSession -UserId user@contoso.com -WhatIf
Revoke-MgUserSignInSession -UserId user@contoso.com
Dry run firstConfirm the right account with Get-MgUser and run with -WhatIf first. SourceModules and permissionsMicrosoft.Graph.Users.Actions. Least-privileged permission on the API page: User.RevokeSessions.All. The revoke-access article connects with User.ReadWrite.All and Directory.AccessAsUser.All for the full disable-and-revoke routine. LicenseNo license requirement is stated on these pages. Last checkedDecember 1, 2026 CaveatsChanges data: the user must sign in again everywhere. Access tokens already issued can work until they expire (one hour by default). |
| Export provisioning logsRead-onlyNot tested against a live tenant | Sign-ins, audit & risk | Export Microsoft Entra provisioning events (success, skip, and failure) for a date range, so you can see why a user or group was or wasn't provisioned. Details, command and permissionsWhat it doesExports Microsoft Entra provisioning events from GET /auditLogs/provisioning. This is a different log from Export sign-in logs and Export directory audit logs. Use it when a user or group was created, updated, skipped, or failed in an HR app, Microsoft Entra Cloud Sync, or another provisioning configuration. Requirements- Module: Microsoft.Graph.Reports
- Connect-MgGraph scopes (least privilege):
AuditLog.Read.All and Directory.Read.All (both are required on the List API page) - Least-privileged admin role: Reports Reader. Both the analyze provisioning logs (opens in a new tab) article and the List API page include Reports Reader. The List API page also lists Security Reader, Security Administrator, Global Reader, Security Operator, Application Administrator, and Cloud Application Administrator among roles supported for the operation.
- License: A working tenant with a Microsoft Entra ID P1 or P2 license, per the analyze-provisioning-logs article
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-11-27
Command# Read-only. Not tested against a live tenant.
# Date-bound export of provisioning log events.
# Docs: GET /auditLogs/provisioning
Import-Module Microsoft.Graph.Reports
Connect-MgGraph -Scopes "AuditLog.Read.All","Directory.Read.All"
# Change the window as needed. Always date-bound this query.
$since = (Get-Date).ToUniversalTime().AddDays(-7).ToString('yyyy-MM-ddTHH:mm:ssZ')
$events = Get-MgAuditLogProvisioning -All -Filter "activityDateTime ge $since"
$report = foreach ($event in $events) {
[pscustomobject]@{
ActivityDateTime = $event.ActivityDateTime
ChangeId = $event.ChangeId
Action = $event.ProvisioningAction
Status = $event.ProvisioningStatusInfo.Status
ErrorCode = $event.ProvisioningStatusInfo.ErrorInformation.ErrorCode
ErrorReason = $event.ProvisioningStatusInfo.ErrorInformation.Reason
ErrorDetails = $event.ProvisioningStatusInfo.ErrorInformation.AdditionalDetails
SourceSystem = $event.SourceSystem.DisplayName
TargetSystem = $event.TargetSystem.DisplayName
SourceIdentity = $event.SourceIdentity.DisplayName
SourceId = $event.SourceIdentity.Id
TargetIdentity = $event.TargetIdentity.DisplayName
TargetId = $event.TargetIdentity.Id
InitiatedBy = $event.InitiatedBy.User.DisplayName
DurationMs = $event.DurationInMilliseconds
JobId = $event.JobId
CycleId = $event.CycleId
Id = $event.Id
}
}
$report | Sort-Object ActivityDateTime |
Export-Csv -Path ".\provisioning-logs.csv" -NoTypeInformation -Encoding UTF8
"Provisioning events since $since : $($report.Count)"
Sample output columns- ActivityDateTime: When the event occurred
- ChangeId, CycleId, JobId, Id: Identifiers for the provisioning job and the event
- Action: Provisioning action (create, update, delete, and so on)
- Status:
provisioningStatusInfo.status (success, warning, failure, skipped, or unknownFutureValue) - ErrorCode, ErrorReason, ErrorDetails: From
provisioningStatusInfo.errorInformation when the result is not success or skipped - SourceSystem, TargetSystem: Source and target directories or apps
- SourceIdentity, SourceId, TargetIdentity, TargetId: The object being provisioned
- InitiatedBy: Who or what started the activity
- DurationMs: Duration in milliseconds
Property names are taken from the provisioningObjectSummary (opens in a new tab) resource. If a nested property is empty in your module version, the CSV cell will be blank; check the raw object with Select-Object -First 1 | Format-List *. Gotchas- Always date-bound the query so it does not time out. The sample uses the last seven days; adjust as needed.
- Application owners can also view logs for applications they own, per the analyze-provisioning-logs article.
- This complements An on-premises change isn’t showing in Microsoft Entra ID when the failure is in a provisioning job rather than the Connect scheduler alone.
Microsoft Learn sources |
| Inactive user accountsRead-onlyOfficial Microsoft sample | Users, groups & guests | Find accounts, including external users, that have not signed in for a long time. Details, command and permissionsWhat it doesOfficial guidance for detecting inactive accounts using the signInActivity properties (lastSignInDateTime and lastSuccessfulSignInDateTime). The Graph PowerShell tab documents date filters on lastSignInDateTime. The same page says the last-sign-in timestamp can help determine whether an external user is still active in the tenant. Why admins use itA common hardening task: list accounts that have not signed in for 90 to 180 days so you can disable or remove them after review. SourceModules and permissionsMicrosoft Graph PowerShell. Scopes observed on the inactive-users page: AuditLog.Read.All, User.Read.All. The page notes that signInActivity is not available through Get-MgAuditLogDirectoryAudit. LicenseThe inactive-users page states that reading lastSignInDateTime with Microsoft Graph requires a Microsoft Entra ID P1 or P2 license. Last checkedDecember 1, 2026 CaveatsDefine "inactive" for your tenant (the page suggests many organizations use 90 to 180 days). Accounts that have never signed in need extra care. The report is read-only; disabling or deleting accounts is a separate, change-making step. Microsoft's dedicated stale-guest page is about Access Reviews and Entra ID Governance or Suite licensing, and it does not include Graph PowerShell examples. This is a documented how-to, not a standalone .ps1 file. |
| Password expiration reportRead-onlyOfficial Microsoft sample | Users, groups & guests | See whose password is expired or about to expire. Details, command and permissionsWhat it doesOfficial Microsoft Entra PowerShell script that reads the tenant password policy, looks at licensed active users, calculates expiration from last password change, and writes a CSV (user, password dates, days to expiration, optional last sign-in, account status). It highlights passwords already expired or expiring within 30 days. Uses Connect-Entra with scopes User.Read.All, Domain.Read.All, Organization.Read.All, and AuditLog.Read.All. Why admins use itUseful after a wave of expired-password sign-in failures, or as a regular hygiene report. SourceMicrosoft Learn: Report users with expired or soon-to-expire passwords (opens in a new tab) Modules and permissionsMicrosoft Entra PowerShell. Scopes: User.Read.All, Domain.Read.All, Organization.Read.All, AuditLog.Read.All. LicenseA P1 requirement is not stated on this page (password policy and user read). Last-sign-in columns, if used, follow the same P1 signInActivity rule as the inactive-users item. Last checkedDecember 1, 2026 CaveatsTenants that disable password expiration will see that reflected in the policy status column. This is an official sample with Microsoft's usual as-is disclaimer. |
| Guest users reportRead-onlyMicrosoft Learn cmdlet example | Users, groups & guests | List every guest with when they were created and whether they accepted the invitation. Details, command and permissionsWhat it doesGet-MgUser with -Filter "userType eq 'Guest'" returns guest accounts; userType supports $filter (eq). externalUserState shows PendingAcceptance or Accepted for invited guests, and both it and createdDateTime are requested with -Property. Why admins use itStart of a guest cleanup: find invitations never accepted and old guests, then review them with an access review. CommandConnect-MgGraph -Scopes "User.Read.All"
Get-MgUser -All -Filter "userType eq 'Guest'" -Property Id, DisplayName, Mail, CreatedDateTime, ExternalUserState | Select-Object DisplayName, Mail, CreatedDateTime, ExternalUserState | Export-Csv guests.csv -NoTypeInformation
SourceModules and permissionsMicrosoft.Graph.Users. Permissions listed on the API page include User.Read.All, used here. LicenseNo license requirement is stated on the API page. Last sign-in (signInActivity) needs P1; see the inactive users item. Last checkedDecember 1, 2026 CaveatsRead-only. |
| List deleted users you can still restoreRead-onlyMicrosoft Learn cmdlet example | Users, groups & guests | See users deleted in the last 30 days, before they're permanently removed. Details, command and permissionsWhat it doesGet-MgDirectoryDeletedItemAsUser lists deleted user objects. Deleted users stay restorable for 30 days. Why admins use itCheck what's recoverable after an accidental deletion or a sync problem. CommandConnect-MgGraph -Scopes "User.Read.All"
Get-MgDirectoryDeletedItemAsUser -All | Select-Object Id, DisplayName, UserPrincipalName, DeletedDateTime
SourceModules and permissionsMicrosoft.Graph.Identity.DirectoryManagement. Least-privileged permission for users on the API page: User.Read.All. LicenseNo license requirement is stated on the API page. Last checkedDecember 1, 2026 CaveatsRead-only. |
| Groups and their owners (find ownerless groups)Read-onlyMicrosoft Learn cmdlet example | Users, groups & guests | Count owners per group so you can find groups nobody owns. Details, command and permissionsWhat it doesGet-MgGroup lists groups and Get-MgGroupOwner lists a group's owners; the example combines them into one CSV. Why admins use itOwnerless Microsoft 365 groups and teams have nobody to approve access or answer access reviews. CommandConnect-MgGraph -Scopes "GroupMember.Read.All","Group.Read.All"
Get-MgGroup -All | ForEach-Object { [pscustomobject]@{ Group = $_.DisplayName; Id = $_.Id; Owners = @(Get-MgGroupOwner -GroupId $_.Id -All).Count } } | Export-Csv group-owners.csv -NoTypeInformation
SourceModules and permissionsMicrosoft.Graph.Groups. Least-privileged permission for owners: GroupMember.Read.All; Group.Read.All is also listed for listing groups. LicenseNo license requirement is stated on these API pages. Last checkedDecember 1, 2026 CaveatsRead-only. One owner call per group, so large tenants take a while. |
| Restore a deleted userChanges dataMicrosoft Learn cmdlet example | Users, groups & guests | Bring back a user deleted in the last 30 days, with group memberships and licenses. Details, command and permissionsWhat it doesRestore-MgDirectoryDeletedItem restores a deleted directory object by its ID. Restored users get back the licenses they had, even if none are free. Why admins use itUndo an accidental deletion without recreating the account. Command (dry run first)Connect-MgGraph -Scopes "User.DeleteRestore.All"
# Dry run first: find the ID and preview
Get-MgDirectoryDeletedItemAsUser -All | Select-Object Id, DisplayName, UserPrincipalName, DeletedDateTime
Restore-MgDirectoryDeletedItem -DirectoryObjectId <deleted-user-id> -WhatIf
Dry run firstList deleted users (the read-only item above), pick the ID, then run with -WhatIf. SourceModules and permissionsMicrosoft.Graph.Identity.DirectoryManagement. Least-privileged permission for users on the API page: User.DeleteRestore.All. LicenseNo license requirement is stated on these pages. Last checkedDecember 1, 2026 CaveatsChanges data. For synced users, on-premises AD is the source of authority: if the user still exists there, the next sync can bring them back. |
| Export dynamic membership groups and their rulesRead-onlyNot tested against a live tenant | Users, groups & guests | List Microsoft Entra dynamic membership groups, including each group's membership rule and whether rule processing is on. Details, command and permissionsWhat it doesLists groups whose groupTypes includes DynamicMembership, and exports membershipRule and membershipRuleProcessingState. Group owners report does not include the rule. For how to write and test a rule, see Set up dynamic membership groups in Microsoft Entra ID. The official List groups examples include a filter on groupTypes/any(c:c eq 'Unified') with ConsistencyLevel eventual and $count. This script uses the same pattern with DynamicMembership. Requirements- Module: Microsoft.Graph.Groups
- Connect-MgGraph scopes:
Group.Read.All (or Directory.Read.All). Note: the current List groups API page lists Group-NestingSupport.ReadWrite.All as the least privileged delegated permission, with Group.Read.All and Directory.Read.All among the higher privileged permissions. This script uses Group.Read.All, a documented read permission on that page, rather than a ReadWrite scope. - Least-privileged admin role: The List groups API page does not currently document a specific Microsoft Entra admin role; it only lists Graph permissions. Use a role that can already read groups in your tenant.
- License: Dynamic membership groups require Microsoft Entra ID P1 (or a license that includes it) for users who can be in dynamic groups; see the dynamic groups concept article
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-11-27
Command# Read-only. Not tested against a live tenant.
# Groups with groupTypes containing DynamicMembership.
# Docs: GET /groups?$filter=groupTypes/any(c:c eq 'DynamicMembership')
# ConsistencyLevel / $count follow the official List groups advanced-query example.
Import-Module Microsoft.Graph.Groups
Connect-MgGraph -Scopes "Group.Read.All"
$groups = Get-MgGroup -All `
-Filter "groupTypes/any(c:c eq 'DynamicMembership')" `
-Property "id,displayName,description,mail,mailEnabled,securityEnabled,groupTypes,membershipRule,membershipRuleProcessingState,createdDateTime" `
-ConsistencyLevel eventual `
-CountVariable GroupCount
$report = foreach ($group in $groups) {
[pscustomobject]@{
DisplayName = $group.DisplayName
Id = $group.Id
Mail = $group.Mail
MailEnabled = $group.MailEnabled
SecurityEnabled = $group.SecurityEnabled
GroupTypes = ($group.GroupTypes -join '; ')
MembershipRule = $group.MembershipRule
MembershipRuleProcessingState = $group.MembershipRuleProcessingState
Description = $group.Description
CreatedDateTime = $group.CreatedDateTime
}
}
$report | Sort-Object DisplayName |
Export-Csv -Path ".\dynamic-membership-groups.csv" -NoTypeInformation -Encoding UTF8
"Dynamic membership groups: $($report.Count) (count=$GroupCount)"
Sample output columns- DisplayName, Id, Mail: Group identity
- MailEnabled, SecurityEnabled, GroupTypes: Security group, Microsoft 365 group, or both
- MembershipRule: The current rule syntax
- MembershipRuleProcessingState: Typically
On or Paused (the documented values) - Description, CreatedDateTime: Metadata
Gotchas- Request
membershipRule and membershipRuleProcessingState in -Property. The default property set may omit them. - If your SDK version does not accept
-CountVariable or -ConsistencyLevel, retry the same -Filter and -Property without those parameters. Some groupTypes filters work as a standard query. - Dynamic group limits and rule syntax are documented in the concept article and in Set up dynamic membership groups in Microsoft Entra ID. This script does not evaluate whether a rule is valid.
Microsoft Learn sources |
| Export a group's members, including nested groupsRead-onlyNot tested against a live tenant | Users, groups & guests | Export everyone in a group to CSV, either direct members only or the flattened (transitive) list that includes members of nested groups, with object type, UPN and user type. Details, command and permissionsWhat it does"Who is actually in this group?" is harder than it looks when groups contain other groups. This script exports direct members (Get-MgGroupMember) or, with -Transitive, the flattened list from Get-MgGroupTransitiveMember, which includes members of nested groups. Each row shows the object type so you can tell users, groups, devices and service principals apart. To see owners rather than members, use Groups and their owners. To see one user's groups, use List every group a user belongs to. Requirements- Modules: Microsoft.Graph.Groups
- Connect-MgGraph scopes (least privilege):
GroupMember.Read.All and User.Read.All. The List members and List transitive members APIs list GroupMember.ReadBasic.All as least privileged, but Learn notes that when the app can't read a member's object type, only the object type and id come back. User.Read.All is added so user rows include UPN and user type (List group members (opens in a new tab)). - Least-privileged admin role: Directory Readers is among the roles the List members API supports; group owners and member users can also read members (List group members (opens in a new tab)).
- License: None stated on the API pages.
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-12-02
Command# Read-only. Not tested against a live tenant.
param(
[Parameter(Mandatory)] [string] $GroupId, # group object ID
[switch] $Transitive # include members of nested groups
)
Import-Module Microsoft.Graph.Groups
Connect-MgGraph -Scopes "GroupMember.Read.All","User.Read.All"
$members = if ($Transitive) {
Get-MgGroupTransitiveMember -GroupId $GroupId -All
} else {
Get-MgGroupMember -GroupId $GroupId -All
}
$report = foreach ($m in $members) {
$p = $m.AdditionalProperties
[pscustomobject]@{
Type = ($p['@odata.type'] -replace '#microsoft.graph.', '')
DisplayName = $p['displayName']
UserPrincipalName = $p['userPrincipalName']
Mail = $p['mail']
UserType = $p['userType']
Id = $m.Id
}
}
$file = if ($Transitive) { ".\group-members-transitive.csv" } else { ".\group-members-direct.csv" }
$report | Sort-Object Type, DisplayName | Export-Csv -Path $file -NoTypeInformation -Encoding UTF8
"Members exported: $($report.Count) -> $file"
Sample output columns- Type:
user, group, device, servicePrincipal or another directory object type - DisplayName, UserPrincipalName, Mail, UserType: Filled for users (
UserType is Member or Guest); groups and devices show DisplayName only - Id: Object ID
Gotchas- Transitive includes the nested groups themselves as rows (Type
group) as well as their members. - Hidden membership groups: Learn lists which roles can read hidden members (for example User Administrator, Exchange Administrator, SharePoint Administrator and Intune Administrator); other readers may get fewer rows (List group members (opens in a new tab)).
- Limited rows: if a row has a Type and Id but no name, the session lacks permission to read that object type (for example devices or service principals) (List group transitive members (opens in a new tab)).
- Property names come from
AdditionalProperties because the cmdlets return generic directory objects.
Microsoft Learn sources |
| List every group and role a user belongs to (including nested)Read-onlyNot tested against a live tenant | Users, groups & guests | For one or more users, export all groups, directory roles and administrative units they belong to directly or through nested groups, with group type, sync source and whether the group can hold roles. Details, command and permissionsWhat it doesUse this before offboarding, when copying access for a new starter, or when someone has access you can't explain. Get-MgUserTransitiveMemberOf returns the groups, directory roles and administrative units a user is a member of, including memberships that come through nested groups (List a user's transitive memberships (opens in a new tab)). For the reverse view (who is in one group), use Export a group's members. Requirements- Modules: Microsoft.Graph.Users
- Connect-MgGraph scopes (least privilege):
User.Read.All (least privileged for another user on the API page) plus GroupMember.Read.All, so group rows include names and types rather than only an id. GroupMember.Read.All is listed as a supported permission on the same page. - Least-privileged admin role: The API page doesn't name a specific role for reading another user's memberships; Directory Readers or Global Reader can read users and groups.
- License: None stated on the API page.
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-12-02
Command# Read-only. Not tested against a live tenant.
param(
[Parameter(Mandatory)] [string[]] $UserPrincipalName # one or more UPNs
)
Import-Module Microsoft.Graph.Users
Connect-MgGraph -Scopes "User.Read.All","GroupMember.Read.All"
$report = foreach ($upn in $UserPrincipalName) {
$memberships = Get-MgUserTransitiveMemberOf -UserId $upn -All
foreach ($m in $memberships) {
$p = $m.AdditionalProperties
[pscustomobject]@{
User = $upn
Type = ($p['@odata.type'] -replace '#microsoft.graph.', '')
DisplayName = $p['displayName']
GroupTypes = ($p['groupTypes'] -join ';')
SecurityEnabled = $p['securityEnabled']
MailEnabled = $p['mailEnabled']
IsAssignableToRole = $p['isAssignableToRole']
OnPremisesSynced = $p['onPremisesSyncEnabled']
Id = $m.Id
}
}
}
$report | Sort-Object User, Type, DisplayName |
Export-Csv -Path ".\user-group-memberships.csv" -NoTypeInformation -Encoding UTF8
"Rows exported: $($report.Count)"
Sample output columns- User: The UPN you passed in
- Type:
group, directoryRole or administrativeUnit - DisplayName: Group, role or administrative unit name
- GroupTypes:
Unified for Microsoft 365 groups, DynamicMembership for dynamic groups; empty for plain security groups - SecurityEnabled, MailEnabled: Security group, mail-enabled security group, distribution list or Microsoft 365 group
- IsAssignableToRole: True if the group can be assigned Microsoft Entra roles
- OnPremisesSynced: True if the group comes from on-premises AD (change it there)
- Id: Object ID
Gotchas- Transitive means "including nested": you can't tell from this output which nested group gave the membership. Use direct
Get-MgUserMemberOf if you need only direct memberships. - Role eligibility isn't membership. This lists memberships returned by the API. For PIM-eligible role assignments, use PIM eligible and active role assignments.
- Hidden membership groups need
Member.Read.Hidden to be listed (List a user's transitive memberships (opens in a new tab)). - Rows with a Type and Id but no name mean the session lacks permission to read that object type.
Microsoft Learn sources |
| Directory sync status and objects with sync errorsRead-onlyNot tested against a live tenant | Users, groups & guests | Check when the tenant last synced from on-premises AD, then list synced users and groups that have provisioning errors (duplicate UPN or proxy address conflicts) with the conflicting value. Details, command and permissionsWhat it doesWhen an on-premises change isn't showing in the cloud, two questions come first: is sync running at all, and is the object stuck on an error? This script reads the tenant's onPremisesLastSyncDateTime and onPremisesSyncEnabled from the organization object, then lists users and groups whose onPremisesProvisioningErrors isn't empty. Each error has a category (currently only PropertyConflict), the property causing it (UserPrincipalName or ProxyAddress) and the conflicting value (onPremisesProvisioningError resource type (opens in a new tab)). Requirements- Modules: Microsoft.Graph.Identity.DirectoryManagement, Microsoft.Graph.Users, Microsoft.Graph.Groups
- Connect-MgGraph scopes (least privilege):
Organization.Read.All (with only User.Read, the organization call returns just id, displayName and verifiedDomains (Get organization (opens in a new tab))), User.Read.All and Group.Read.All. The List groups page currently names Group-NestingSupport.ReadWrite.All as least privileged; this script uses the read permission Group.Read.All, as earlier EntraReady scripts do. - Least-privileged admin role: Global Reader can read all three. (The separate
onPremisesDirectorySynchronization API that holds sync feature flags supports only Global Administrator, so this script doesn't call it (Get onPremisesDirectorySynchronization (opens in a new tab)).) - License: None stated on the API pages.
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-12-02
Command# Read-only. Not tested against a live tenant.
# onPremisesProvisioningErrors isn't documented as filterable, so users and groups are filtered in memory.
Import-Module Microsoft.Graph.Identity.DirectoryManagement
Import-Module Microsoft.Graph.Users
Import-Module Microsoft.Graph.Groups
Connect-MgGraph -Scopes "Organization.Read.All","User.Read.All","Group.Read.All"
$org = Get-MgOrganization -Property "id,displayName,onPremisesSyncEnabled,onPremisesLastSyncDateTime"
$last = $org.OnPremisesLastSyncDateTime
"Tenant: $($org.DisplayName)"
"Sync enabled: $($org.OnPremisesSyncEnabled)"
"Last sync (UTC): $last"
if ($last) { "Hours since last sync: {0:N1}" -f ((Get-Date).ToUniversalTime() - $last.ToUniversalTime()).TotalHours }
$users = Get-MgUser -All -Property "id,displayName,userPrincipalName,onPremisesSyncEnabled,onPremisesLastSyncDateTime,onPremisesProvisioningErrors"
$groups = Get-MgGroup -All -Property "id,displayName,onPremisesSyncEnabled,onPremisesLastSyncDateTime,onPremisesProvisioningErrors"
$objects = @($users | ForEach-Object { [pscustomobject]@{ Type = 'user'; Obj = $_ } }) +
@($groups | ForEach-Object { [pscustomobject]@{ Type = 'group'; Obj = $_ } })
$report = foreach ($item in $objects) {
$o = $item.Obj
foreach ($e in @($o.OnPremisesProvisioningErrors)) {
if (-not $e) { continue }
[pscustomobject]@{
ObjectType = $item.Type
DisplayName = $o.DisplayName
UserPrincipalName = if ($item.Type -eq 'user') { $o.UserPrincipalName } else { $null }
Category = $e.Category
PropertyCausingError = $e.PropertyCausingError
ConflictingValue = $e.Value
OccurredUtc = $e.OccurredDateTime
ObjectLastSyncUtc = $o.OnPremisesLastSyncDateTime
Id = $o.Id
}
}
}
$report | Sort-Object OccurredUtc -Descending |
Export-Csv -Path ".\sync-provisioning-errors.csv" -NoTypeInformation -Encoding UTF8
"Objects with sync errors: $(@($report | Select-Object -Unique Id).Count)"
Sample output columns- ObjectType, DisplayName, UserPrincipalName, Id: The synced user or group with the error
- Category:
PropertyConflict: another object already has this value - PropertyCausingError:
UserPrincipalName or ProxyAddress - ConflictingValue: The duplicate value; search the tenant for the other object that holds it
- OccurredUtc, ObjectLastSyncUtc: When the error occurred, and when this object last synced (UTC)
GotchasonPremisesSyncEnabled on the organization is true when the tenant syncs from on-premises, false if it used to and no longer does, and null if it never did (organization resource type (opens in a new tab)).- Times are UTC. Convert before comparing with local server logs.
- Only duplicate-attribute errors appear here. Other sync problems (connectivity, filtering, password hash sync) show in Microsoft Entra Connect or Cloud Sync health; see Microsoft Entra Connect and Cloud Sync Health Check.
- Reading every user and group is slow in large tenants; run it off-hours.
Microsoft Learn sources |
| Block sign-in for a list of users from CSV (with -WhatIf)Changes dataNot tested against a live tenant | Users, groups & guests | Read a CSV of UPNs, skip accounts synced from on-premises AD, and set accountEnabled to false for the rest, logging each result. Run with -WhatIf first. Details, command and permissionsWhat it doesChanges data. This script blocks sign-in for every account in the CSV. Disabling doesn't end sessions that are already open; revoke them too if the accounts may be compromised (Revoke a user's sign-in sessions). Run with -WhatIf first and check the log.
Use it for a batch of leavers, a contractor group ending, or a set of accounts you found in an inactivity review (Inactive user accounts). Accounts synced from on-premises AD are skipped and logged: disable those in Active Directory, where the source of authority is (Update user (opens in a new tab) notes that for synced users, what you can update depends on the source of authority). Requirements- Modules: Microsoft.Graph.Users
- Connect-MgGraph scopes (least privilege):
User.EnableDisableAccount.All + User.Read.All, documented as the least-privileged combination for updating accountEnabled (Update user (opens in a new tab)). - Least-privileged admin role: Disabling users is a sensitive action. User Administrator can disable users with no admin role and some admin roles (for example Helpdesk, Groups and User Administrators); Privileged Authentication Administrator is needed for all administrators (Who can perform sensitive actions (opens in a new tab)).
- License: None stated.
- Flag: Changes data (supports
-WhatIf and -Confirm) - Label: Not tested against a live tenant
- Learn checked: 2026-12-02
Command# CHANGES DATA. Not tested against a live tenant. Run with -WhatIf first.
# CSV needs a column named UserPrincipalName.
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
[Parameter(Mandatory)] [string] $CsvPath
)
Import-Module Microsoft.Graph.Users
Connect-MgGraph -Scopes "User.EnableDisableAccount.All","User.Read.All"
$log = foreach ($row in Import-Csv -Path $CsvPath) {
$upn = $row.UserPrincipalName.Trim()
try {
$u = Get-MgUser -UserId $upn -Property "id,userPrincipalName,accountEnabled,onPremisesSyncEnabled" -ErrorAction Stop
} catch {
[pscustomobject]@{ User = $upn; Action = 'Failed: not found'; Detail = $_.Exception.Message }; continue
}
if ($u.OnPremisesSyncEnabled) {
[pscustomobject]@{ User = $upn; Action = 'Skipped: synced from on-premises'; Detail = 'Disable in Active Directory' }; continue
}
if ($u.AccountEnabled -eq $false) {
[pscustomobject]@{ User = $upn; Action = 'Skipped: already disabled'; Detail = '' }; continue
}
if ($PSCmdlet.ShouldProcess($upn, "Block sign-in (accountEnabled = false)")) {
try {
Update-MgUser -UserId $u.Id -BodyParameter @{ accountEnabled = $false } -ErrorAction Stop
[pscustomobject]@{ User = $upn; Action = 'Disabled'; Detail = '' }
} catch {
[pscustomobject]@{ User = $upn; Action = 'Failed'; Detail = $_.Exception.Message }
}
} else {
[pscustomobject]@{ User = $upn; Action = 'Not changed (WhatIf or declined)'; Detail = '' }
}
}
$log | Export-Csv -Path ".\bulk-disable-users-log.csv" -NoTypeInformation -Encoding UTF8
$log | Group-Object Action | Select-Object Name, Count
Run it: .\Disable-UsersFromCsv.ps1 -CsvPath .\leavers.csv -WhatIf # preview
.\Disable-UsersFromCsv.ps1 -CsvPath .\leavers.csv # prompts per user (ConfirmImpact High)
.\Disable-UsersFromCsv.ps1 -CsvPath .\leavers.csv -Confirm:$false # no prompts
Sample output columns- User: UPN from the CSV
- Action:
Disabled, Not changed (WhatIf or declined), Skipped: synced from on-premises, Skipped: already disabled, Failed: not found or Failed - Detail: Error message or reason
GotchasFailed rows for admin accounts usually mean your role can't disable that admin role; see the sensitive actions table linked above.- Don't include break-glass accounts or the account you're running as.
- Licenses aren't removed. Follow up with Remove direct licenses from disabled users once mailboxes and data are handled (Offboard a Departing User).
- To undo, run the same loop with
accountEnabled = $true for the users the log shows as Disabled.
Microsoft Learn sources |
| Export apps with expiring secrets and certificatesRead-onlyOfficial Microsoft sample | Apps & consent | List app registrations whose secrets or certificates expire soon, before they cause an outage. Details, command and permissionsWhat it doesExports app registrations whose secrets or certificates expire in the next X days (optionally including already-expired ones), with owners, to a CSV. Uses Connect-MgGraph -Scopes 'Application.Read.All', Get-MgApplication, and Get-MgApplicationOwner. Why admins use itAn expired app secret is a common outage, and long-lived secrets that are never reviewed are a security gap. SourceModules and permissionsMicrosoft Graph PowerShell SDK. Scope: Application.Read.All. LicenseNo extra Entra ID P1 or P2 requirement is stated on the sample page (this is a directory read of applications). Last checkedDecember 1, 2026 CaveatsThe sample pages include Microsoft's usual as-is disclaimer. Use this current Graph SDK sample, not older AzureAD-module copies of the same idea. |
| List delegated app consent grantsRead-onlyOfficial Microsoft sample | Apps & consent | See which apps have been granted delegated permissions in the tenant. Details, command and permissionsWhat it doesLists oauth2PermissionGrant objects (delegated permission grants) in the tenant with Get-MgOauth2PermissionGrant. Why admins use itA common review after a guest, vendor, or suspicious consent: which apps have access, and with which delegated permissions. SourceMicrosoft Graph: List oAuth2PermissionGrant (PowerShell tab) (opens in a new tab) Modules and permissionsMicrosoft Graph. Least-privileged permission documented on this API page: Directory.Read.All (delegated and application). Higher-privileged alternatives listed include DelegatedPermissionGrant.ReadWrite.All and Directory.ReadWrite.All, which are more than a report needs. For delegated access, the signed-in user must have a supported Entra role (or custom role) that grants the permission. LicenseNo extra Entra ID P1 or P2 sentence was stated on this API page. Last checkedDecember 1, 2026 CaveatsGrants are easier to read if you also resolve service principal and user names (Application.Read.All or User.Read.All may be needed for a friendlier report). Do not point at revoke or update examples as if they were this starter report. This is a documented cmdlet example, not a standalone .ps1 file. |
| Application permissions granted to an appRead-onlyMicrosoft Learn cmdlet example | Apps & consent | List the application (app-only) permissions granted to one service principal. Details, command and permissionsWhat it doesGet-MgServicePrincipalAppRoleAssignment lists app role assignments granted to a service principal, which is how application permissions are recorded. Why admins use itDelegated grants are only half the picture; app-only permissions such as Mail.Read for all mailboxes show up here. CommandConnect-MgGraph -Scopes "Application.Read.All"
Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId <service-principal-object-id> -All
SourceModules and permissionsMicrosoft.Graph.Applications. Least-privileged permission on the API page: Application.Read.All. LicenseNo license requirement is stated on the API page. Last checkedDecember 1, 2026 CaveatsRead-only. Learn's review page also has Graph PowerShell that revokes permissions; that part modifies the tenant. |
| App registration ownersRead-onlyMicrosoft Learn cmdlet example | Apps & consent | List who owns an app registration, so expiring secrets and consent questions have someone to go to. Details, command and permissionsWhat it doesGet-MgApplicationOwner lists the owners of an application object. Why admins use itApps without an owner are hard to rotate and easy to forget. CommandConnect-MgGraph -Scopes "Application.Read.All"
Get-MgApplicationOwner -ApplicationId <application-object-id>
SourceModules and permissionsMicrosoft.Graph.Applications. Least-privileged permission on the API page: Application.Read.All. LicenseNo license requirement is stated on the API page. Last checkedDecember 1, 2026 CaveatsRead-only. -ApplicationId is the application's object ID, not the client (app) ID. |
| Tenant-wide app role assignments (application permissions)Read-onlyNot tested against a live tenant | Apps & consent | List app role assignments for every service principal in the tenant (application permissions granted app-only), not just one app. Details, command and permissionsWhat it doesThis is the tenant-wide version of App role assignments for a service principal, which covers one service principal. It lists every service principal, then every app role assignment granted to that principal (GET /servicePrincipals/{id}/appRoleAssignedTo is the other direction; this script uses GET /servicePrincipals/{id}/appRoleAssignments). Those assignments are the application (app-only) permissions a service principal has been granted on a resource app. OAuth2 permission grants (delegated) is the delegated-consent counterpart and is not included here. Requirements- Module: Microsoft.Graph.Applications
- Connect-MgGraph scopes (least privilege):
Application.Read.All (the List appRoleAssignments API also lists Directory.Read.All as a higher privileged permission) - Least-privileged admin role: Directory Readers (the List API also lists Cloud Application Administrator and Application Administrator, among others)
- License: No extra license is stated on the List appRoleAssignments API for this read
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-11-27
Command# Read-only. Not tested against a live tenant.
# Tenant-wide: every service principal, then its app role assignments.
# This will run a long time in a large tenant. -All pages both lists.
# Docs: GET /servicePrincipals
# GET /servicePrincipals/{id}/appRoleAssignments
Import-Module Microsoft.Graph.Applications
Connect-MgGraph -Scopes "Application.Read.All"
Write-Host "Listing service principals (this can take a while)..."
$servicePrincipals = Get-MgServicePrincipal -All -Property "id,displayName,appId,servicePrincipalType"
# Optional lookup: resource app + app role display name.
# This is an extra read-only call per unique resourceId.
$resourceCache = @{}
$report = foreach ($sp in $servicePrincipals) {
$assignments = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $sp.Id -All
foreach ($assignment in $assignments) {
$roleName = $assignment.AppRoleId
$resourceName = $assignment.ResourceDisplayName
if ($assignment.ResourceId) {
if (-not $resourceCache.ContainsKey($assignment.ResourceId)) {
try {
$resource = Get-MgServicePrincipal -ServicePrincipalId $assignment.ResourceId -Property "id,displayName,appRoles"
$resourceCache[$assignment.ResourceId] = $resource
}
catch {
$resourceCache[$assignment.ResourceId] = $null
}
}
$resource = $resourceCache[$assignment.ResourceId]
if ($resource) {
$resourceName = $resource.DisplayName
$role = $resource.AppRoles | Where-Object { $_.Id -eq $assignment.AppRoleId } | Select-Object -First 1
if ($role) { $roleName = $role.Value }
if ($role -and $role.DisplayName) { $roleDisplayName = $role.DisplayName } else { $roleDisplayName = $null }
}
else {
$roleDisplayName = $null
}
}
else {
$roleDisplayName = $null
}
[pscustomobject]@{
PrincipalDisplayName = $sp.DisplayName
PrincipalId = $sp.Id
PrincipalAppId = $sp.AppId
PrincipalType = $sp.ServicePrincipalType
ResourceDisplayName = $resourceName
ResourceId = $assignment.ResourceId
AppRoleId = $assignment.AppRoleId
AppRoleValue = $roleName
AppRoleDisplayName = $roleDisplayName
CreatedDateTime = $assignment.CreatedDateTime
AssignmentId = $assignment.Id
}
}
}
$report | Sort-Object PrincipalDisplayName, ResourceDisplayName, AppRoleValue |
Export-Csv -Path ".\tenant-app-role-assignments.csv" -NoTypeInformation -Encoding UTF8
"Service principals examined: $($servicePrincipals.Count)"
"App role assignments found: $($report.Count)"
Sample output columns- PrincipalDisplayName, PrincipalId, PrincipalAppId, PrincipalType: The service principal that was granted the role
- ResourceDisplayName, ResourceId: The resource application (for example Microsoft Graph)
- AppRoleId: The app role GUID
- AppRoleValue, AppRoleDisplayName: Role
value and display name, when the resource's appRoles could be read - CreatedDateTime, AssignmentId: When the grant was created, and the assignment object ID
Gotchas- Runtime and paging. The script calls
Get-MgServicePrincipal -All, then Get-MgServicePrincipalAppRoleAssignment -All once per principal, plus an optional lookup per unique resource. In a large tenant this can take a long time and may hit throttling. Run it in a window you can leave running, and expect Graph to page automatically via -All. - This lists assignments to each service principal (application permissions the app has been granted). It is not a list of who has been assigned roles on a given app. For one resource app, the existing App role assignments for a service principal is the more targeted starting point.
- The optional role-name lookup is read-only. If it fails,
AppRoleValue falls back to the role GUID. - This report does not rank permissions as high risk. Review
AppRoleValue yourself against your consent policy.
Microsoft Learn sources |
| App registrations with no ownerRead-onlyNot tested against a live tenant | Apps & consent | Tenant-wide list of app registrations with their owner count and next credential expiry, so you can find apps nobody owns before a secret or certificate expires. Details, command and permissionsWhat it doesApp registration owners shows the owners of one app. This script walks every app registration in the tenant and counts owners, so you get the list of apps with nobody to contact when a secret expires or a consent question comes up. It also shows the soonest credential expiry for each app. RequirementsCommand# Read-only. Not tested against a live tenant.
# One owner call per app: slow in tenants with many app registrations.
Import-Module Microsoft.Graph.Applications
Connect-MgGraph -Scopes "Application.Read.All"
$apps = Get-MgApplication -All -Property "id,appId,displayName,createdDateTime,signInAudience,passwordCredentials,keyCredentials"
$report = foreach ($app in $apps) {
$owners = @(Get-MgApplicationOwner -ApplicationId $app.Id -All)
$ends = @($app.PasswordCredentials.EndDateTime) + @($app.KeyCredentials.EndDateTime) |
Where-Object { $_ } | Sort-Object
[pscustomobject]@{
DisplayName = $app.DisplayName
AppId = $app.AppId
OwnerCount = $owners.Count
Owners = ($owners | ForEach-Object {
if ($_.AdditionalProperties['userPrincipalName']) { $_.AdditionalProperties['userPrincipalName'] }
else { $_.AdditionalProperties['displayName'] } }) -join '; '
SecretCount = @($app.PasswordCredentials).Count
CertificateCount = @($app.KeyCredentials).Count
NextCredentialEnd = $ends | Select-Object -First 1
SignInAudience = $app.SignInAudience
Created = $app.CreatedDateTime
ObjectId = $app.Id
}
}
$report | Sort-Object OwnerCount, NextCredentialEnd |
Export-Csv -Path ".\app-registration-owners.csv" -NoTypeInformation -Encoding UTF8
"App registrations: $($report.Count)"
"With no owner: $(@($report | Where-Object OwnerCount -eq 0).Count)"
Sample output columns- DisplayName, AppId, ObjectId: The app registration (ObjectId is what the owner cmdlet uses)
- OwnerCount, Owners: Number of owners and their UPNs (or display names for non-user owners)
- SecretCount, CertificateCount: Client secrets and certificates on the app
- NextCredentialEnd: Earliest secret or certificate end date (UTC); may already be in the past
- SignInAudience: Single-tenant or multitenant
- Created: When the registration was created
Gotchas- App registrations only. Enterprise applications (service principals), including Microsoft and third-party apps, aren't included; those have their own owners.
- Owners can be service principals, not only users; they still count.
- The script doesn't check whether owners are still active accounts. An app whose only owner has left needs a new owner just as much; compare
Owners with your leaver list. - For expiring credentials in detail, use Export apps with expiring secrets and certificates.
Microsoft Learn sources |
| Intune device report exportRead-onlyOfficial Microsoft sample | Devices & Intune | Export Intune devices, including compliance state, to support compliant-device Conditional Access. Details, command and permissionsWhat it doesThe official Learn page documents the Intune report export API, including a Devices report whose selected columns include complianceState. The official GitHub sample creates an export job, waits until it is ready, downloads the zip, and extracts CSV (and optionally JSON). The sample's built-in request body is the DeviceEncryption report; the comment in the script points at the same Learn article for building other report bodies. Why admins use itYou need a list of noncompliant or unmanaged-looking devices when you require a compliant device in Conditional Access. SourceModules and permissionsMicrosoft.Graph.Reports (sample import). The sample uses Invoke-MgGraphRequest. An Intune administrator account and an Intune license are required per the repository README. LicenseIntune (production or trial), per the repository README. Last checkedDecember 1, 2026 CaveatsTo get noncompliant devices, use the official Devices report body from Learn, not the sample's default DeviceEncryption body — still the same official sample pattern. The script creates a temporary export job (POST to deviceManagement/reports/exportJobs) but does not change compliance policies or device settings. Treat it as a report. Do not copy a modified script onto this site; change reportName as Microsoft documents. |
| Stale devices report (activity timestamp)Read-onlyMicrosoft Learn cmdlet example | Devices & Intune | Export devices that haven't signed in for 90 days, before you disable anything. Details, command and permissionsWhat it doesMicrosoft's stale-device how-to lists devices with Get-MgDevice and filters on ApproximateLastSignInDateTime (the activity timestamp), exporting to CSV. Why admins use itThe report-first step of Microsoft's cleanup routine: review it before you disable or delete. Command$dt = (Get-Date).AddDays(-90)
Get-MgDevice -All | Where {$_.ApproximateLastSignInDateTime -le $dt} | Select-Object -Property AccountEnabled, DeviceId, OperatingSystem, OperatingSystemVersion, DisplayName, TrustType, ApproximateLastSignInDateTime | Export-Csv devicelist-olderthan-90days-summary.csv -NoTypeInformation
SourceModules and permissionsMicrosoft.Graph.Identity.DirectoryManagement. Least-privileged permission on the API page: Device.Read.All. LicenseNo license requirement is stated on these pages. Last checkedDecember 1, 2026 CaveatsRead-only. Learn warns that some active devices may have a blank timestamp, and system-managed devices such as Autopilot need care. |
| List BitLocker recovery keys for a deviceRead-onlyMicrosoft Learn cmdlet example | Devices & Intune | Find the BitLocker recovery key IDs stored for a device, and read a key when you need it. Details, command and permissionsWhat it doesGet-MgInformationProtectionBitlockerRecoveryKey lists recovery key objects and can filter by deviceId. By default the key value isn't returned; selecting it with -Property key on a single key returns it and writes an audit log entry. Why admins use itBack up keys before you delete stale devices: Learn says deleted devices lose their keys for good. CommandConnect-MgGraph -Scopes "BitlockerKey.ReadBasic.All"
Get-MgInformationProtectionBitlockerRecoveryKey -Filter "deviceId eq '<device-id>'"
SourceModules and permissionsMicrosoft.Graph.Identity.SignIns. Least-privileged permission on the API pages: BitlockerKey.ReadBasic.All (BitlockerKey.Read.All is the higher one listed). Delegated callers must own the device or hold a supported role such as Cloud Device Administrator or Helpdesk Administrator. LicenseNo license requirement is stated on these API pages. Last checkedDecember 1, 2026 CaveatsRead-only, but sensitive: viewing a key is audited (KeyManagement category). Store exported keys securely. |
| Export Intune compliance policiesRead-onlyMicrosoft Learn cmdlet example | Devices & Intune | List your Intune device compliance policies so you can review or back them up. Details, command and permissionsWhat it doesGet-MgDeviceManagementDeviceCompliancePolicy lists deviceCompliancePolicy objects. Why admins use itSee what "compliant" means in your tenant before you require compliant devices in Conditional Access. CommandConnect-MgGraph -Scopes "DeviceManagementConfiguration.Read.All"
Get-MgDeviceManagementDeviceCompliancePolicy -All | ConvertTo-Json -Depth 10 | Out-File compliance-policies.json
SourceModules and permissionsMicrosoft.Graph.DeviceManagement. Least-privileged permission on the API page: DeviceManagementConfiguration.Read.All. LicenseRequires Microsoft Intune. Last checkedDecember 1, 2026 CaveatsRead-only. The change-making import sample is listed separately. |
| List Windows Autopilot devicesRead-onlyMicrosoft Learn cmdlet example | Devices & Intune | Export the devices registered for Windows Autopilot. Details, command and permissionsWhat it doesGet-MgDeviceManagementWindowsAutopilotDeviceIdentity lists windowsAutopilotDeviceIdentity objects. Why admins use itCheck a device is registered (and to which profile) before you troubleshoot an enrollment. CommandConnect-MgGraph -Scopes "DeviceManagementServiceConfig.Read.All"
Get-MgDeviceManagementWindowsAutopilotDeviceIdentity -All | Export-Csv autopilot-devices.csv -NoTypeInformation
SourceModules and permissionsMicrosoft.Graph.DeviceManagement.Enrollment. Least-privileged permission on the API page: DeviceManagementServiceConfig.Read.All. LicenseRequires Microsoft Intune (Autopilot licensing is on Microsoft Learn's Autopilot requirements page). Last checkedDecember 1, 2026 CaveatsRead-only. |
| List Intune managed devicesRead-onlyMicrosoft Learn cmdlet example | Devices & Intune | Export Intune managed devices with their compliance state and last check-in. Details, command and permissionsWhat it doesGet-MgDeviceManagementManagedDevice lists managedDevice objects from Intune. Why admins use itA quick inventory when the Intune export job report is more than you need. CommandConnect-MgGraph -Scopes "DeviceManagementManagedDevices.Read.All"
Get-MgDeviceManagementManagedDevice -All | Select-Object DeviceName, UserPrincipalName, OperatingSystem, ComplianceState, LastSyncDateTime | Export-Csv managed-devices.csv -NoTypeInformation
SourceModules and permissionsMicrosoft.Graph.DeviceManagement. Least-privileged permission on the API page: DeviceManagementManagedDevices.Read.All. LicenseRequires Microsoft Intune. Last checkedDecember 1, 2026 CaveatsRead-only. |
| Import an Intune compliance policy from JSONChanges dataOfficial Microsoft sample | Devices & Intune | Creates a device compliance policy from a previously exported JSON file. Details, command and permissionsWhat it doesOfficial microsoft/mggraph-intune-samples script that pairs with CompliancePolicy_Export.ps1. It creates a policy with New-MgDeviceManagementDeviceCompliancePolicy. Why admins use itA backup and restore pattern for Intune compliance policies, after you have reviewed the export. SourceOfficial sample: CompliancePolicy_Import_FromJSON.ps1 (opens in a new tab) Modules and permissionsMicrosoft Graph PowerShell, from microsoft/mggraph-intune-samples. LicenseIntune, per the repository README. Last checkedDecember 1, 2026 CaveatsThis creates a policy. The repository README says to test in a non-production tenant. |
| Disable stale devicesChanges dataMicrosoft Learn cmdlet example | Devices & Intune | Disable devices with no activity for 90 days, after you reviewed the report. Details, command and permissionsWhat it doesMicrosoft's stale-device how-to pipes the 90-day list into Update-MgDevice with accountEnabled = $false. Deletion is a later, separate step that can't be undone. Why admins use itDisabling first gives you a grace period: a device someone still needs can be re-enabled. Command (dry run first)$dt = (Get-Date).AddDays(-90)
$params = @{ accountEnabled = $false }
$Devices = Get-MgDevice -All | Where {$_.ApproximateLastSignInDateTime -le $dt}
# Dry run first: review $Devices (or the Stale devices report CSV), then preview
foreach ($Device in $Devices) { Update-MgDevice -DeviceId $Device.Id -BodyParameter $params -WhatIf }
Dry run firstRun the Stale devices report first and review the CSV, then run the loop with -WhatIf before removing it. SourceModules and permissionsMicrosoft.Graph.Identity.DirectoryManagement. The Update device page lists Directory.AccessAsUser.All for delegated calls (Device.ReadWrite.All for application). Enabling or disabling a device needs Intune Administrator or Cloud Device Administrator. LicenseNo license requirement is stated on these pages. Last checkedDecember 1, 2026 CaveatsChanges data. Back up BitLocker keys before any later deletion; Learn says BitLocker keys can't be recovered after the device is deleted. |
| Export Intune app protection (MAM) policiesRead-onlyNot tested against a live tenant | Devices & Intune | List Intune app protection (MAM) policies in the tenant, including each policy's type, platforms, and last modified time. Details, command and permissionsWhat it doesLists app protection policies from GET /deviceAppManagement/managedAppPolicies. This is the policy catalog, not a report of which users or devices have the policy applied, and not a device compliance policy export (see Export Intune compliance policies). Requirements- Module: Microsoft.Graph.Devices.CorporateManagement
- Connect-MgGraph scopes (least privilege):
DeviceManagementApps.Read.All (DeviceManagementApps.ReadWrite.All is also listed, as a higher privileged permission) - Least-privileged admin role: The List managedAppPolicies API page documents application permissions only; it does not list a Microsoft Entra or Intune admin role. Do not assume Intune Administrator is documented for this API. Use a role that your tenant already uses to read Intune app protection policies in the admin center, and grant the Graph scope above.
- License: The List managedAppPolicies page notes: "The Microsoft Graph API for Intune requires an active Intune license for the tenant."
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-11-27
Command# Read-only. Not tested against a live tenant.
# List Intune managed app (app protection / MAM) policies.
# Docs: GET /deviceAppManagement/managedAppPolicies
Import-Module Microsoft.Graph.Devices.CorporateManagement
Connect-MgGraph -Scopes "DeviceManagementApps.Read.All"
$policies = Get-MgDeviceAppManagementManagedAppPolicy -All
$report = foreach ($policy in $policies) {
$odataType = $null
if ($policy.AdditionalProperties.ContainsKey('@odata.type')) {
$odataType = $policy.AdditionalProperties['@odata.type']
}
[pscustomobject]@{
DisplayName = $policy.DisplayName
Id = $policy.Id
Description = $policy.Description
ODataType = $odataType
CreatedDateTime = $policy.CreatedDateTime
LastModifiedDateTime = $policy.LastModifiedDateTime
Version = $policy.Version
}
}
$report | Sort-Object DisplayName |
Export-Csv -Path ".\intune-mam-policies.csv" -NoTypeInformation -Encoding UTF8
"App protection (managed app) policies: $($report.Count)"
Sample output columns- DisplayName, Id, Description: Policy identity
- ODataType: Derived type (for example an Android, iOS, or Windows managed app policy type), when the module returns
@odata.type - CreatedDateTime, LastModifiedDateTime, Version: When the policy was created or last changed
Gotchas- The list returns the base
managedAppPolicy type. Platform-specific settings live on derived types; this export does not expand every setting. Open the policy in the Intune admin center, or GET the derived type, if you need the full configuration. - No Microsoft Entra least-privileged role is documented on the list API page; only the Graph application permission is. That is flagged in Requirements.
- An Intune license for the tenant is required to call Intune Graph APIs. This script does not check whether that license is present.
-All pages the full list.
Microsoft Learn sources |
| Export Intune configuration profiles (templates and Settings catalog)Read-onlyNot tested against a live tenant | Devices & Intune | List Intune device configuration profiles with their type and last change, and optionally Settings catalog policies (beta API) with platform, setting count and whether they're assigned. Details, command and permissionsWhat it doesExport Intune compliance policies covers compliance. This script covers configuration profiles, which live in two places in Microsoft Graph: Requirements- Modules: Microsoft.Graph.DeviceManagement; Microsoft.Graph.Beta.DeviceManagement only for
-IncludeSettingsCatalog - Connect-MgGraph scopes (least privilege):
DeviceManagementConfiguration.Read.All (listed for both APIs) - Least-privileged admin role: The Graph pages list permissions only; no Intune or Microsoft Entra role is named. Use an Intune role that can read device configurations.
- License: The Microsoft Graph API for Intune requires an active Intune license for the tenant.
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-12-02
Command# Read-only. Not tested against a live tenant.
param([switch] $IncludeSettingsCatalog)
Import-Module Microsoft.Graph.DeviceManagement
Connect-MgGraph -Scopes "DeviceManagementConfiguration.Read.All"
$rows = foreach ($p in Get-MgDeviceManagementDeviceConfiguration -All) {
[pscustomobject]@{
Source = 'deviceConfiguration (v1.0)'
Name = $p.DisplayName
Type = ($p.AdditionalProperties['@odata.type'] -replace '#microsoft.graph.', '')
Platforms = $null
SettingCount = $null
IsAssigned = $null
Created = $p.CreatedDateTime
LastModified = $p.LastModifiedDateTime
Version = $p.Version
Id = $p.Id
}
}
if ($IncludeSettingsCatalog) {
Import-Module Microsoft.Graph.Beta.DeviceManagement
$rows += foreach ($p in Get-MgBetaDeviceManagementConfigurationPolicy -All) {
[pscustomobject]@{
Source = 'configurationPolicy (beta, Settings catalog)'
Name = $p.Name
Type = 'settingsCatalog'
Platforms = $p.Platforms
SettingCount = $p.SettingCount
IsAssigned = $p.IsAssigned
Created = $p.CreatedDateTime
LastModified = $p.LastModifiedDateTime
Version = $null
Id = $p.Id
}
}
}
$rows | Sort-Object Source, Name |
Export-Csv -Path ".\intune-config-profiles.csv" -NoTypeInformation -Encoding UTF8
"Profiles exported: $(@($rows).Count)"
Sample output columns- Source: v1.0 template profile or beta Settings catalog policy
- Name: Profile name
- Type: For templates, the derived type, for example
windowsUpdateForBusinessConfiguration for an update ring - Platforms, SettingCount, IsAssigned: Settings catalog only;
IsAssigned False means the policy isn't deployed to anyone - Created, LastModified: UTC timestamps
- Version: Template profiles only
- Id: Policy ID
Gotchas- Without
-IncludeSettingsCatalog you miss Settings catalog policies, which many newer tenants use for most configuration. - The export lists policies, not their individual settings or assignments.
Type names come from @odata.type; the v1.0 list documents the base deviceConfiguration type, and each profile returns its specific derived type.
Microsoft Learn sources |
| License assignment reportRead-onlyOfficial Microsoft sample | Licensing | See which licenses are consumed and which user has which service plan. Details, command and permissionsWhat it doesLists subscribed SKUs and consumed units, and per-user license and service-plan details, using Get-MgSubscribedSku and Get-MgUserLicenseDetail. The official Microsoft 365 Enterprise "view licenses" pages now use these Graph cmdlets (not MSOnline). Why admins use itA regular MSP and tenant-hygiene question: who is licensed, who is not, and which service plans are assigned. SourceModules and permissionsMicrosoft Graph (Identity.DirectoryManagement, Users). Scopes observed: Organization.Read.All, User.Read.All, Directory.Read.All, LicenseAssignment.Read.All. LicenseNo Entra ID P1 requirement was stated on these pages (this is license inventory, not a P1-gated report). Last checkedDecember 1, 2026 CaveatsThese view pages are read-only. The separate "Assign Microsoft 365 licenses" how-to uses User.ReadWrite.All and makes changes; it is listed under Related change-making samples, not here. These are documented cmdlet examples, not a standalone .ps1 file. |
| Groups and users with license errorsRead-onlyMicrosoft Learn cmdlet example | Licensing | Find groups whose members have group-based licensing errors, then the users in error. Details, command and permissionsWhat it doesThe List groups API page shows Get-MgGroup with the hasMembersWithLicenseErrors filter. Learn's group-based licensing PowerShell examples add samples that list the users with errors in a group or in the whole organization. Why admins use itGroup-based licensing fails in the background; this finds the errors before users notice missing apps. CommandConnect-MgGraph -Scopes "Group.Read.All","User.Read.All"
Get-MgGroup -Filter "hasMembersWithLicenseErrors eq true" -Property "id,displayName"
SourceModules and permissionsMicrosoft.Graph.Groups and Microsoft.Graph.Users. The examples page connects with Group.Read.All and User.Read.All for users in a group. LicenseNo license requirement is stated on these pages. Last checkedDecember 1, 2026 CaveatsRead-only. Fix the cause (not enough licenses, conflicting plans, usage location) in the admin center, then reprocess. |
| Assign Microsoft 365 licensesChanges dataOfficial Microsoft sample | Licensing | Assign licenses to user accounts with Microsoft Graph PowerShell. Details, command and permissionsWhat it doesOfficial Microsoft 365 Enterprise how-to for assigning licenses. It uses User.ReadWrite.All and writes license assignments. Why admins use itThe official counterpart to the read-only license report, when you actually need to assign a license. SourceMicrosoft Learn: Assign Microsoft 365 licenses to user accounts with PowerShell (opens in a new tab) Modules and permissionsMicrosoft Graph PowerShell. Scope documented on the page: User.ReadWrite.All (and Organization.Read.All). LicenseYou can only assign licenses your tenant already owns. Last checkedDecember 1, 2026 CaveatsThis how-to writes licenses. It is not a report. Review it and test in a lab or non-production tenant first. |
| Groups with assigned licensesRead-onlyNot tested against a live tenant | Licensing | List Microsoft Entra groups that have licenses assigned, including which SKUs each group assigns. Details, command and permissionsWhat it doesLists groups that have one or more licenses assigned (assignedLicenses). Group license assignment errors reports users who failed to receive a group license. This script is the group-side inventory: which groups assign licenses, and which SKUs. The official examples page uses this pattern: Get-MgGroup -All -Property Id, MailNickname, DisplayName, GroupTypes, Description, AssignedLicenses | Where-Object {$_.AssignedLicenses -ne $null }. This script follows that sample and joins SKU part numbers from Get-MgSubscribedSku. It does not assign or remove licenses. Requirements- Modules: Microsoft.Graph.Groups, Microsoft.Graph.Identity.DirectoryManagement
- Connect-MgGraph scopes (least privilege):
Group.Read.All and LicenseAssignment.Read.All. LicenseAssignment.Read.All is the least privileged permission on the List subscribedSkus API (Organization.Read.All and Directory.Read.All are listed as higher privileged). The official examples page uses Group.ReadWrite.All only in samples that also assign or remove licenses; this report does not. - Least-privileged admin role: The List groups API page does not currently document a specific Microsoft Entra admin role; it only lists Graph permissions. For List subscribedSkus, the documented roles include Directory Readers and Global Reader. Use a role that can already read groups and subscribed SKUs in your tenant.
- License: No extra license is stated on the List groups API or the PowerShell examples page for this read. Using group-based licensing to assign licenses has its own requirements; this script only reports existing assignments.
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-11-27
Command# Read-only. Not tested against a live tenant.
# Official pattern from licensing-powershell-graph-examples:
# Get-MgGroup -All -Property Id, MailNickname, DisplayName, GroupTypes, Description, AssignedLicenses |
# Where-Object { $_.AssignedLicenses -ne $null }
# Docs: GET /groups
# GET /subscribedSkus
# licenseProcessingState is documented as supported only on GET /groups/{id},
# so it is requested in a second, read-only call per licensed group.
Import-Module Microsoft.Graph.Groups
Import-Module Microsoft.Graph.Identity.DirectoryManagement
Connect-MgGraph -Scopes "Group.Read.All","LicenseAssignment.Read.All"
$skus = @{}
Get-MgSubscribedSku -All | ForEach-Object {
$skus[$_.SkuId.ToString()] = $_.SkuPartNumber
}
$groups = Get-MgGroup -All -Property "Id,MailNickname,DisplayName,GroupTypes,Description,AssignedLicenses"
# Official sample uses -ne $null. Also require a non-empty collection.
$licensed = $groups | Where-Object { $_.AssignedLicenses -and @($_.AssignedLicenses).Count -gt 0 }
$report = foreach ($group in $licensed) {
$skuIds = @($group.AssignedLicenses | ForEach-Object { $_.SkuId.ToString() })
$partNumbers = $skuIds | ForEach-Object { if ($skus.ContainsKey($_)) { $skus[$_] } else { $_ } }
$processingState = $null
try {
$detail = Get-MgGroup -GroupId $group.Id -Property "Id,LicenseProcessingState"
$processingState = $detail.LicenseProcessingState
}
catch {
$processingState = $null
}
[pscustomobject]@{
DisplayName = $group.DisplayName
MailNickname = $group.MailNickname
Id = $group.Id
GroupTypes = ($group.GroupTypes -join '; ')
Description = $group.Description
SkuPartNumbers = ($partNumbers -join '; ')
SkuIds = ($skuIds -join '; ')
LicenseProcessingState = $processingState
DisabledPlansCount = @($group.AssignedLicenses | ForEach-Object { @($_.DisabledPlans).Count } | Measure-Object -Sum).Sum
}
}
$report | Sort-Object DisplayName |
Export-Csv -Path ".\groups-with-licenses.csv" -NoTypeInformation -Encoding UTF8
"Groups examined: $($groups.Count)"
"Groups with assigned licenses: $($report.Count)"
Sample output columns- DisplayName, MailNickname, Id: The group
- GroupTypes, Description: Group type and description from the official property list
- SkuPartNumbers, SkuIds: SKUs the group assigns, resolved from subscribed SKUs when possible
- LicenseProcessingState: From a follow-up
GET /groups/{id} (the group resource says this property is supported only on the Get group API). Possible values include QueuedForProcessing and the other values listed on that resource; a blank cell means it was not returned. - DisabledPlansCount: How many service plans are disabled across the group's assigned licenses (count only;
disabledPlans is a property of assignedLicense (opens in a new tab))
Gotchas- This is not the user-error report. For users who failed to receive a group license, use Group license assignment errors.
-All pages every group, then the script filters client-side for AssignedLicenses, matching the official example. That can take time in a large tenant. The follow-up Get for licenseProcessingState runs only for groups that already have licenses.- The script does not call any license-assignment cmdlet.
Microsoft Learn sources |
| Disabled user accounts that still have licensesRead-onlyNot tested against a live tenant | Licensing | List sign-in blocked (accountEnabled eq false) users who still have assigned licenses, including whether the license came from a group. Details, command and permissionsWhat it doesLicense assignment report is a tenant-wide inventory of who has which SKU. This script is narrower: it starts with the documented filter accountEnabled eq false, then keeps users who also have assignedLicenses. The result is disabled (sign-in blocked) accounts that are still consuming a license. licenseAssignmentStates is included so you can see whether a license was assigned directly or assignedByGroup. The script does not remove licenses and has no -WhatIf path.
Requirements- Modules: Microsoft.Graph.Users, Microsoft.Graph.Identity.DirectoryManagement
- Connect-MgGraph scopes (least privilege):
User.Read.All and LicenseAssignment.Read.All. LicenseAssignment.Read.All is the least privileged permission on the List subscribedSkus API (Organization.Read.All and Directory.Read.All are listed as higher privileged). User.ReadBasic.All is listed as a more least-privileged permission on List users, but this script requests assignedLicenses and licenseAssignmentStates, so it uses User.Read.All. - Least-privileged admin role: The List users API page does not currently document a specific Microsoft Entra admin role. For List subscribedSkus, the documented roles include Directory Readers and Global Reader. Use a role that can already list users and subscribed SKUs in your tenant.
- License: No extra license is stated on the List users API for this read. Group-based licensing has its own requirements if you use
assignedByGroup; this script only reports existing assignments. - Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-11-27
Command# Read-only. Not tested against a live tenant.
# Distinct from /scripts#license-assignment-report:
# filter accountEnabled eq false, then keep users with assignedLicenses.
# Docs: GET /users?$filter=accountEnabled eq false
# licenseAssignmentStates shows direct vs assignedByGroup.
Import-Module Microsoft.Graph.Users
Import-Module Microsoft.Graph.Identity.DirectoryManagement
Connect-MgGraph -Scopes "User.Read.All","LicenseAssignment.Read.All"
$skus = @{}
Get-MgSubscribedSku -All | ForEach-Object {
$skus[$_.SkuId.ToString()] = $_.SkuPartNumber
}
# Documented filter only. Do not combine with assignedLicenses in $filter
# unless you have confirmed that combination as an advanced query in your SDK.
$disabled = Get-MgUser -All `
-Filter "accountEnabled eq false" `
-Property "id,displayName,userPrincipalName,accountEnabled,userType,assignedLicenses,licenseAssignmentStates"
$licensed = $disabled | Where-Object { $_.AssignedLicenses }
$report = foreach ($user in $licensed) {
$skuIds = @($user.AssignedLicenses | ForEach-Object { $_.SkuId.ToString() })
$partNumbers = $skuIds | ForEach-Object { if ($skus.ContainsKey($_)) { $skus[$_] } else { $_ } }
$states = @($user.LicenseAssignmentStates)
$direct = @($states | Where-Object { -not $_.AssignedByGroup } | ForEach-Object {
if ($skus.ContainsKey($_.SkuId.ToString())) { $skus[$_.SkuId.ToString()] } else { $_.SkuId }
})
$fromGroup = @($states | Where-Object { $_.AssignedByGroup } | ForEach-Object {
$sku = if ($skus.ContainsKey($_.SkuId.ToString())) { $skus[$_.SkuId.ToString()] } else { $_.SkuId }
"{0} (group {1})" -f $sku, $_.AssignedByGroup
})
[pscustomobject]@{
UserPrincipalName = $user.UserPrincipalName
DisplayName = $user.DisplayName
UserType = $user.UserType
AccountEnabled = $user.AccountEnabled
SkuPartNumbers = ($partNumbers -join '; ')
SkuIds = ($skuIds -join '; ')
DirectAssignments = ($direct -join '; ')
GroupAssignments = ($fromGroup -join '; ')
Id = $user.Id
}
}
$report | Sort-Object UserPrincipalName |
Export-Csv -Path ".\disabled-licensed-users.csv" -NoTypeInformation -Encoding UTF8
"Disabled users: $($disabled.Count)"
"Disabled users with licenses: $($report.Count)"
Sample output columns- UserPrincipalName, DisplayName, UserType, AccountEnabled: The disabled account (
AccountEnabled should be False) - SkuPartNumbers, SkuIds: Licenses currently assigned
- DirectAssignments: SKUs whose
licenseAssignmentStates have no assignedByGroup - GroupAssignments: SKUs assigned by a group, with that group's object ID
- Id: User object ID
Gotchas- This is not a full license inventory. For every licensed user, use License assignment report.
- The script uses the documented
accountEnabled eq false filter, then filters assignedLicenses in memory. A combined advanced query is not used, because that combination is not shown as a standard example on the List users page. - Removing a group license, or deleting the user, is out of scope. This report does not change data.
-All over every disabled account can be large; still prefer that over an unbounded unfiltered user list.
Microsoft Learn sources |
| License counts: purchased, assigned and free per SKURead-onlyNot tested against a live tenant | Licensing | One row per subscribed SKU with enabled, assigned (consumed) and remaining units, plus units in warning, suspended or locked-out state, so you can see free licenses and expiring subscriptions at a glance. Details, command and permissionsWhat it doesLicense assignment report answers "who has which license?" This one answers "how many do we have left?" for each SKU, using Get-MgSubscribedSku. It also surfaces units in warning (expired, in the renewal grace period), suspended and locked out state (licenseUnitsDetail resource type (opens in a new tab)), which is easy to miss until users lose access. Requirements- Modules: Microsoft.Graph.Identity.DirectoryManagement
- Connect-MgGraph scopes (least privilege):
LicenseAssignment.Read.All (List subscribedSkus (opens in a new tab)) - Least-privileged admin role: Directory Readers or Global Reader (listed on the API page).
- License: None stated on the API page.
- Flag: Read-only
- Label: Not tested against a live tenant
- Learn checked: 2026-12-02
Command# Read-only. Not tested against a live tenant.
Import-Module Microsoft.Graph.Identity.DirectoryManagement
Connect-MgGraph -Scopes "LicenseAssignment.Read.All"
$report = Get-MgSubscribedSku -All | ForEach-Object {
[pscustomobject]@{
SkuPartNumber = $_.SkuPartNumber
CapabilityStatus = $_.CapabilityStatus
AppliesTo = $_.AppliesTo
Enabled = $_.PrepaidUnits.Enabled
Consumed = $_.ConsumedUnits
Remaining = $_.PrepaidUnits.Enabled - $_.ConsumedUnits # calculated, not an API field
Warning = $_.PrepaidUnits.Warning
Suspended = $_.PrepaidUnits.Suspended
LockedOut = $_.PrepaidUnits.LockedOut
SkuId = $_.SkuId
}
}
$report | Sort-Object SkuPartNumber |
Export-Csv -Path ".\license-sku-summary.csv" -NoTypeInformation -Encoding UTF8
$report | Format-Table SkuPartNumber, Enabled, Consumed, Remaining, Warning, Suspended -AutoSize
Sample output columns- SkuPartNumber, SkuId: The product, for example
AAD_PREMIUM - CapabilityStatus:
Enabled, Warning, Suspended, Deleted or LockedOut - AppliesTo:
User SKUs are assignable to users; Company SKUs aren't - Enabled: Units enabled for the active subscription
- Consumed: Licenses assigned
- Remaining:
Enabled - Consumed; negative or zero means nothing left to assign - Warning: Units in the grace period after the subscription expired
- Suspended: Units that can't be assigned but can still be reactivated before deletion
- LockedOut: Units locked out because the subscription was canceled
Gotchas- Remaining is a calculation. Learn defines
enabled and consumedUnits but doesn't publish an "available" field; units in warning state aren't counted in Remaining. - Group-based licensing errors (for example not enough licenses) show per user, not here; use Groups and users with license errors.
Microsoft Learn sources |
| Remove direct licenses from disabled users (with -WhatIf)Changes dataNot tested against a live tenant | Licensing | For sign-in-blocked users, remove directly assigned licenses (optionally only one SKU), skip group-assigned ones, and log every action. Run with -WhatIf first. Details, command and permissionsWhat it doesChanges data. This script removes licenses. When you remove a license, the user's data is held for 30 days; if a mailbox must be kept for legal or compliance reasons, put it on hold (which needs the right Exchange Online license) before removing licenses (Step 6 - Remove a license from a former employee (opens in a new tab)). Run with -WhatIf first and review the CSV.
Disabled user accounts that still have licenses is the read-only report. This is the follow-up: for each disabled user it removes direct license assignments and skips licenses inherited from a group. Learn's own group-licensing example treats the error "User license is inherited from a group membership" as something to skip, because inherited licenses are removed by changing group membership, not per user (Remove direct licenses for users with group licenses (opens in a new tab)). Requirements- Modules: Microsoft.Graph.Users, Microsoft.Graph.Users.Actions, Microsoft.Graph.Identity.DirectoryManagement
- Connect-MgGraph scopes (least privilege):
User.Read.All (find disabled users and their license states), LicenseAssignment.Read.All (least privileged for List subscribedSkus) and LicenseAssignment.ReadWrite.All (least privileged for assignLicense (opens in a new tab)). - Least-privileged admin role: License Administrator or User Administrator (both listed on the assignLicense page).
- License: No extra license needed to remove licenses.
- Flag: Changes data (supports
-WhatIf and -Confirm) - Label: Not tested against a live tenant
- Learn checked: 2026-12-02
Command# CHANGES DATA. Not tested against a live tenant. Run with -WhatIf first.
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
[string] $SkuPartNumber # optional: only remove this SKU, for example "SPE_E3"
)
Import-Module Microsoft.Graph.Users
Import-Module Microsoft.Graph.Users.Actions
Import-Module Microsoft.Graph.Identity.DirectoryManagement
Connect-MgGraph -Scopes "User.Read.All","LicenseAssignment.Read.All","LicenseAssignment.ReadWrite.All"
$skuById = @{}
Get-MgSubscribedSku -All | ForEach-Object { $skuById[$_.SkuId.ToString()] = $_.SkuPartNumber }
$disabled = Get-MgUser -All -Filter "accountEnabled eq false" `
-Property "id,userPrincipalName,accountEnabled,assignedLicenses,licenseAssignmentStates"
$log = foreach ($u in ($disabled | Where-Object { $_.AssignedLicenses })) {
$states = @($u.LicenseAssignmentStates)
$direct = @($states | Where-Object { -not $_.AssignedByGroup } | ForEach-Object { $_.SkuId.ToString() } | Sort-Object -Unique)
$group = @($states | Where-Object { $_.AssignedByGroup })
if ($SkuPartNumber) {
$direct = @($direct | Where-Object { $skuById[$_] -eq $SkuPartNumber })
$group = @($group | Where-Object { $skuById[$_.SkuId.ToString()] -eq $SkuPartNumber })
}
foreach ($g in $group) {
[pscustomobject]@{ User = $u.UserPrincipalName; Sku = $skuById[$g.SkuId.ToString()]; Action = 'Skipped: assigned by group'; Detail = $g.AssignedByGroup }
}
if ($direct.Count -eq 0) { continue }
$names = ($direct | ForEach-Object { $skuById[$_] }) -join ', '
if ($PSCmdlet.ShouldProcess($u.UserPrincipalName, "Remove direct licenses: $names")) {
try {
Set-MgUserLicense -UserId $u.Id -AddLicenses @() -RemoveLicenses $direct -ErrorAction Stop | Out-Null
$action = 'Removed'; $detail = ''
} catch {
$action = 'Failed'; $detail = $_.Exception.Message
}
} else {
$action = 'Not changed (WhatIf or declined)'; $detail = ''
}
[pscustomobject]@{ User = $u.UserPrincipalName; Sku = $names; Action = $action; Detail = $detail }
}
$log | Export-Csv -Path ".\remove-licenses-disabled-users-log.csv" -NoTypeInformation -Encoding UTF8
$log | Group-Object Action | Select-Object Name, Count
Run it: .\Remove-LicensesDisabledUsers.ps1 -WhatIf # preview everything
.\Remove-LicensesDisabledUsers.ps1 -SkuPartNumber "SPE_E3" -WhatIf # preview one SKU
.\Remove-LicensesDisabledUsers.ps1 -SkuPartNumber "SPE_E3" # prompts per user (ConfirmImpact High)
Sample output columns- User: UPN of the disabled user
- Sku: SKU part number(s) acted on
- Action:
Not changed (WhatIf or declined), Removed, Failed, or Skipped: assigned by group - Detail: Error message, or the group ID that assigns the skipped license
Gotchas- Group-assigned licenses stay until you remove the user from the licensing group. Use Groups with assigned licenses to find the group.
- Disabled isn't always departed. Some accounts are disabled on purpose (shared mailboxes that are blocked from sign-in, for example). A shared mailbox that needs more than 50 GB, a larger archive or litigation hold needs its license; check before you run without
-WhatIf (Shared Mailboxes in Microsoft 365). - Dependencies: a removal can fail when another license depends on it (
DependencyViolation is one of the documented license assignment errors (licenseAssignmentState (opens in a new tab))). The failure is logged and the script moves on. - The
-SkuPartNumber filter uses the part number from Get-MgSubscribedSku, not the product's display name.
Microsoft Learn sources |