Skip to main content

Command Palette

Search for a command to run...

Automating Microsoft Entra ID PIM Role Activation with PowerShell and Microsoft Graph

Updated
β€’5 min read

Managing Microsoft Entra ID roles through Privileged Identity Management (PIM) can be repetitive and time-consuming, especially for administrators who frequently activate roles. To streamline this process while maintaining robust security, I developed a PowerShell script that automates role activation using Microsoft Graph with full Multi-Factor Authentication (MFA) support.

Version 2.0 Update: After receiving feedback and conducting a thorough security review, I've significantly enhanced the script with security hardening, input validation, audit logging, and adherence to the principle of least privilege.


πŸ”§ Key Features

Core Functionality

  • πŸ” Secure Connection: Establishes connection to Microsoft Graph with minimal required permissions (only 3 scopes instead of 5)
  • πŸ‘€ User Context Retrieval: Automatically fetches the current user context to identify eligible roles
  • ⚑ Automated Activation: Streamlines the role activation process with intelligent prompts
  • πŸ“‹ Interactive Selection: Clear, numbered menu when multiple roles are available
  • ⏱️ Configurable Duration: Set activation duration from 1-8 hours (default: 4 hours)
  • βœ… Explicit Confirmation: Type "ACTIVATE" to confirm and prevent accidental activations

Security Enhancements (New in v2.0)

  • πŸ›‘οΈ Least Privilege: Reduced Microsoft Graph scopes by 40% - uses only what's essential
  • βœ… Input Validation: Comprehensive validation with 20-500 character requirement for justifications
  • 🧹 Input Sanitization: Automatic cleaning of potentially dangerous characters
  • πŸ“ Audit Logging: Persistent JSON logs for compliance and security monitoring
  • πŸ”’ Data Protection: Sensitive information (like Request IDs) never displayed to console
  • 🎯 Error Handling: Sanitized error messages with helpful troubleshooting guidance

πŸ’» How It Works

The script follows a secure, step-by-step process:

  1. Clean State: Disconnects any existing Microsoft Graph sessions to ensure a fresh start
  2. Secure Authentication: Connects with only 3 essential scopes (reduced from 5):
    • RoleAssignmentSchedule.ReadWrite.Directory - For self-activation
    • Directory.Read.All - For reading role information
    • User.Read - For user profile access
  3. User Verification: Validates the current user and retrieves their context
  4. Role Discovery: Fetches all eligible PIM roles for the authenticated user
  5. Interactive Selection: If multiple roles exist, displays a clear numbered menu
  6. Duration Configuration: Prompts for activation duration (1-8 hours, default 4)
  7. Justification Input: Requires meaningful justification (minimum 20 characters) with automatic sanitization
  8. Confirmation Summary: Shows all details and requires typing "ACTIVATE" to proceed
  9. Secure Activation: Submits the activation request with MFA support
  10. Verification: Confirms the role is active and displays expiration time
  11. Audit Trail: Logs the entire transaction to local audit file for compliance

All actions are logged to %LOCALAPPDATA%\PIMActivation\audit.log in JSON format for easy parsing and compliance reporting.


πŸ”’ Security Improvements - What Changed

Before (v1.0)

❌ 5 Microsoft Graph scopes (over-privileged)
❌ No input validation
❌ No audit logging
❌ Sensitive data exposed in console
❌ Generic justifications accepted
❌ No explicit confirmation

After (v2.0)

βœ… 3 Microsoft Graph scopes (least privilege)
βœ… Comprehensive input validation
βœ… Full audit logging with JSON format
βœ… Sensitive data protected
βœ… Enforced 20-character minimum justifications
βœ… Explicit "ACTIVATE" confirmation required


πŸ“Š Real-World Example

Here's what the improved experience looks like:

===================================================================
  PIM Role Activation Script - Secured Version 2.0
===================================================================

Connecting to Microsoft Graph...
βœ“ Successfully connected to Microsoft Graph
βœ“ Connected as: admin@contoso.com
βœ“ Found 3 eligible role(s)

===================================================================
  Available Roles for Activation
===================================================================
1. Global Reader
2. Security Administrator
3. User Administrator

Enter the number of the role to activate (1-3): 1

Selected role: Global Reader

-------------------------------------------------------------------
Duration Configuration
-------------------------------------------------------------------
Enter activation duration in hours (1-8, default: 4): 4
βœ“ Duration set to: 4 hour(s)

-------------------------------------------------------------------
Justification (minimum 20 characters)
-------------------------------------------------------------------
Enter justification for role activation: Monthly security review and compliance audit
βœ“ Justification validated

===================================================================
  Activation Summary
===================================================================
Role:          Global Reader
Duration:      4 hour(s)
Justification: Monthly security review and compliance audit...
User:          admin@contoso.com
===================================================================

⚠️  This will activate privileged access. Ensure you have authorization.

Type 'ACTIVATE' to confirm (case-sensitive): ACTIVATE

βœ… Role activation successful!

Currently Active Roles:
  βœ“ Global Reader (Expires: 2025-11-02 18:30:00 UTC)

βœ“ Script completed successfully
===================================================================
  Audit log: C:\Users\Admin\AppData\Local\PIMActivation\audit.log
===================================================================

πŸ“‚ Access the Script

You can find the updated script on my GitHub repository: Activate-EntraIDPIMRole.ps1

What's Included:

  • βœ… Complete PowerShell script (v2.0)
  • βœ… Comprehensive README with security details
  • βœ… Usage examples and troubleshooting guide
  • βœ… Audit log format documentation

Feel free to clone the repository, test the script in your environment, and customize it to fit your organization's security policies and compliance requirements.


πŸ›‘οΈ Security Considerations

When using this script in production:

  1. Review Audit Logs Regularly: Check %LOCALAPPDATA%\PIMActivation\audit.log for unusual patterns
  2. Use Minimum Duration: Only activate roles for as long as needed
  3. Provide Clear Justifications: Always document why you're activating privileged access
  4. Test First: Run in a non-production environment before deploying
  5. Follow Policies: Ensure compliance with your organization's security policies
  6. Monitor Failed Attempts: Investigate repeated activation failures

πŸ“£ Feedback and Contributions

The security improvements in v2.0 came directly from community feedback and security reviews. I'm always open to more suggestions!

How to Contribute:

  • πŸ› Found a bug? Open an issue
  • πŸ’‘ Have an enhancement idea? Submit a pull request
  • πŸ”’ Identified a security concern? Please report it responsibly
  • πŸ“– Want to improve documentation? Contributions welcome!

🎯 What's Next?

I'm considering these enhancements for future versions:

  • πŸ”” Notification System: Alerts when roles are about to expire
  • πŸ“Š Reporting Dashboard: Visual analytics from audit logs
  • πŸ€– Scheduled Activations: Pre-approved activation windows
  • πŸ”— Integration with Ticketing Systems: Link to ITSM tickets

Let me know in the comments which features would be most valuable for your environment!



Update History:

  • v2.0 (Nov 2025): Security hardening, audit logging, input validation
  • v1.0 (Initial): Basic PIM role activation automation

Have you implemented PIM automation in your environment? What security considerations were most important to you? Share your experience in the comments below!