How to find logged on user using Powershell

0

Hi there,

While browsing one of the forums, I came across a question where one of the members asked the following.

How to find logged on user using Powershell in an Active Directory domain?

So I thought of sharing the script with all of you so that you might find it useful if you come across a similar situation.

Now there are various ways to find the users currently logged on to the using the graphical wizard.

The easiest of the ways would be to open up the task manager and click on the Users tab.

Coming back to our topic, we are interested in finding out the current logged on user using Powershell.

We will be making use of WMI object to fetch this information for us.

If we had to get this information on my local, we would simply use Get-WMIObject along with the Win32_ComputerSystem class.

So the command would look something like this.

Get-WMIObject - class Win32_ComputerSystem | select DNSHostName, username

How did I get to know what to select?

Simple, if I just pipe the Get-WMIObject to Get-Member cmdlet, I can find out all the associated properties of a particular class.

Get-WMIObject - class Win32_ComputerSystem Get-Member

Alright moving on, we would like to run this in our Active Directory environment and you can use the below script to get that information.

Import-Module ActiveDirectory
$comps = Get-ADComputer -Filter * | Select-Object Name | Sort-Object
$result = foreach ($comp in $comps) {
Get-WMIObject -class Win32_ComputerSystem -ComputerName $comp | select DNShostname, username
}
$result | Export-Csv C:\UserDetails.csv

It is pretty simple.

At first we imported the Active Directory module.

Then we used the Get-ADComputer cmdlet to find all the computer objects in the domain and assigned to a variable.

Then we ran the for loop and found the associated hostname and the current user logged on details.

Finally, we exported the information on to a CSV file for easy reading.

Update:

In a terminal services session, UserName returns the name of the user that is logged on to the console—not the user logged on during the terminal service session.

For more information, refer the below article by MVP Emin.

https://p0w3rsh3ll.wordpress.com/2012/02/03/get-logged-on-users/

I hope this has been informative and thank you for reading.

Share.

About Author

I am Adil Arif, working as a Senior Technical Support Engineer at Rubrik as well as an independent blogger and founder of Enterprise Daddy. In my current role, I am supporting infrastructure related to Windows and VMware datacenters.

Leave A Reply