Tuesday, September 29, 2015

Find Users Logged In To Servers

Many times I've been put in a situation of trying to find users logged into servers. Most recently, it was for someone who changed their password and kept getting locked out. Rather than go through the event viewer on the DC to find the computer, and then go log them off, just to do it all over again, I would much rather just have a list of every server the person is logged into. There are ways to do this with PowerShell, but I've never had much luck when it came to spanning servers from 2003 to 2012 R2. It seems like some commands work on different versions, and getting all the info from the servers was getting pretty complicated. I steps below take just a few minutes, most of which ends up being just downloading the utilities.

First, create a list of servers. 

I do this with 2 utilities. The first is AD Info, an awesome reporting utility that even has lots of value in the free version.  http://www.cjwdev.com/Software/ADReportingTool/Info.html. Easily worth $59 for the full version, though. Run a report on Computers, Computers with Specified Operating System. Put in Server, and you'll get a list. Right-click the Name column, and choose Copy Full Column.



Next, ping the list of servers.

Download PingInfoView http://www.nirsoft.net/utils/multiple_ping_tool.html, and paste in the list of server names.



I choose Ping again every 2 seconds, and once I get a list of my servers after 10 pings, I sort by succeeded count, and copy the ones that are responding to ping into Excel. I copy the computer name column, and paste it into notepad and save it as C:\data\servers.txt. This file comes in very handy for not only the next step, but for using in scripting any variety of commands that need to reference a list of servers with something like the import-csv command.

Prepare and Run the command.

I open a command prompt, and set the Screen Buffer Size Height to 9999.


Then I execute the following command, which begins to query the servers.
for /f "tokens=1 delims= " %a in (C:\data\servers.txt) do query session /SERVER:%a
Once the command is done, I just right-click within the command prompt window and choose Select All. I then right-click again, which does a copy. I then paste that into notepad, and do a search on users names.

Note: If you are using privileged accounts (and I hope that you are), then you will need to run your command prompt as the admin user in order to get the proper session information from all the servers.