Page 1 of 1

How to get current username (non-admin) when running script as Admin?

Posted: 11 Aug 2016, 19:40
by RandomAHKUser
I've created an installer that needs to run as Administrator to install certain registry keys and files. I need to get the name of the current logged in user to find the proper current user registry SID, but obviously running as admin will show the current user (A_Username) as the administrator credentials, not the actual user.

What I do to work around the problem, is run the program unelevated, request elevation through RunAs and pass the %A_Username% to the command line, so running elevated will have the proper name in %1%.

Is there an easy way to get the actual logged in username when elevated, rather than this workaround?

Re: How to get current username (non-admin) when running script as Admin?  Topic is solved

Posted: 11 Aug 2016, 23:10
by lexikos
You could get the owner of any process which you know to be owned by the logged-in user.

Code: Select all

WinGet desktop_pid, PID, ahk_class Progman
for process in ComObjGet("winmgmts:").ExecQuery(""
    . "Select * from Win32_Process where ProcessId = " desktop_pid)
{
    VarSetCapacity(var, 24, 0), vref := ComObject(0x400C, &var)  ; Requires v1.1.17+
    process.GetOwner(vref, "")
    MsgBox % vref[]
}

Re: How to get current username (non-admin) when running script as Admin?

Posted: 11 Oct 2016, 00:16
by JJohnston2
I arrived at this post by way of slogging through a completely different problem in WMI land, only to get stuck at the GetOwner() call. I was wondering if it had a slightly more complicated parameter setup since everything I was trying failed quite nicely... might have figured it out eventually from other example code setting up the arguments like this, but this particular post just saved me a huge amount of time and headache. Thank you for posting.