I wanted a simple way to get all (remote) logged on (and disconnected) users on all servers in my domain. This way it’s easier for me to see if there are any disconnected sessions still open. In my case I’ve entered them into a SQL database, but for the example on this blog, I will export the list to a CSV file, on a daily basis.
I use the QUERY SESSION command for this purpose (as I found it to be the most quick and reliable one). The command is called as QWINSTA in my code (which is the same as QUERY SESSION) and works from Windows 2012 and up.
In my case I run this directly on my AD controller, so I can query the computers available in the domain. I also added an exclude list (so I won’t query machines that have been shut down, but are still available in the computers list on my domain)
After I get the list of users (with the server name, session name, sessionId and session state), I will filter out empty user names and administrator account(s), because I’m not interested in those sessions.
In the end I will export the list to a CSV file, but this can also easily be exported to a SQL database, web site etc.
Here is the code:
Start-Transcript C:\Logging\GetConnectedUsers.txt
$Servers = (Get-ADComputer -Filter *).Name | Sort-Object
$dt = Get-Date -Format yyyyMMdd
$exportFile = "C:\Logging\$dt ConnectedUsers.csv"
$openSessions = @()
Foreach ($ServerName in $Servers)
{
$ExcludedServers = "EXCLUDESRV01", "EXCLUDESRV02", "EXCLUDESRV03"
If ($ExcludedServers -notcontains $ServerName)
{
Write-Host "Getting session information for $ServerName"
$sessions = qwinsta /server $ServerName| ?{ $_ -notmatch '^ SESSIONNAME' } | %{
$item = "" | Select "ServerName", "SessionName", "Username", "Id", "State"
$item.ServerName = $ServerName
$item.SessionName = $_.Substring(1,18).Trim()
$item.Username = $_.Substring(19,20).Trim()
$item.Id = $_.Substring(39,9).Trim()
$item.State = $_.Substring(48,8).Trim()
$item
}
$openSessions += $sessions | where { ($_.Username -ne "") -and ($_.Username -ne "Administrator") }
}
Else { Write-Host "Skipping named computer $ServerName" }
}
$openSessions | Export-Csv "$exportFile" -NoTypeInformation
Stop-Transcript
And the complete script can be downloaded here.
How to get the Logn On time and the IDOl time of the user using above script
LikeLike