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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With