/
/

How to Automate Temporary Access Expiry for Admin Accounts in Microsoft 365

by Angelo Salandanan, IT Technical Writer
How to Automate Temporary Access Expiry for Admin Accounts in Microsoft 365 blog banner image

Instant Summary

This NinjaOne blog post offers a comprehensive basic CMD commands list and deep dive into Windows commands with over 70 essential cmd commands for both beginners and advanced users. It explains practical command prompt commands for file management, directory navigation, network troubleshooting, disk operations, and automation with real examples to improve productivity. Whether you’re learning foundational cmd commands or mastering advanced Windows CLI tools, this guide helps you use the Command Prompt more effectively.

Managing admin accounts requires a careful balance between security and user experience. For instance, Azure temporary admin access is sometimes only suited in certain segments or workflows, where admin privileges may not always prove necessary. To follow through on this setup, check out this comprehensive guide below.

Methods for automating temporary access in Microsoft 365

Use the table to choose and quickly navigate to your preferred activation steps.

📌 Prerequisites:

  • Microsoft Entra ID P2 (required for PIM)
  • PowerShell 7+ with Microsoft.Graph or AzureAD module
  • Admin permissions to assign directory roles
  • [Optional] GPO or registry tagging for local status logging
  • [Optional] NinjaOne RMM for script deployment, registry scanning, or alerting

👉 Reminder: Some steps may vary depending on system defaults or active settings.

Click to Choose a Method 💻

Best for Individual Users 

💻💻💻

Best for Enterprises

Method 1: Entra PIM
Method 2: PowerShell script

💡 Tip: Check out the Things to look out for section for tips on managing potential risks.

Method 1: Use Microsoft Entra Privileged Identity Management (PIM)

This method is ideal for organizations with Entra ID P2/PIM looking to grant temporary access with automated expiry.

  1. Here’s the script for assigning an eligible role instead of an active role:

Connect-MgGraph -Scopes "RoleManagement.ReadWrite.Directory","Directory.ReadWrite.All"

  1. Then, here’s how to pull the eligible user ID and role ID:

$user = Get-MgUser -UserPrincipalName "[email protected]"

$role = Get-MgDirectoryRole | Where-Object {$_.DisplayName -eq "Global

Administrator"}

  1. If the user is inactive:

New-MgRoleManagementDirectoryRoleEligibilityScheduleRequest `

-PrincipalId $user.Id `

-RoleDefinitionId $role.Id `

-DirectoryScopeId "/" `

-Action "AdminAssign" `

-ScheduleInfo @{startDateTime = (Get-Date); expiration =

@{type="AfterDuration"; duration="PT2H"}}

This step ensures the user receives access for only 2 hours, and it expires automatically.

Method 2: Automate role activation and expiry via PowerShell Script

PowerShell scripts are flexible and can be used via an RMM for one-click deployment or automation. Here’s the corresponding script:

Start-MgRoleManagementDirectoryRoleAssignmentScheduleRequest `

-Action "SelfActivate" `

-PrincipalId $user.Id `

-RoleDefinitionId $role.Id `

-DirectoryScopeId "/" `

-ScheduleInfo @{

startDateTime = (Get-Date);

expiration = @{

type = "AfterDuration";

duration = "PT1H"

}

}

An activation request will be submitted against the existing eligibility, which then triggers PIM to enforce a time-boxed assignment for eligible users. This script also terminates the elevated access after a set duration.

Tips for logging and auditing temporary admin requests

The following actions can help with the enforcement and logging of temporary elevated privileges.

Store admin access status in the registry

You can track the associated registry keys via PowerShell to verify if the deployment was successful. Run the following script with administrative privileges:

New-Item -Path "HKLM:\SOFTWARE\Org\AdminAccessAudit" -Force

Set-ItemProperty -Path "HKLM:\SOFTWARE\Org\AdminAccessAudit" -Name

"LastAdminGranted" -Value (Get-Date).ToString("u")

Set-ItemProperty -Path "HKLM:\SOFTWARE\Org\AdminAccessAudit" -Name

"ExpiresAt" -Value ((Get-Date).AddHours(1)).ToString("u")

💡 Tip: Additionally, you can also check registry values by using reg query HKLM\SOFTWARE\Org\AdminAccessAudit on an elevated Command Prompt.

Monitor or revoke active admin access via script

For immediate enforcement, you can use PowerShell to enumerate active assignments and remove them after a set access period:

$assignments =

Get-MgRoleManagementDirectoryRoleAssignmentScheduleInstance

foreach ($a in $assignments) {

if ($a.StartDateTime -lt (Get-Date).AddHours(-1)) {

Remove-MgRoleManagementDirectoryRoleAssignmentScheduleInstance

-RoleAssignmentScheduleInstanceId $a.Id

}

}

This script can be scheduled via Task Scheduler or automated through a NinjaOne policy.

Use Group Policy for event logging and enforcement

While Group Policy is unable to directly automate temporary access expiry, you can utilize it instead for audit logging and detection of access requests and changes.

Here are some ways it can complement PIM:

  • Enable detailed logon/logoff, privilege use, and security group management auditing.
  • Deploy a Scheduled Task that runs your revocation or monitoring script on a cadence.
  • Fire scripts on event IDs (e.g., local admin group change) for immediate remediation or logging.

In addition, you can limit interactive logon to standard users and manage local Administrators group membership via GPO/Restricted Groups.

⚠️ Things to look out for when automating Intune profile assignments

Below are common risks, their possible consequences, and some practical ways to reverse or prevent issues.

Risks Potential Consequences Reversals
Loose eligibility criteria Requests for elevated access can be abused or spam. Set strict eligibility rules; ensure role activation requires MFA to limit spam; use Power Automate or Graph API to notify users/admins of

temporary role activations.

Excessive or duplicate auditing logs Makes key events harder to find; takes up additional storage Adjust audit policy to focus only on Privilege Use, Logon/Logoff, and Group Management; archive or forward logs to SIEM.
Incorrect PIM role assignment (eligible vs active) The user may retain elevated access rights indefinitely. Review assignments in Entra PIM → Roles; revoke immediately if necessary via portal or PowerShell.
Failed user access Graph API permission errors Ensure the application or user has

RoleManagement.ReadWrite.Directory permissions.

As always with access policies, it’s recommended to test and validate configurations in a controlled environment or segment. The length of temporary access also deserves careful consideration, since some workflows may require longer or shorter access expiry durations.

Use NinjaOne to enhance temporary access policies

Access policies are crucial to IT and business operations, which is why automation is valuable for creating efficient workflows, minimizing delay, and securing auditable trails for risk management and compliance. NinjaOne helps accomplish these and unlock capabilities to:

  • Deploy scripts to initiate or revoke temporary role access
  • Read registry keys to validate admin access to Windows
  • Trigger alerts when devices have overdue admin privileges
  • Log events related to privilege elevation for audit reviews
  • Tag endpoints for admin exposure risk or escalation policy coverage

With NinjaOne RMM®, MSPs can enforce zero-standing access policies with greater efficiency and consistency, especially for scaling environments, through automation, visibility, and control.

Best practices for automating profile assignment in Intune

Credential management requires a layered approach to thoroughly balance security and flexibility across stakeholders. On one hand, elevated access can be important to various IT and production workflows. On the other, privilege can be misused or abused in the absence of strict implementation and control policies. With these in mind, temporary access provides a reliable safeguard for supporting critical tasks and minimizing risks .

Related topics:

Quick-Start Guide

Recommended Approach:

For automated temporary access expiry, you would likely need to:

  • Use NinjaOne’s scripting capabilities
  • Combine with Microsoft 365 Conditional Access policies
  • Potentially develop a custom script to manage admin account access

FAQs

Users tagged as eligible can activate the role temporarily or on demand. Active roles are usually held by administrators and carry permissions indefinitely.

RMM and scripting can be used to set up and customize access control. However, scripting requires more manual setup and validation.

This action is relatively optional and is more purposeful for creating local logs and auditing.

You might also like

Ready to simplify the hardest parts of IT?

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).