Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the active user username using 'query user'

I will be running a script on a users box that does some work on a remote server. However, the user will not have access to the server, so I will be running the script as a different user with permissions.

The bit that I'm having difficulty with is that I need to grab the logged on user's (the box user) username and domain to pass to the server. There are various commands that can grab the data I need, but when running PowerShell ISE as a different user, they all return that users data not the logged on users data.

Some of the commands I am speaking of:

[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$env:USERNAME
$env:USERDOMAIN
$(whoami)

The only one that seems to work the way I want it to is:

query user

This returns the format of:

USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
>user1                sessionName         4  Active          .  6/22/2017 2:56 PM

My two questions are:

  1. Is there a way to get the domain in this way too? I dont see it when I run this command.
  2. Is there a way to just grab the username out of query user? what about specificity the 'active' username?
like image 661
Zirono Avatar asked Sep 19 '25 23:09

Zirono


2 Answers

Query active user:

query user | Select-String '^>(\w+)' | ForEach-Object { $_.Matches[0].Groups[1].Value }

This depends on usernames not containing whitespace. Add the /server parameter to the query command to query a remote computer.

like image 121
Bill_Stewart Avatar answered Sep 23 '25 07:09

Bill_Stewart


win32_loggedonuser has all of the information you need in the 'antecedent' property for each user. You'll need to filter it using string-parsing but it has what you're looking for. if you want any additional, session-related information, you can use the value in the 'dependent' property to search Win32_logonsession for things like logontype and starttime.

$s = (gwmi win32_loggedonuser).antecedent.split('=')
$s[1].Replace('"', '').Replace(',Name', '') ## domain
$s[2].Replace('"','') ## username

edit: the above displays parsing the output in a single user scenario. in a multi-user scenario, you'd need to loop through the results and perform like-operations for each user. my intent was to provide an example.

edit2: the -computername property on Get-WmiObject will allow you to run this against remote computers--with the appropriate permissions of course.

like image 25
thepip3r Avatar answered Sep 23 '25 05:09

thepip3r