Azure – PowerShell – Add User into Local Administrators Group

email me

On an Azure AD machine, acquiring the user’s UPN is required to add a user into the local administrators group. To obtain the UPN, you will first need the user SID. And, the caveat to all of this, is that those values must be returned in the System Account security context, meaning…the normal (Current User) environmental variables will not work.

I grab the user SID from a known registry location > use the user SID to acquire the UPN in a known location > add user into administrators group using the returned UPN. All this happens in a dynamic manner.

I turned this into an EXE, uploaded to SCCM, and deployed to a specific device collection to control which devices will have access to the package (temporarily, of course).

Tested from SCCM in the System Account (…and tested from Intune in the System Account).

NOTE: There is an overly complex Microsoft solution using Graph API and custom OMA-URI settings (requires global admin or security admin access in Azure). My scripted solution works without anything extra, and can be deployed using SCCM, Intune, or any other desktop management system.


This solution is free to claim as your own.


Return SID

$key1 = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, [Microsoft.Win32.RegistryView]::Registry64)
$subKey1 = $key1.OpenSubKey(“SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI”)
$SID = $subKey1.GetValue(“LastLoggedOnUserSID“)
# Use ‘SelectedUserSID‘ if this is AVD/VDI

Return UPN

$key2 = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, [Microsoft.Win32.RegistryView]::Registry64)
$subKey2 = $key2.OpenSubKey(“SOFTWARE\Microsoft\IdentityStore\Cache\$SID\IdentityCache\$SID“)
$UPN = $subKey2.GetValue(“UserName“)

Add User

Add-LocalGroupMember Group “Administrators” Member “AzureAD\$UPN

Package Wrapper (use in script.cmd to EXE packaging)

\\%computername%\C$\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File C:\Windows\temp\script.ps1

* I use the admin share UNC to guarantee 64 bit powershell.exe (otherwise, it’s dependent on whatever app you’re using to package your scripts)



Also see Remove-LocalGroupMember

How to manage the local administrators group on Azure AD joined devices

Microsoft Graph permissions reference

Working with groups in Microsoft Graph


Other ideas:

Create a revoke administrator access package.

Create a scheduled task [run daily] to check a marker file or reg key. If the marker or reg key has been deleted, the task will remove user from administrators group.

Allow 24 hour admin access, and then a scheduled task removes user from administrators group.

More secure:

Create 2 AAD groups: Add access, Remove access.
Create 2 packages: Add access, Remove access.
Add and remove by moving user from one group to the next.