azureblog.co.uk
← cd ~/posts
Entra

Activate PIM roles from PowerShell with Microsoft Graph

The portal is fine for occasional use, but if you activate roles every day, a few lines of Graph PowerShell are faster. Here's how to list eligible roles and activate one.

Entra4 min read⚠ checked 5 Nov 2025Entra ID · PowerShell · Governance
On this page
  1. Connect with the right scopes
  2. List your eligible roles
  3. Activate one
  4. Check the result, extend or end early
  5. Wrap it in a function
  6. Things that trip people up

Privileged Identity Management is the right way to handle admin roles: nobody holds them permanently, and every elevation is time-boxed and justified. The downside is clicks. If you activate roles several times a day, scripting it with the PowerShell SDK saves real time.

YouMicrosoft GraphPIMEntra IDConnect-MgGraph withschedule scopes1List eligibilityschedule instances2Your eligible roles and scopes3New assignment schedulerequest: selfActivate4Check policy: MFA,justification,approval, max duration5Create activeassignment for theduration6Role usable after token refresh7
What happens when you activate a role from PowerShell.

Connect with the right scopes

powershell4 lineshover a line number for notes
Connect-MgGraph -Scopes "RoleEligibilitySchedule.Read.Directory",
                        "RoleAssignmentSchedule.ReadWrite.Directory"

$me = Get-MgUser -UserId (Get-MgContext).Account
What each line does
  1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
  2. Line 4: Reads user details from Microsoft Graph.

List your eligible roles

powershell3 lineshover a line number for notes
$eligible = Get-MgRoleManagementDirectoryRoleEligibilityScheduleInstance -Filter "principalId eq '$($me.Id)'" -ExpandProperty RoleDefinition

$eligible | Select-Object @{n="Role";e={$_.RoleDefinition.DisplayName}}, DirectoryScopeId, EndDateTime
What each line does
  1. Line 1: Reads role management directory role eligibility schedule instance details from Microsoft Graph.
  2. Line 3: Keeps only the properties listed, so the output stays small.

Activate one

Activation is a role assignment schedule request with the action selfActivate. The duration uses ISO 8601 format, so PT2H means two hours:

powershell14 lines1 changes something · hover a line number for notes
$role = $eligible | Where-Object { $_.RoleDefinition.DisplayName -eq "Exchange Administrator" }

$params = @{
    Action           = "selfActivate"
    PrincipalId      = $me.Id
    RoleDefinitionId = $role.RoleDefinitionId
    DirectoryScopeId = $role.DirectoryScopeId
    Justification    = "Investigating mail flow issue"
    ScheduleInfo     = @{
        StartDateTime = Get-Date
        Expiration    = @{ Type = "AfterDuration"; Duration = "PT2H" }
    }
}
New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter $params
What each line does
  1. Line 1: Keeps only the items that match the condition.
  2. Line 10: Gets the current date and time.
  3. Line 14: Creates a role management directory role assignment schedule request in Microsoft Graph. Makes a change.

Check the result, extend or end early

The request returns a status straight away. Provisioned means the role is active. PendingApproval means the role's settings require an approver, and nothing happens until they respond.

powershell9 lines1 changes something · hover a line number for notes
# Requests you've made, newest first
Get-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -Filter "principalId eq '$($me.Id)'" |
  Sort-Object CreatedDateTime -Descending |
  Select-Object -First 5 Action, Status, RoleDefinitionId, CreatedDateTime

# Finished early? Deactivate rather than leave it running
$params.Action = "selfDeactivate"
$params.Remove("ScheduleInfo"); $params.Remove("Justification")
New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter $params
What each line does
  1. Line 2: Reads role management directory role assignment schedule request details from Microsoft Graph.
  2. Line 3: Sorts the results.
  3. Line 4: Keeps only the properties listed, so the output stays small.
  4. Line 9: Creates a role management directory role assignment schedule request in Microsoft Graph. Makes a change.

Deactivating when you're done is good practice. It shortens the window in which a stolen session could use the role, and it shows up in the audit log as a deliberate action.

Wrap it in a function

Once it works, put it in your PowerShell profile so activation becomes one command:

powershell17 lines3 change something · hover a line number for notes
function Enable-PimRole {
    param([Parameter(Mandatory)][string]$Role,
          [string]$Reason = "Planned admin work",
          [int]$Hours = 1)
    $me = Get-MgUser -UserId (Get-MgContext).Account
    $r = Get-MgRoleManagementDirectoryRoleEligibilityScheduleInstance -Filter "principalId eq '$($me.Id)'" -ExpandProperty RoleDefinition |
         Where-Object { $_.RoleDefinition.DisplayName -eq $Role }
    if (-not $r) { throw "Not eligible for $Role" }
    New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter @{
        Action = "selfActivate"; PrincipalId = $me.Id
        RoleDefinitionId = $r.RoleDefinitionId; DirectoryScopeId = $r.DirectoryScopeId
        Justification = $Reason
        ScheduleInfo = @{ StartDateTime = Get-Date; Expiration = @{ Type = "AfterDuration"; Duration = "PT$($Hours)H" } }
    }
}

Enable-PimRole -Role "Intune Administrator" -Reason "Deploying compliance policy" -Hours 2
What each line does
  1. Line 1: Turns on a PIM role. Makes a change.
  2. Line 5: Reads user details from Microsoft Graph.
  3. Line 6: Reads role management directory role eligibility schedule instance details from Microsoft Graph.
  4. Line 7: Keeps only the items that match the condition.
  5. Line 9: Creates a role management directory role assignment schedule request in Microsoft Graph. Makes a change.
  6. Line 13: Gets the current date and time.
  7. Line 17: Turns on a PIM role. Makes a change.

Things that trip people up

  • Role settings still apply. If the role needs approval, a ticket number or a shorter maximum duration, the request fails with an error that says so. Read it rather than retrying.
  • MFA and authentication context. If the role requires or a on activation, your Graph session must satisfy it. You may need to reconnect so you're prompted.
  • Propagation. An activated role can take a minute or two to take effect in some admin portals. Sign out and back in if a portal doesn't see it.
  • Deactivate when done. Use the action selfDeactivate with the same role and scope to end the activation early.
Tip: wrap this in a small function or a simple GUI and share it with your team. The easier activation is, the less people push back on PIM.
Error or symptomWhat it usually means
Activation rejected for durationYou asked for longer than the role's maximum activation duration in PIM settings. Ask for less.
Justification or ticket requiredThe role settings require them. Add Justification or TicketInfo to the request.
Authentication context or ACRS validation errorThe role requires a Conditional Access authentication context. Activate in the portal, or reconnect so your token satisfies that context. See PIM with authentication context.
Role active but the portal still says noYour existing token predates the activation. Sign out and back in, or wait a few minutes.
Insufficient privileges on the requestYour Graph session lacks RoleAssignmentSchedule.ReadWrite.Directory. Reconnect with the scope.
Can I use this for Azure resource roles too?

Not with these cmdlets. Azure resource roles use the Azure PIM APIs in Az PowerShell, such as New-AzRoleAssignmentScheduleRequest, with the same idea of an eligible schedule and a self-activation request.

Does scripting bypass MFA or approval?

No. The request is checked against the same role settings as the portal. If the role needs approval, the request waits for it.

Can a service principal activate a role?

PIM is designed for people. should hold only the narrow permissions they need, granted directly, and be monitored instead.

This post was last checked against Microsoft's documentation over six months ago. The approach should still hold, but check the linked sources for anything that has changed before you act on it.

Next in Locking down admin access · part 3 of 6Require phishing-resistant MFA on every PIM activation →

More on Entra ID →

Spotted something out of date or wrong? Tell us and we'll fix it.