Skip to content

Instantly share code, notes, and snippets.

@Diagg
Last active September 25, 2023 17:52
Show Gist options
  • Select an option

  • Save Diagg/7ae0563a09d35124781d375d05ab54cc to your computer and use it in GitHub Desktop.

Select an option

Save Diagg/7ae0563a09d35124781d375d05ab54cc to your computer and use it in GitHub Desktop.
Get Current user from system/admin context. Works with Workgroup/AD user, Windows Sandbox user and Azure AD user. Works also with an x86 Powershell client on an X64 Windows 10
# By Diagg/OSDC
# https://www.osd-couture.com/
# Twitter: @Diagg
#V 2.0 - Logic refactored, Added support for X86 powershell on X64 windows
#V 1.0 - Initial release
# Get Workgroup/AD User
$CurrentLoggedOnUser = (Get-CimInstance –ClassName Win32_ComputerSystem | Select-Object -expand UserName)
If ([String]::IsNullOrWhiteSpace($CurrentLoggedOnUser))
{
$CurrentUser = Get-Itemproperty "Registry::\HKEY_USERS\*\Volatile Environment"|Where-Object {$_.USERDOMAIN -match 'AzureAD' -or $_.USERNAME -match 'WDAGUtilityAccount'}
If (![String]::IsNullOrWhiteSpace($CurrentUser))
{
$CurrentLoggedOnUser = "$($CurrentUser.USERDOMAIN)\$($CurrentUser.USERNAME)"
$CurrentLoggedOnUserSID = split-path $CurrentUser.PSParentPath -leaf
If($CurrentUser.USERDOMAIN -match 'AzureAD')
{
$UPNKeys = $(reg query hklm\SOFTWARE\Microsoft\IdentityStore\LogonCache /reg:64).Split([Environment]::NewLine)| where{$_ -ne ""}
ForEach ($item in $UPNKeys)
{
$UPN = reg @('query',"$item\Sid2Name\$CurrentLoggedOnUserSID",'/v','IdentityName','/reg:64')
If ($LASTEXITCODE -eq 0){$CurrentLoggedOnUserUPN = ($UPN[2] -split ' {2,}')[3] ; Break}
}
}
}
}
Write-host "Current user: $CurrentLoggedOnUser"
If(![string]::IsNullOrWhiteSpace($CurrentLoggedOnUserUPN)){Write-host "Current user UPN: $CurrentLoggedOnUserUPN"}
@Darkomen78
Copy link

Hi ! I can't get you script to work on a AzureAD joined computer.
On a admin powershell "Get-Itemproperty "Registry::\HKEY_USERS*\Volatile Environment"|Where-Object {$.USERDOMAIN -match 'AzureAD' -or $.USERNAME -match 'WDAGUtilityAccount'}" return an empty string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment