In search of this same solution, I found what I needed under a different question in stackoverflow: Powershell-log-off-remote-session. The below one line will return a list of logged on users.

query user /server:$SERVER
Answer from Quickmute on Stack Overflow
🌐
Reddit
reddit.com › r/powershell › get logged in user, even when user is using remote desktop
r/PowerShell on Reddit: Get logged in user, even when user is using Remote Desktop
November 30, 2021 -

I have a script that relies on retrieving the username of the user logged into the PC. I'm using the following line to get that information:

get-ciminstance win32_computersystem | % username

Problem is, it doesn't seem to return anything if the user is using Remote Desktop to log into the computer. Is there a way for me to retrieve the username of who is connected via RDP?

🌐
4sysops
4sysops.com › home › blog › articles › how to find a logged-in user remotely using powershell
How to find a logged-in user remotely using PowerShell – 4sysops
July 28, 2023 - The code below gets the currently logged on user from windows explorer. It will return more than 1 name if multiple users are currently logged in. Simply give $RemoteHost an IP address or Hostname.
Discussions

Need to find the logged on user on windows 10 machine
Hi Team, i am using the below command to retreive the logged on user on win10 machine $userInfo = Get-WmiObject -Class Win32_ComputerSystem $($userInfo.UserName) The problem with this command is that it only retreives the console logon user and not the rdp user. is there any command which will ... More on forums.powershell.org
🌐 forums.powershell.org
3
0
March 29, 2024
Powershell script to view logged on user
I used to have a script that I would run to tell me what user is logged into a computer. We have stickers on each desktop with the computer name but many of these users don’t even know that. Ideally it would display all computers within an OU with the user that is currently logged on. More on community.spiceworks.com
🌐 community.spiceworks.com
9
10
February 11, 2020
PowerShell: Find computers that a specific user is logged on with the LastLogonDate
Good afternoon, I would need to run a script that would tell me which computers a particular user was logged into. I found this script: #Set variables $progress = 0 #Get Admin Credentials Function Get-Login { Clear-Host Write-Host "Please provide… More on learn.microsoft.com
🌐 learn.microsoft.com
7
0
who is logged on remote pc from which computer
I have a domain admin account. I want to find out who is logged in to PC1 from which computer/ip ? currently I can only query which username is logged on PC1 but non of command showed from which computer this user is logged in to PC1. So far I have used pstools \\PC1 query user (this only shows ... More on community.spiceworks.com
🌐 community.spiceworks.com
9
11
September 24, 2018
🌐
PowerShell Forums
forums.powershell.org › powershell help
Need to find the logged on user on windows 10 machine - PowerShell Help - PowerShell Forums
March 29, 2024 - Hi Team, i am using the below command to retreive the logged on user on win10 machine $userInfo = Get-WmiObject -Class Win32_ComputerSystem $($userInfo.UserName) The problem with this command is that it only retreives the console logon user and not the rdp user. is there any command which will ...
🌐
Windows OS Hub
woshub.com › find-current-user-logged-remote-computer
Find the Current User Logged on a Remote Computer | Windows OS Hub
March 15, 2024 - The command shows only the user logged on to the console (not through the RDP). You can also use PSRemoting to get information from remote computers with the Invoke-Command cmdlet. YOu can get only the username on the remote computer (without a domain), use these commands: $userinfo = Get-WmiObject -ComputerName pc1215wks1 -Class Win32_ComputerSystem $user = $userinfo.UserName -split '\\' $user[1] In modern PowerShell Core (pwsh.exe) versions, you need to use the Get-CimInstance cmdlet instead of Get-WmiObject:
🌐
The Sysadmin Channel
thesysadminchannel.com › home › get logged in users using powershell
Get Logged In Users Using Powershell - the Sysadmin Channel
February 9, 2022 - Within the Powershell Window type: . .\_Scripts\Get-LoggedInUser.ps1 – Note the two dots before the backslash. The best thing I love about this script is your ability to get who is logged into a remote computer. This mitigates the need to physically log into computer and checking that way.
Find elsewhere
🌐
The PoSh Wolf
theposhwolf.com › howtos › A-better-way-to-find-logged-on-users-remotely-using-PowerShell
A better way to find a logged on user remotely using PowerShell | The PoSh Wolf
June 1, 2018 - To retrieve the users logged into a remote or local computer, we would simply use: ... And if you pass it to a variable and look at the type name, we should have a PSCustomObject, meaning we can use all the other useful cmdlets for filtering and whatnot! $sessions = Get-ActiveSessions ComputerName ($sessions | Get-Member).TypeName[0] System.Management.Automation.PSCustomObject
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 1162904 › powershell-find-computers-that-a-specific-user-is
PowerShell: Find computers that a specific user is logged on with the LastLogonDate - Microsoft Q&A
Specifically, you can place it after the line that checks the user's active session and before the else statement, like this: Copy code foreach ($comp in $computers){ $Computer = $comp.Name $Reply = $null $Reply = test-connection $Computer -count 1 -quiet if($Reply -eq 'True'){ if($Computer -eq $env:COMPUTERNAME){ #Get explorer.exe processes without credentials parameter if the query is executed on the localhost $proc = gwmi win32_process -ErrorAction SilentlyContinue -computer $Computer -Filter "Name = 'explorer.exe'" } else{ #Get explorer.exe processes with credentials for remote hosts $proc = gwmi win32_process -ErrorAction SilentlyContinue -Credential $Credential -computer $Computer -Filter "Name = 'explorer.exe'" } # Get last logon date $lastLogon = (gwmi -Class Win32_NetworkLoginProfile -ComputerName $computer.Name | Where-Object {$_.Name -eq $Username}).LastLogon if
🌐
Delft Stack
delftstack.com › home › howto › powershell › get logged on users using powershell
How to Get Logged on Users in PowerShell | Delft Stack
February 2, 2024 - ... # Use any of the commands (Get-WMIObject -ClassName Win32_ComputerSystem).Username (Get-CimInstance -ClassName Win32_ComputerSystem).Username · It is worth noting that querying the Win32_ComputerSystem .NET class will only output the username ...
🌐
YouTube
youtube.com › techsnips
How To Find A Remotely Logged-On User With PowerShell - YouTube
If you enjoyed this video, be sure to head over to http://techsnips.io to get free access to our entire library of content! Adam Bertram, the most handsome m...
Published   October 9, 2018
Views   402
🌐
Spiceworks
community.spiceworks.com › programming & development
who is logged on remote pc from which computer - Programming & Development - Spiceworks Community
September 24, 2018 - I have a domain admin account. I want to find out who is logged in to PC1 from which computer/ip ? currently I can only query which username is logged on PC1 but non of command showed from which computer this user is logged in to PC1. So far I have used pstools \\PC1 query user (this only shows username , not computer name from which the user is loggedin) WMIC /NODE: "PC1" COMPUTERSYSTEM GET USERNAME
🌐
ManageEngine
manageengine.com › products › active-directory-audit › powershell › get-remote-logged-on-user-with-powershell.html
How to remotely see what users are logged into Windows | ManageEngine ADAudit Plus
April 4, 2025 - ADAudit Plus will automatically scan all DCs in the domain to retrieve information about the users currently logged on remotely to a computer, generate the report and present it in a simple and intuitively designed UI.
Top answer
1 of 2
1

The environment variable [System.Environment]::GetEnvironmentVariable('username') will give you the username for the executor of the script, in your case that is System because this is user who ran the code.

If you want to user the environment variable for the user, you must make it so the script been ran from or on behalf of the user, this also means that user must have "permissions" to modify the registry.

If I understand right, you need to know who is the "Logged in user" for the machine where that script runs, unfortunately there is nothing available from PowerShell that do that to my knowledge, instead you could use the build-in tool query for Windows machines, which will provide you with a list with all logged in users to that machine, you would need to further test it to get what you want from it, the output looks like this :

PS C:\Users\t-user> query user
 USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
>t-user                console             1  Active      none   8/29/2022 11:58 AM

The trick with query user is that it will provide you with the list of users in case more than one have logged in.

I see what you are trying to do, and here is a "dirty" example of doing it :

$loggedUserList= query user

if($loggedUserList.count -eq 2){
    $user = $loggedUserList -split ">" -replace '\s\s+', ';' | convertfrom-csv -Delimiter ';' | select -ExpandProperty username
    Write-Host "Logged in user is - $user"
}else{
    Write-Host "More than one user have signed"
}
2 of 2
0

I realize this is a year old but this was answered here: Finding current logged on user(s) while running as SYSTEM (no environment variables)

That page provides two methods of obtaining the current logged on user from a powershell script running as the system user.

Displays User instead of Computer/User or Domain/User.

Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" |
ForEach-Object { $_.GetOwner() } |
Select-Object -Unique -Expand User

Displays Computer/User or Domain/User 2 times

$User = tasklist /v /FI "IMAGENAME eq explorer.exe" /FO list | find "User Name:"
$User = $User.Substring(14)
Top answer
1 of 9
4

The issue with Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique is that it shows all sessions even those that have been closed since the last time the computer rebooted. The easiest way to poll sessions is unfortunately using the old executable query.exe.

You can convert the output of query.exe to objects using a bit of regex:

$Computer = $env:COMPUTERNAME
$Users = query user /server:$Computer 2>&1

$Users = $Users | ForEach-Object {
    (($_.trim() -replace ">" -replace "(?m)^([A-Za-z0-9]{3,})\s+(\d{1,2}\s+\w+)", '$1  none  $2' -replace "\s{2,}", "," -replace "none", $null))
} | ConvertFrom-Csv

foreach ($User in $Users)
{
    [PSCustomObject]@{
        ComputerName = $Computer
        Username = $User.USERNAME
        SessionState = $User.STATE.Replace("Disc", "Disconnected")
        SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")
    } 
}

Which will give you output like this:

ComputerName Username SessionState SessionType
------------ -------- ------------ -----------
BSMITH-LT    bobsm    Active       console    

Taking it a lot further in to a function:

function Convert-QueryToObjects
{
    [CmdletBinding()]
    [Alias('QueryToObject')]
    [OutputType([PSCustomObject])]
    param
    (
        [Parameter(Mandatory = $false,
                   ValueFromPipeline = $true,
                   ValueFromPipelineByPropertyName = $true,
                   Position = 0)]
        [Alias('ComputerName', 'Computer')]
        [string]
        $Name = $env:COMPUTERNAME
    )

    Process
    {
        Write-Verbose "Running query.exe against $Name."
        $Users = query user /server:$Name 2>&1

        if ($Users -like "*No User exists*")
        {
            # Handle no user's found returned from query.
            # Returned: 'No User exists for *'
            Write-Error "There were no users found on $Name : $Users"
            Write-Verbose "There were no users found on $Name."
        }
        elseif ($Users -like "*Error*")
        {
            # Handle errored returned by query.
            # Returned: 'Error ...<message>...'
            Write-Error "There was an error running query against $Name : $Users"
            Write-Verbose "There was an error running query against $Name."
        }
        elseif ($Users -eq $null -and $ErrorActionPreference -eq 'SilentlyContinue')
        {
            # Handdle null output called by -ErrorAction.
            Write-Verbose "Error action has supressed output from query.exe. Results were null."
        }
        else
        {
            Write-Verbose "Users found on $Name. Converting output from text."

            # Conversion logic. Handles the fact that the sessionname column may be populated or not.
            $Users = $Users | ForEach-Object {
                (($_.trim() -replace ">" -replace "(?m)^([A-Za-z0-9]{3,})\s+(\d{1,2}\s+\w+)", '$1  none  $2' -replace "\s{2,}", "," -replace "none", $null))
            } | ConvertFrom-Csv

            Write-Verbose "Generating output for $($Users.Count) users connected to $Name."

            # Output objects.
            foreach ($User in $Users)
            {
                Write-Verbose $User
                if ($VerbosePreference -eq 'Continue')
                {
                    # Add '| Out-Host' if -Verbose is tripped.
                    [PSCustomObject]@{
                        ComputerName = $Name
                        Username = $User.USERNAME
                        SessionState = $User.STATE.Replace("Disc", "Disconnected")
                        SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")
                    } | Out-Host
                }
                else
                {
                    # Standard output.
                    [PSCustomObject]@{
                        ComputerName = $Name
                        Username = $User.USERNAME
                        SessionState = $User.STATE.Replace("Disc", "Disconnected")
                        SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")
                    }
                }
            }
        }
    }
}

and now you can do things like: Get-ADComputer -Filter {Name -like "SERVER*"} | Convert-QueryToObjects | ? {$_.SessionState -eq 'Active'}

2 of 9
4

Here's how I do it. It doesn't work for rdp sessions though.

$out = query session | where {$_ -match 'console'}
$array = $out -split('\s+')
$consoleuser = $array[1]

Or:

$consoleuser = query session | select-string console | foreach { -split $_ } | 
  select -index 1
🌐
Powershell Commands
powershellcommands.com › powershell-get-current-logged-on-user-remote-computer
PowerShell: Get Current Logged On User From Remote Computer
September 16, 2024 - PowerShell Get Service on Remote Computer Simplified · The `Get-WmiObject` cmdlet can be employed to fetch the current logged-on user information as follows:
🌐
Adam the Automator
adamtheautomator.com › powershell-get-current-user
Using the Dynamic PowerShell to Get Current Users
Let’s start with the PowerShell native cmdlets called Get-WMIObject and Get-CimInstance. These cmdlets allow you to query information, including the currently logged-on user, using the Windows Management Instrumentation (WMI) classes on a local or remote computer.
Published   October 6, 2022
🌐
AirDroid
airdroid.com › home › remote support › how to see who is logged into a remote computer? [2025]
How to See Who Is Logged into a Remote Computer? [2025]
April 3, 2025 - If you have this suite installed on your computer, you can use the "PsLoggedOn" command [ PsLoggedOn \\RemoteComputerName ] through PowerShell or Command Prompt. Here's how: ... Step 2: Once the screen appears, paste the following command.