Sometimes when a program is run as Administrator, using the System.Security.Principal.WindowsIdentity.GetCurrent().Name will return always System or NT Authority\System. This happens while running the exe under windows service or by Installer class in the windows application.
The below code will solve this issue.
Code Snippet
- public static string GetParentUser(int pid)
- {
- string parentUserAccount = null;
- string queryString = String.Format("select ParentProcessId from win32_process where ProcessId={0}", pid);
- using (ManagementObjectSearcher query = new ManagementObjectSearcher(new
- SelectQuery(queryString)))
- {
- foreach (ManagementObject mo in query.Get())
- {
- uint parentPid = (uint)mo.Properties["ParentProcessId"].Value;
- queryString = String.Format("select Handle from win32_process where ParentProcessId = {0}", parentPid);
- using (ManagementObjectSearcher subQuery = new ManagementObjectSearcher(new
- SelectQuery(queryString)))
- {
- foreach (ManagementObject mo1 in subQuery.Get())
- {
- string handle = (string)mo1.Properties["Handle"].Value;
- RelatedObjectQuery relatedQuery =
- new RelatedObjectQuery("associators of {Win32_Process.Handle=\"" + handle + "\"}");
- relatedQuery.RelatedClass = "Win32_LogonSession";
- using (ManagementObjectSearcher relQuery = new ManagementObjectSearcher(relatedQuery))
- {
- foreach (ManagementObject mo2 in relQuery.Get())
- {
- RelatedObjectQuery relQuery2 =
- new RelatedObjectQuery("associators of {Win32_LogonSession.LogonId='" +
- mo2["LogonId"] + "'}");
- relQuery2.RelationshipClass = "win32_LoggedonUser";
- using (ManagementObjectSearcher searcher2 = new ManagementObjectSearcher(relQuery2))
- {
- foreach (ManagementObject mo3 in searcher2.Get())
- {
- parentUserAccount = String.Format(@"{0}\{1}", mo3["Domain"], mo3["Name"]);
- }
- }
- }
- }
- }
- }
- }
- }
- return parentUserAccount;
- }
You can download the code here
Hope the above code works. It works for me.
Thanks to the original post
http://bytes.com/topic/c-sharp/answers/631036-getting-currently-logged-user
Can something similar be tried in powershell ?