Skip to content

Get-LocalUserSession

Windows: Retrieves active user sessions and logged-on accounts

#Requires -Version 5.1

[CmdletBinding()]
Param
(
    [string]$ComputerName = $env:COMPUTERNAME,

    [pscredential]$Credential
)

Process
{
    try
    {
        $scriptBlock = {
            $sessions = Get-CimInstance -ClassName Win32_LogonSession -ErrorAction Stop
            $results = foreach ($session in $sessions)
            {
                # LogonType 2 = Interactive, 10 = RemoteInteractive (RDP)
                if ($session.LogonType -in @(2, 10, 11))
                {
                    $userLink = Get-CimAssociatedInstance -InputObject $session -ResultClassName Win32_UserAccount -ErrorAction SilentlyContinue
                    
                    if ($userLink)
                    {
                        [PSCustomObject]@{
                            UserName     = "$($userLink.Domain)\$($userLink.Name)"
                            LogonType    = switch($session.LogonType) {
                                2  { "Interactive" }
                                10 { "RemoteInteractive (RDP)" }
                                11 { "CachedInteractive" }
                                default { "Other ($($session.LogonType))" }
                            }
                            StartTime    = $session.StartTime
                            LogonId      = $session.LogonId
                            ComputerName = $env:COMPUTERNAME
                        }
                    }
                }
            }
            $results
        }

        if ($ComputerName -ne $env:COMPUTERNAME)
        {
            $invokeParams = @{
                'ComputerName' = $ComputerName
                'ScriptBlock'  = $scriptBlock
                'ErrorAction'  = 'Stop'
            }
            if ($null -ne $Credential)
            {
                $invokeParams.Add('Credential', $Credential)
            }

            $result = Invoke-Command @invokeParams
        }
        else
        {
            $result = &$scriptBlock
        }

        Write-Output $result
    }
    catch
    {
        throw
    }
}

Specifies the name of the computer to query. Defaults to the local computer.

Specifies a PSCredential object for remote connection.

An interactive directory of PowerShell scripts.