I have a script that is running under alternate credentials and needs to get the username of the current logged in user.
My current solution only works for consoled users:
Get-WMIObject -class Win32_ComputerSystem -Property username | select username
I need a solution that will work for RDP as well.
Unfortunately most of the simple solutions like [Environment]::username will only report the alternate credential running the script and not the true logged in username. The Get-WMIObject method works great except for remote desktop scenarios like RDP to a virtual machine.
I have tried methods like “query user” however this reports all the logged users and I only want the exact current user. In the case of RDP you might have several active sessions and that doesn’t work. I need just the current user who triggered the process.
My full script looks like this
import-module activedirectory function Get-GroupMembership($DN,$group){ $objEntry = [adsi]("LDAP://"+$DN) $objEntry.memberOf | where { $_ -match $group} } $nUser = Get-WMIObject -class Win32_ComputerSystem -Property username | select username $cUser = $nUser.username -split 'domain\\' $pUser = Get-ADUser -Identity $cUser[1] | select Name, DistinguishedName #$pUser.DistinguishedName #$aUser = $pUser.name -replace ",","\," $aUser = $pUser.DistinguishedName $bUser = $pUser.name If (Get-GroupMembership "$aUser" "IMO Collection") { $imo = $True "[IMO] $bUser" "$bUser [IMO]" | CLIP } Else { $imo = $False "$bUser" "$bUser" | CLIP }
The basic purpose is to display the current logged in user name into an HTA application and identify if the user is part of special active directory security group. If they are a member of the AD group additional features are enabled in the HTA for them. The HTA calls this script during the body onload() process. The user triggers this HTA via the SCCM 2012 Software Center (thus why the HTA runs under system credentials).