Automating Microsoft Entra ID PIM Role Activation with PowerShell and Microsoft Graph
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:
- Clean State: Disconnects any existing Microsoft Graph sessions to ensure a fresh start
- Secure Authentication: Connects with only 3 essential scopes (reduced from 5):
RoleAssignmentSchedule.ReadWrite.Directory- For self-activationDirectory.Read.All- For reading role informationUser.Read- For user profile access
- User Verification: Validates the current user and retrieves their context
- Role Discovery: Fetches all eligible PIM roles for the authenticated user
- Interactive Selection: If multiple roles exist, displays a clear numbered menu
- Duration Configuration: Prompts for activation duration (1-8 hours, default 4)
- Justification Input: Requires meaningful justification (minimum 20 characters) with automatic sanitization
- Confirmation Summary: Shows all details and requires typing "ACTIVATE" to proceed
- Secure Activation: Submits the activation request with MFA support
- Verification: Confirms the role is active and displays expiration time
- 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:
- Review Audit Logs Regularly: Check
%LOCALAPPDATA%\PIMActivation\audit.logfor unusual patterns - Use Minimum Duration: Only activate roles for as long as needed
- Provide Clear Justifications: Always document why you're activating privileged access
- Test First: Run in a non-production environment before deploying
- Follow Policies: Ensure compliance with your organization's security policies
- 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!
π Related Resources
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!


