Enable PIM role thru Microsoft Graph PowerShell

Page content

Five years ago, I wrote an article about enabling PIM roles with Powershell, and last week I took it upon myself to convert it using the Microsoft Graph PowerShell modules

Why would you move?

The primary reason to start moving to the graph modules is that the AzureAD and other modules were declared deprecated last year; see this post for all the details https://techcommunity.microsoft.com/t5/microsoft-entra-azure-ad-blog/azure-ad-change-management-simplified/ba-p/2967456 The modules still work but will not get any updates anymore. All effort of Microsoft is being put into the Microsoft Graph and Microsoft Graph Modules.


Before we can start using the Graph Modules we need to install them; here is a choice to install the needed submodules or to install them all.

  • Installing them all can be done via “Install-Module Microsoft.Graph”; This is the preferred one as this will give you everything.
  • The needed submodules
    • Microsoft.Graph.Authentication
    • Microsoft.Graph.DeviceManagement.Enrolment
    • Microsoft.Graph.Users

Enabling PIM via Graph

It is not at straightforward as via the Azure AD modules as you need to know a few guids, luckaly these are easy to find

The first step is to connect to the Graph API and setup the variable for TenantID and User ObjectID

# Connect Via deviceauthentication and get the User ObjectID
Connect-MgGraph -UseDeviceAuthentication
$context = Get-MgContext
$currentUser = (Get-MgUser -UserId $context.Account).Id

After you are connected, you can get all the available roles for the logged-in account

$myRoles = Get-MgRoleManagementDirectoryRoleEligibilitySchedule -ExpandProperty RoleDefinition -All -Filter "principalId eq '$currentuser'"

Moving from this, we can get the correct guids to activate our desired role; in the example below, we activate the “SharePoint Service Adminstrator” role for 4 hours from the moment this script executes

$myRole = $myroles | Where-Object {$_.RoleDefinition.DisplayName -eq "SharePoint Service Administrator"}

$params = @{
    Action = "selfActivate"
    PrincipalId = $myRole.PrincipalId
    RoleDefinitionId = $myRole.RoleDefinitionId
    DirectoryScopeId = $myRole.DirectoryScopeId
    Justification = "Enable SharePoint admin role"
    ScheduleInfo = @{
        StartDateTime = Get-Date
        Expiration = @{
            Type = "AfterDuration"
            Duration = "PT4H"
    TicketInfo = @{
        TicketNumber = TS46283
        TicketSystem = "OurTicketSysytem"

New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter $params

Here is the gist with all the steps for you to copy/paste


Here are the references to the Microsoft documentation: