How-to: Get a list of Logged on users [Get-Loggedon]

The script below can be used to list all the users currently logged into a remote machine using WMI/CIM. It includes background processes/services but excludes standard processes running under NETWORK SERVICE, LOCAL SERVICE and SYSTEM. This does make the assumption that the user is running at least one process, theoretically someone could be log in and kill all processes including the Desktop/Explorer but that’s a pretty rare edge case.

For instructions of how to download and run this script see: Run a PowerShell script.
Background information on monitoring logon sessions.

function Get-LoggedOn {
#Requires -Version 3.0
[CmdletBinding()]
Param (
   [Parameter(
      Mandatory=$true,
      Position=0,
      ValueFromPipeline=$true,
      ValueFromPipelineByPropertyName=$true
   )]
   [String[]]$ComputerName
)

Begin {
   Write-Host "`n Gathering data, please wait..."
   $i = 0
}

Process {
   $ComputerName | Foreach-object {
      $Computer = $_
      try {
         $processinfo = @(Get-CimInstance -class win32_process -ComputerName $Computer -ErrorAction "Stop")
         # To exclude service accounts add  -filter "Name='Explorer.exe'"  to the line above.

         if ($processinfo) {
            $processinfo | Foreach-Object {
               Invoke-CimMethod -InputObject $_ -MethodName GetOwner | Select-Object -ExpandProperty user
            } | Where-Object {
               $_ -ne "NETWORK SERVICE" -and $_ -ne "LOCAL SERVICE" -and $_ -ne "SYSTEM"
            } | Sort-Object -Unique |
            ForEach-Object { New-Object psobject -Property @{Computer=$Computer;LoggedOn=$_} } |
            Select-Object Computer,LoggedOn
         }
      }
      catch {
         "Cannot find any processes running on $computer" | Out-Host
      }
   }

}

End {
}

}

Example

Find who is logged on to the machine computer64:

Get-LoggedOn computer64

“Your present circumstances don’t determine where you can go; they merely determine where you start” ~ Nido Qubein

Related PowerShell Cmdlets

Get-CimInstance - Get a managed resource (storage, network, software etc).


 
Copyright © 1999-2024 SS64.com
Some rights reserved