Getting currently logged on user


I hope this is the right place to write my question.

I want to search all my domain computers for the currently logged on user.

I have this command:

Get-WMIObject -Class Win32_ComputerSystem -ComputerName (Get-Content C:\Temp\ComputerNames.txt) | Select Name, Username

It works great, but I want to it to skip computers that don’t reply, turned off or out of the office (in the case of laptops).

How would I do that?

Thank you,

There are many scripts for getting logged on users. Have you tried to search “Powershell Get Logged On User”? If you want to write it yourself, you can minimally use the scripts as a guide as they will have logic to test connections.

Check out Test-Connection.

You could do something like the following. However, this will be slow for a lot of computers.

$ConnectedComps = Test-Connection -ComputerName (Get-Content C:\Temp\ComputerNames.txt) -Count 1 | Select -Expand Address -Unique

This type of task is better suited for a configuration/inventory management solution.

Please try the below code:

$Today = Get-Date -Format 'F'
$SessionList = "nnRDP Session List - " + $Today + "nn"
$CurrentSN = 0

$Servers = Get-Content C:\Temp\ComputerNames.txt

$NumberOfServers = $Servers.Count

# Iterate through the retrieved list to check RDP sessions on each machine
ForEach ($Server in $Servers)
	Write-Host "Processing $Server ..." -ForegroundColor Yellow
	Write-progress -activity "Checking RDP Sessions" -status "Querying $Server" -percentcomplete (($CurrentSN / $NumberOfServers) * 100)
		$SessionList += qwinsta /server:$Server |
		Select-Object -Skip 1 |
		% {
			[PSCustomObject] @{
				Type = $_.Substring(1, 18).Trim()
				User = $_.Substring(19, 20).Trim()
				ID   = $_.Substring(41, 5).Trim()
				State = $_.Substring(48, 6).Trim()
		} |
		? { $_.Type -notin 'console', 'services', 'rdp-tcp' -and $_.User -ne $null -and $_.User -ne 65536 } |
		% {
			[PSCustomObject] @{
				Server = $Server
				User   = $_.User
				LogonType = $_.Type
				ID   = $_.ID
				State = $_.State
			"`n$Server logged in by $($_.User) on $($_.Type), session id $($_.ID) $($_.state)"
		$SessionList += "`n Unable to query " + $Server
		write-host "Unable to query $Server! `n $($Error[0].Exception)" -foregroundcolor Red

# Send the output the screen.
$SessionList + "nn"

$sendMailArgs = @{
	From = "$env:USERNAME@$env:userdnsdomain"
	To   = ''
	SmtpServer = ''
	Priority = 'High'
	Body = $SessionList | Select-Object Server, User, LogonType, ID, State
	Subject = "$($SessionList.Count) Logged On users from $($NumberOfServers) online servers as at $($Today)"

Send-MailMessage @sendMailArgs


Hope that helps.