Wednesday, March 25, 2026

Azure Privileged Identity Management(PIM) Role

# ============================================================

#  Azure PIM Role Activator

#  Requires: Microsoft.Graph PowerShell Module

#  Install : Install-Module Microsoft.Graph -Scope CurrentUser

# ============================================================

# ---------- CONFIGURATION ----------

$justification = "Activating role via PowerShell script"

$durationHours = 8   # Set activation duration (hours)

# -----------------------------------

# Step 1: Install Graph module if missing

if (-not (Get-Module -ListAvailable -Name Microsoft.Graph)) {

    Write-Host "Installing Microsoft.Graph module..." -ForegroundColor Yellow

    Install-Module Microsoft.Graph -Scope CurrentUser -Force

}

# Step 2: Connect to Microsoft Graph

Write-Host "`nConnecting to Microsoft Graph..." -ForegroundColor Cyan

Connect-MgGraph -Scopes "RoleManagement.ReadWrite.Directory", "RoleAssignmentSchedule.ReadWrite.Directory" -NoWelcome

 

# Step 3: Get current user

$userId = (Get-MgContext).Account

$user   = Get-MgUser -Filter "userPrincipalName eq '$userId'"

Write-Host "Logged in as: $userId" -ForegroundColor Green

 

# Step 4: Get all eligible roles for the user

Write-Host "`nFetching eligible PIM roles..." -ForegroundColor Cyan

$eligibleRoles = Get-MgRoleManagementDirectoryRoleEligibilitySchedule `

    -Filter "principalId eq '$($user.Id)'" -ExpandProperty RoleDefinition

 

if (-not $eligibleRoles) {

    Write-Warning "No eligible PIM roles found for this user. Exiting."

    exit

}

 

# Step 5: Display eligible roles

Write-Host "`n===== ELIGIBLE ROLES =====" -ForegroundColor Yellow

$index = 1

$roleList = @()

foreach ($role in $eligibleRoles) {

    $roleName  = $role.RoleDefinition.DisplayName

    $scopeId   = $role.DirectoryScopeId

    Write-Host "  [$index] $roleName  (Scope: $scopeId)"

    $roleList += [PSCustomObject]@{

        Index            = $index

        RoleName         = $roleName

        RoleDefinitionId = $role.RoleDefinitionId

        DirectoryScopeId = $scopeId

    }

    $index++

}

# Step 6: Prompt user to select roles

Write-Host "`nEnter role numbers to activate (comma-separated), or type 'ALL' to activate all:"

$input = Read-Host "Your selection"

 

if ($input.Trim().ToUpper() -eq "ALL") {

    $selectedRoles = $roleList

} else {

    $selectedIndexes = $input -split "," | ForEach-Object { $_.Trim() -as [int] }

    $selectedRoles   = $roleList | Where-Object { $_.Index -in $selectedIndexes }

}

if (-not $selectedRoles) {

    Write-Warning "No valid roles selected. Exiting."

    exit

}
 

# Step 7: Activate selected roles

Write-Host "`n===== ACTIVATING ROLES =====" -ForegroundColor Yellow

foreach ($role in $selectedRoles) {

    try {

        $params = @{

            Action           = "selfActivate"

            PrincipalId      = $user.Id

            RoleDefinitionId = $role.RoleDefinitionId

            DirectoryScopeId = $role.DirectoryScopeId

            Justification    = $justification

            ScheduleInfo     = @{

                StartDateTime = (Get-Date).ToUniversalTime()

                Expiration    = @{

                    Type     = "AfterDuration"

                    Duration = "PT${durationHours}H"

                }

            }

        }


        New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter $params | Out-Null

        Write-Host "  Activated : $($role.RoleName) for $durationHours hour(s)" -ForegroundColor Green

    }

    catch {

        Write-Host "  Failed    : $($role.RoleName) — $($_.Exception.Message)" -ForegroundColor Red

    }

}

Write-Host "`nDone! Active roles will expire after $durationHours hour(s)." -ForegroundColor Cyan

 

No comments:

Post a Comment

Featured Post

Azure Privileged Identity Management(PIM) Role

# ============================================================ #   Azure PIM Role Activator #   Requires: Microsoft.Graph PowerShell Mod...

Popular posts