Activate and Deactivate Microsoft Entra PIM Roles Using Microsoft Graph PowerShell

IMPORTANT:
Cloud Modernization Notice (2026):
The legacy AzureADPreview and Microsoft.Azure.ActiveDirectory.PIM.PSModule cmdlets (Get-AzureADMSPrivilegedRoleAssignment, Open-AzureADMSPrivilegedRoleAssignmentRequest) have been retired.
> Microsoft Entra Privileged Identity Management (PIM) role activation is now fully integrated into the Microsoft Graph PowerShell SDK (Microsoft.Graph.Identity.Governance) via the RoleAssignmentScheduleRequest API. Historical references are preserved at the bottom for archival purposes.

When managing high-privilege Microsoft 365 environments, adhering to the principle of Least Privilege is critical. With Microsoft Entra Privileged Identity Management (PIM), administrators maintain eligible role assignments rather than permanent standing access.

However, having to navigate to the Microsoft Entra admin center (https://entra.microsoft.com), complete MFA, select roles, enter justifications, and wait for the web interface to refresh every morning can be time-consuming for sysadmins who live in the PowerShell console.

In this guide, we walk through how to interact with Entra PIM programmatically using modern Microsoft Graph PowerShell, query your eligible directory roles, and run a production script to self-activate and deactivate multiple roles simultaneously with custom durations and ticket justifications.


Prerequisites & Permissions

To query and activate your own eligible PIM directory roles via PowerShell:

  • Module: Microsoft.Graph.Identity.Governance (or the unified Microsoft.Graph SDK).
  • Scope: RoleAssignmentSchedule.ReadWrite.Directory (delegated).
  • MFA Session: Because PIM role activation policies enforce Multi-Factor Authentication, your interactive Connect-MgGraph session must be authenticated with MFA.
POWERSHELL
# Install the Identity Governance and Users modules
Install-Module Microsoft.Graph.Identity.Governance, Microsoft.Graph.Users -Scope CurrentUser -Repository PSGallery -Force

# Connect to Graph with delegated PIM permissions
Connect-MgGraph -Scopes "RoleAssignmentSchedule.ReadWrite.Directory", "RoleEligibilitySchedule.Read.Directory", "User.Read"

Understanding the PIM Graph API

Under Microsoft Graph, role management is driven by the roleAssignmentScheduleRequest endpoint:

Action ParameterPurpose
selfActivateA user temporarily activates an eligible directory role they are assigned to.
selfDeactivateA user ends their active role session early once administrative tasks are complete.
adminAssignAn admin assigns an active role to a target principal.
adminRemoveAn admin revokes a role assignment.
Durations are defined using standard ISO 8601 duration strings:
  • PT1H = 1 Hour
  • PT4H = 4 Hours
  • PT8H = 8 Hours

Step 1: Discover Your Eligible Directory Roles

To find out which Entra ID directory roles your signed-in account is eligible to activate:

POWERSHELL
# Get signed-in user ID
$context = Get-MgContext
$myUserId = (Get-MgUser -UserId $context.Account).Id

# Query all eligible directory role schedules for current user
$eligibleRoles = Get-MgRoleManagementDirectoryRoleEligibilitySchedule `
    -Filter "principalId eq '$myUserId'" `
    -ExpandProperty "roleDefinition" `
    -All

$eligibleRoles | Select-Object @{n="RoleName";e={$_.RoleDefinition.DisplayName}}, RoleDefinitionId, DirectoryScopeId | Format-Table -AutoSize

Sample output:

TEXT
RoleName                  RoleDefinitionId                     DirectoryScopeId
--------                  ----------------                     ----------------
Exchange Administrator    29230cdf-9323-42fd-ab21-01641d9e4e6d /
User Administrator        fe930be7-5e62-47db-91af-98c3a49a38b1 /
Groups Administrator      fdd7a751-b60b-444a-984c-02652fe8fa1c /


Step 2: Self-Activating a Single Role via PowerShell

To activate an eligible role (for example, Exchange Administrator) for 4 hours with a business justification:

POWERSHELL
$roleDefId = "29230cdf-9323-42fd-ab21-01641d9e4e6d" # Exchange Administrator

$params = @{
    Action           = "selfActivate"
    PrincipalId      = $myUserId
    RoleDefinitionId = $roleDefId
    DirectoryScopeId = "/"
    Justification    = "Executing scheduled migration and mailbox maintenance"
    ScheduleInfo     = @{
        StartDateTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
        Expiration    = @{
            Type     = "AfterDuration"
            Duration = "PT4H"
        }
    }
}

$request = New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter $params
Write-Host "PIM Request Submitted! Status: $($request.Status)" -ForegroundColor Green

Step 3: Self-Deactivating an Active Role Early

Once your maintenance window concludes, deactivating the role immediately reduces attack surface rather than waiting for the timer to expire:

POWERSHELL
$params = @{
    Action           = "selfDeactivate"
    PrincipalId      = $myUserId
    RoleDefinitionId = $roleDefId
    DirectoryScopeId = "/"
    Justification    = "Maintenance window completed early"
}

$deactivate = New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter $params
Write-Host "Role Deactivated! Status: $($deactivate.Status)" -ForegroundColor Green

Production Interactive Tool: Multi-Role PIM Manager (Manage-PimRoles.ps1)

To replicate and modernize the popular GUI role selector from the original 2019 script, here is a complete PowerShell function using Out-GridView to let you multi-select roles to activate or deactivate in a single click.

POWERSHELL
<#
.SYNOPSIS
    Interactive Multi-Role PIM Activation/Deactivation Tool for Microsoft Entra ID.
.DESCRIPTION
    Queries eligible and active PIM directory roles for the signed-in user,
    provides a GUI multi-select menu via Out-GridView, and processes requests via Graph SDK.
.NOTES
    Author: Sunil Chauhan (https://www.lab365.in)
    Requirements: Microsoft.Graph.Identity.Governance
#>

function Manage-PimRoles {
    [CmdletBinding()]
    param(
        [ValidateSet('Activate', 'Deactivate')]
        [string]$Action = 'Activate',

        [ValidateSet('1', '2', '4', '8')]
        [string]$DurationHours = '4',

        [string]$Justification = "Routine administrative operations"
    )

    if (-not (Get-MgContext)) {
        Write-Host "[*] Connecting to Microsoft Graph..." -ForegroundColor Cyan
        Connect-MgGraph -Scopes "RoleAssignmentSchedule.ReadWrite.Directory", "RoleEligibilitySchedule.Read.Directory", "User.Read"
    }

    $myAccount = (Get-MgContext).Account
    $userId = (Get-MgUser -UserId $myAccount).Id
    Write-Host "[+] Authenticated as: $myAccount ($userId)" -ForegroundColor Green

    if ($Action -eq 'Activate') {
        Write-Host "[*] Fetching eligible directory roles..." -ForegroundColor Yellow
        $eligible = Get-MgRoleManagementDirectoryRoleEligibilitySchedule `
            -Filter "principalId eq '$userId'" `
            -ExpandProperty "roleDefinition" `
            -All

        if (-not $eligible) {
            Write-Warning "No eligible directory roles found for your account."
            return
        }

        # Select roles via interactive GridView
        $selected = $eligible | Select-Object `
            @{n="RoleName";e={$_.RoleDefinition.DisplayName}}, `
            @{n="Description";e={$_.RoleDefinition.Description}}, `
            RoleDefinitionId, DirectoryScopeId |
            Out-GridView -Title "Select PIM Roles to ACTIVATE (Hold Ctrl for multiple)" -PassThru

        if (-not $selected) {
            Write-Warning "No roles selected. Exiting."
            return
        }

        foreach ($role in $selected) {
            Write-Host "[*] Activating '$($role.RoleName)' for $DurationHours hour(s)..." -NoNewline
            
            $body = @{
                Action           = "selfActivate"
                PrincipalId      = $userId
                RoleDefinitionId = $role.RoleDefinitionId
                DirectoryScopeId = $role.DirectoryScopeId
                Justification    = $Justification
                ScheduleInfo     = @{
                    StartDateTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
                    Expiration    = @{
                        Type     = "AfterDuration"
                        Duration = "PT$($DurationHours)H"
                    }
                }
            }

            try {
                $req = New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter $body -ErrorAction Stop
                Write-Host " [SUCCESS: $($req.Status)]" -ForegroundColor Green
            } catch {
                Write-Host " [FAILED]" -ForegroundColor Red
                Write-Warning $_.Exception.Message
            }
        }
    } else {
        Write-Host "[*] Fetching currently active role assignments..." -ForegroundColor Yellow
        $active = Get-MgRoleManagementDirectoryRoleAssignmentSchedule `
            -Filter "principalId eq '$userId'" `
            -ExpandProperty "roleDefinition" `
            -All

        if (-not $active) {
            Write-Warning "No active directory roles found to deactivate."
            return
        }

        $selected = $active | Select-Object `
            @{n="RoleName";e={$_.RoleDefinition.DisplayName}}, `
            RoleDefinitionId, DirectoryScopeId |
            Out-GridView -Title "Select PIM Roles to DEACTIVATE early" -PassThru

        if (-not $selected) {
            Write-Warning "No roles selected. Exiting."
            return
        }

        foreach ($role in $selected) {
            Write-Host "[*] Deactivating '$($role.RoleName)'..." -NoNewline
            
            $body = @{
                Action           = "selfDeactivate"
                PrincipalId      = $userId
                RoleDefinitionId = $role.RoleDefinitionId
                DirectoryScopeId = $role.DirectoryScopeId
                Justification    = "Finished administrative work"
            }

            try {
                $req = New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter $body -ErrorAction Stop
                Write-Host " [DEACTIVATED]" -ForegroundColor Green
            } catch {
                Write-Host " [FAILED]" -ForegroundColor Red
                Write-Warning $_.Exception.Message
            }
        }
    }
}

Usage Examples:

POWERSHELL
# Activate multiple roles with GUI prompt for 4 hours
Manage-PimRoles -Action Activate -DurationHours 4 -Justification "Deploying Exchange CU"

# Deactivate roles early when done
Manage-PimRoles -Action Deactivate

Archival Reference: Legacy AzureADPreview Method

Click to view historical 2019 PIM instructions

Historical methods utilized the preview cmdlets inside AzureADPreview:

POWERSHELL
Connect-AzureAD
# Legacy cmdlet
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId 'aadRoles' -ResourceId $tenantId -RoleDefinitionId $roleId -SubjectId $userId -AssignmentState 'Active' -Type 'UserAdd' -Reason 'Admin work' -Duration 'PT4H'


Related reading: Migrating from Windows PowerShell 5.1 to PowerShell 7 for Microsoft Graph ยท Auditing Entra Dynamic Groups for Retired memberOf Rules