PS: Find Logged On Users

1 minute read


Powershell script to find currently logged on users for a machine.

To Resolve:

1a. Relevant main portion of the script:

$ComputerName = $env:Computername
Log "Running Query.Exe Against $ComputerName" 
$Users = Query User /Server:$ComputerName 2>&1

If ($Users -Like "*No User Exists*")
	# Handle No User's Found Returned From Query.
	# Returned: 'No User Exists For *'
	Log "There Were No Users Found Logged On $ComputerName." 
Elseif ($Users -Like "*Error*")
	# Handle Errored Returned By Query.
	# Returned: 'Error ...<Message>...'
	Log "There Was An Error Running Query Against $ComputerName." 
Elseif ($Users -Eq $Null -And $Erroractionpreference -Eq 'Silentlycontinue')
	# Handdle Null Output Called By -Erroraction.
	Log "Error Action Has Supressed Output From Query.Exe. Results Were Null." 
	Log "Users Found On $ComputerName. 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
	Log "Generating Output For $($Users.Count) Users Connected To $ComputerName" 
	# Output Objects.
	Foreach ($User In $Users)
		$Output = [Pscustomobject]@{
			Computername = $ComputerName
			Username     = $User.Username
			Sessionstate = $User.State.Replace("Disc", "Disconnected")
			Sessiontype  = $($User.Sessionname -Replace '#', '' -Replace "[0-9]+", "")
		$Results += $Output
	Log "$Results"

This can be found in my gwConfiguration section.