Find who is logged on to a remote computer
List the users with a desktop session on a local or remote computer, including remote desktop sessions, with the session start time.
LanguagePowerShell
What it does to the systemReads only. It changes nothing.
Before you restart a computer or take it over, you want to know who is working on it. The console user alone is not enough when people use remote desktop.
This script finds every desktop session. It looks for the explorer.exe processes and reads the owner of each one.
PowerShell
<#
Who is logged on to a computer.
Every desktop session runs explorer.exe, so the owners of those processes are the users.
Remote computers need WinRM turned on and administrator rights.
Example: .\Get-LoggedOnUser.ps1 -ComputerName PC01
#>
param(
[string[]]$ComputerName = $env:COMPUTERNAME
)
foreach ($computer in $ComputerName) {
$cim = @{ ErrorAction = 'Stop' }
if ($computer -notin @($env:COMPUTERNAME, 'localhost', '.')) { $cim.ComputerName = $computer }
try {
# The user at the physical screen and keyboard, if there is one.
$console = (Get-CimInstance @cim -ClassName Win32_ComputerSystem).UserName
$shells = @(Get-CimInstance @cim -ClassName Win32_Process -Filter "Name = 'explorer.exe'")
if ($shells.Count -eq 0) {
[pscustomobject]@{ ComputerName = $computer; User = '(nobody)'; SessionId = $null; Console = $false; Since = $null }
}
foreach ($shell in $shells) {
$owner = Invoke-CimMethod -InputObject $shell -MethodName GetOwner
$user = '{0}\{1}' -f $owner.Domain, $owner.User
[pscustomobject]@{
ComputerName = $computer
User = $user
SessionId = $shell.SessionId
Console = ($user -eq $console)
Since = $shell.CreationDate
}
}
}
catch {
[pscustomobject]@{ ComputerName = $computer; User = "Error: $($_.Exception.Message)"; SessionId = $null; Console = $false; Since = $null }
}
}
How to use it
- Save the script as
Get-LoggedOnUser.ps1. - Open PowerShell as an administrator. Without it you only see your own session.
- Run
.\Get-LoggedOnUser.ps1for this computer, or add-ComputerName PC01. - Read the
Consolecolumn. True is the user at the screen. False is a remote desktop or disconnected session.
Good to know
- A disconnected session still counts. The user did not sign out, so the programs still run.
- A user with two Explorer processes shows two times. Add
| Sort-Object User, SessionId -Uniqueto remove the extra line. Sinceis the start of Explorer. It is close to the logon time unless Explorer crashed and started again.
logged on user
sessions
Win32_Process
explorer.exe
remote desktop