Last active
September 25, 2023 17:52
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.