A common task any Windows admin might have is finding out, locally or remotely, which user account is logged onto a particular computer. Many tools exist for this purpose, and one of them, of course, is PowerShell.

Adam Bertram

Adam Bertram is a 20-year IT veteran, Microsoft MVP, blogger, and trainer. Adam is the founder of the e-learning tech screencast platform TechSnips. Catch up on Adam’s articles at adamtheautomator.com, or follow TechSnips on Twitter at @techsnips_io.

A Windows admin might need this information to create reports, to track down malware infection or to see who's in the office. Since this is a repeatable task, it's a good idea to build a script that you can reuse over and over again, rather than having to figure out how to do it every time.

In this article, I'm going to go over how to build a PowerShell script to find a logged-on user on your local Windows machine, as well as on many different remote Windows machines at once. By the end, you should have a good understanding of what it takes to query the logged-on user of a Windows computer. You will also understand how to build a PowerShell script to execute the command on multiple computers at the same time.

With PowerShell, getting the account information for a logged-on user of a Windows machine is easy, since the username is readily available using the Win32_ComputerSystem WMI instance. This can be retrieved via PowerShell by using either the Get-CimInstance or Get-WmiObject cmdlet. I prefer to use the older Get-WmiObject cmdlet because I’m still working on older machines.

Output

Output

If you prefer to use CIM, you can also use Get-CimInstance to return the same result.

End of article, right? I suppose you could say I did just show you how to discover a logged-on user remotely. However, we need to make this reusable, more user-friendly and easy to perform on multiple computers. Let's take it a step further and build a PowerShell function from this.

First, let's build our template function. It looks like this:

Here, we have an advanced function with a single parameter: ComputerName. We also want to incorporate some parameter validations to ensure that the computer responds to a ping request before we query it. Also, notice the parameter type: [string[]]. Notice how there is an extra set of brackets in there? This makes ComputerName a string collection, rather than just a simple string. This is going to allow us to specify multiple computer names, separated by commas. We’ll see how this comes into play a bit later.

Once we have the function template down, we’ll need to add some functionality. To do that, let’s add a foreach loop, in case $ComputerName has multiple computer names, and then create a custom object for each computer, querying each for the logged-on user.

Here, notice that instead of outputting only the username, we are building a custom object that outputs the computer name as well, so that when multiple computer names are used, I can tell which username coincides with which computer.

Now, let’s run this and see what the output looks like when we don't specify a computer name.

Without specified computer name

Without specified computer name

My local computer name is WINFUSIONVM, and I am logged in through a local account called Adam. Now, let's see what it looks like when we query a remote computer.

Queried a remote computer

Queried a remote computer

In the instance above, notice that the account exists within a domain. We know this because the username starts with MYLAB, rather than MEMBERSRV1.

Finally, let's pass a couple different computer names through this function.

Different computer names

Different computer names

You can see that CLIENT2's UserName is null. This is because no account is currently logged on the computer.

If you'd like a fully featured function with error control, feel free to download this function from my Github repo.

Join the 4sysops PowerShell group!

Your question was not answered? Ask in the forum!

13+

Users who have LIKED this post:

  • avatar
  • avatar
Share
17 Comments
  1. Ashish Singh 3 years ago

    For some scenarios, it returns null. I tried running it on a Virtual Machine running Windows 10 (14393) x64.

    6+

  2. Roi 3 years ago

    It lookes like that some things changed:

    Get-WmiObject –ComputerName client01 –Class Win32_ComputerSystem

    This returns no longer a property called UserName

    2+

    • Marc 2 years ago

      Yeah this isn't working for me either.

      2+

    • Luc Fullenwarth 2 years ago

      What is you client OS and powershell version?

      What is the OS and .Net Framework version of the target server?

      1+

  3. Dennis 2 years ago

    Hello,

    is there a way to list logged on users from a list createdbefore? I want to create a script  which exports a list of specific domain Computers. Then I want to get the logged on users and the information when the machine last bootet up. The result of this should be outputet as a csv.

    Could might help me out with this?

    I tired this without success:

    I really would appriciate your help.

    best regards

    D

    1+

  4. Author
    Adam Bertram 2 years ago

    You are so close! You just need to create the function that pulls the logged in user from a single computer and then loop over each computer calling the function ad well as the Get-WmiObject reference. Something like this:

    2+

    • Dennis 2 years ago

      Hello Adam,

      thank you for your reply 🙂

      I'm really at the beginning in writing powershell scripts. What you mean is to replace line 11 to 30 in my script with the code you provided so that it lookslike this?

      1+

      • Author
        Adam Bertram 2 years ago

        You will need to include the last bootup time within the foreach loop too so it can gather the information from each computer as it's reading them.

        2+

        • Dennis 2 years ago

          Hi Adam,

          thank you for your reply. So this would be the solution?:

          When I run this script like provided above I get a command line which tells me to enter a parameter without telling me which one. The Screenshot can be found under this link:

          https://www.dropbox.com/s/jrtgyxa1kd1slng/26-06-_2017_17-52-56.png?dl=0

          But I have to say it is in german language.

          thank you very much for your help 🙂

          regards Dennis

          1+

  5. Mauro 2 years ago

    I use:
    invoke-command -computername -scriptblock { qwinsta }
    or:
    qwinsta /server:

    8+

    • PatrikN 2 years ago

      Like some others, it did not work for me either. UserName is just empty, both on Server 2003, 2008 and Win10.

      Qwinsta, as Mauro suggested, did work, but didn't show the device og client name.

      Instead I found the PSTerminalServices module, which gave me exactly the information I wanted, and it can also do a lot more! (To get it installed, I had to unzip and manually rename the MSI file).

      I then ended up with this script (using Get-TSSession), which shows exactly the same information as Task Manager 🙂

      This can of course be run on remote computers (PSTerminalServices just need to be installed locally) and there is also some commands to get info about TS/RD servers and processes. Here is one mor script, with some extended info.

      Best regards,
      Patrik

      1+

  6. Eric W 1 year ago

    I am using "$LocalUser = get-wmiobject -class win32_ComputerSystem | Select username" which returns not only the user name but the domain name "Domain\UserName". how do pass this info while removing the domain part from the username?

    1+

  7. David Figueroa 1 year ago

    Eric W.

    Simple solution:
    $LocalUser = (Get-WmiObject -Class win32_computersystem | Select-Object -ExpandProperty username).split('\')[1]

    David F.

    4+

  8. Blake 1 year ago

    I use powershell and cmd to do this. The code below gets the currently logged on user from windows explorer. It will return more than 1 name if multiple users are currently logged in. Simply give $RemoteHost an IP address or Hostname.

    $RemoteHost = IPAddress/Hostname

    $LoggedInUser = tasklist /s $RemoteHost /v /FI "IMAGENAME eq explorer.exe" /FO list | find "User Name:"
    $LoggedInUser = $LoggedInUser.Substring(14)

    Blake

    5+

  9. David Figueroa 1 year ago

    Now that I've read the entire post & comments.. the easiest way is certainly without powershell.

    As Mauro pointed out, you can use qwinsta /server:servername, you can also use quser /server:servername.  The benefit of these is you don't require any special permissions on the machine to get the info.   You can also use qwinsta, quser & qprocess on a local machine.. qprocess with no parameters gives you your own processes with no special permissions.

    You can also use qprocess against a remote machine (that *does* require admin permissions, unless it is your own session.  qprocess /id:<sessionid> /server:<server>..

    And of course, there are a number of options to all these commands.

    David F.

    3+

  10. Todd M 1 year ago

    Hello, I have been trying to find a simple script or cmd to see if anyone is logged on to another computer.  I found your reply about the quser being used in a cmd prompt instead of a powershell script and you note that no special authority is needed.  However, when I try it on my own pc, it works fine but when querying somebody else's, it comes up with access denied.  I am using an account that has administrative authority so not sure why access denied is coming up.  I was wondering if you were familiar with the error: 0x00000005 enumerating sessionnames [5]:Access is denied.

    1+

  11. David Figueroa 1 year ago

    You do need to belong to the domain or have some authentication between the machines.  I'm guessing you are not in the same domain/workgroup?  You will need *some* sort of authentication between the source & target, but not special permissions beyond normal user permissions.

    I've seen access denied when the accounts were from untrusted accounts, or when trying to use qprocess without admin rights.

    David F.

    2+

    Users who have LIKED this comment:

    • avatar

Leave a reply

Your email address will not be published. Required fields are marked *

*

© 4sysops 2006 - 2019

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account