Open sessions on a computer
Win32_LogonSession lists the logon sessions; the Win32_LoggedOnUser association gives the account of each one. The LogonType filter keeps only interactive sign-ins (2), Remote Desktop (10) and cached credentials (11).
$sessionFilter = 'LogonType = 2 OR LogonType = 10 OR LogonType = 11'
$systemAccount = 'Window Manager', 'Font Driver Host'
$logonSession = Get-CimInstance -ClassName Win32_LogonSession -Filter $sessionFilter
foreach ($session in $logonSession) {
$user = Get-CimAssociatedInstance -InputObject $session -Association Win32_LoggedOnUser
foreach ($account in $user) {
if ($account.Domain -notin $systemAccount) {
[PSCustomObject]@{
Domain = $account.Domain
User = $account.Name
LogonId = $session.LogonId
LogonType = $session.LogonType
StartTime = $session.StartTime
}
}
}
}
Windows opens technical sessions for the window manager and the font driver host (Window Manager, Font Driver Host): the script skips them. StartTime is a [datetime]. To get only the console user, Win32_ComputerSystem is enough: its UserName property holds the signed-in account (DOMAIN\name), or nothing if nobody is signed in.
Variant: remote
Quick version: the console user of each server.
$cimSession = New-CimSession -ComputerName 'SERVER01', 'SERVER02'
try {
$cimParameters = @{
CimSession = $cimSession
ClassName = 'Win32_ComputerSystem'
}
Get-CimInstance @cimParameters |
Select-Object -Property PSComputerName, UserName
} finally {
Remove-CimSession -CimSession $cimSession
}