Forum Discussion
Fetch Email of Login User In System Context
Thank you for your response. We have tested the provided command, and it currently returns the email address of the user who initially joined the device to Entra ID, instead of the email address of the currently logged-in user.
We require to obtain the email address of the presently logged-in user. For instance, if UserA initially joined the device to Entra ID, and subsequently UserB logs in, the command continues to display UserA's email address.
Ah, if devices are used by multiple users or are different from the enrollment user... Ok, I modified Andrew Taylor's script a bit to return the email address:
function get-UserPrincipalNameFromLoggedOnUser() {
<#
.SYNOPSIS
This function is used to find the logged-in user's userprincipalname as System
.DESCRIPTION
This function is used to find the logged-in user's userprincipalname as System
.EXAMPLE
getloggedindetails
Returns the SID and Username in an array
.NOTES
NAME: getloggedindetails
Written by: Andrew Taylor (https://andrewstaylor.com) and changed by Harm Veenstra to return only the User Principal Name
#>
##Find logged in username
$user = Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" |
ForEach-Object { $_.GetOwner() } |
Select-Object -Unique -Expand User
##Find logged-in user's SID
##Loop through registry profile list until ProfileImagePath matches and return the path
$path = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\*"
$sid = (Get-ItemProperty -Path $path | Where-Object { $_.ProfileImagePath -like "*$user" }).PSChildName
try {
$userprincipalname = (Get-ChildItem "Registry::HKEY_USERS\$($sid)\Software\Microsoft\Windows NT\CurrentVersion\WorkplaceJoin\AADNGC" -Recurse -ErrorAction Stop).GetValue('UserID')
}
catch {
$userprincipalname = "Not found"
}
return $userprincipalname
}
Original source: https://andrewstaylor.com/2023/11/07/enumerating-the-logged-on-user-when-running-as-system-with-azure-ad-entra-joined-devices/