Knowing which users are currently logged on to a Windows machine can be helpful for system administrators, IT support, and security purposes. This guide provides several methods to list logged-on users using built-in Windows tools and via commands.
Why Check Currently Logged-on Users?
- Monitor Active Sessions: Identify who is using the system.
- Troubleshoot Issues: Diagnose login-related problems or performance bottlenecks.
- Security Checks: Ensure no unauthorized access has occurred.
Methods to List Currently Logged-on Users
1. Using Task Manager
- Press Ctrl + Shift + Esc to open the Task Manager.
- Click on the Users tab.
- You will see the list of logged-on users, their session types, and their statuses (e.g., active or disconnected).
2. Using Command Prompt
- Open Command Prompt:
- Press Win + R, type
cmd
, and press Enter.
- Press Win + R, type
- Use the following commands:
query user
: Displays the list of active sessions and users.whoami
: Shows the username of the current user.net user
: Lists all user accounts on the system, though it does not indicate logged-on users.
3. Using PowerShell
-
Open PowerShell:
- Press Win + R, type
powershell
, and press Enter.
- Press Win + R, type
-
Run the following command:
Get-WmiObject -Class Win32_ComputerSystem | Select-Object -ExpandProperty UserName
- This command shows the currently logged-in user on the console session.
4. Using Event Viewer
- Press Win + R, type
eventvwr
, and press Enter. - Navigate to:
- Windows Logs > Security.
- Look for Event ID 4624 (logon events) to see who logged in and Event ID 4647 for logoff events.
5. Using Sysinternals Tools
- Download and install Sysinternals tools from Microsoft (if not already installed).
- Use the PsLoggedOn tool:
- Open Command Prompt.
- Run
psloggedon
to list currently logged-on users locally and remotely.
6. Using Remote Desktop Services (RDS)
-
If using an RDS server or session host, use the Remote Desktop Services Manager or
qwinsta
command to list users logged into terminal sessions:qwinsta
March 11, 2017 updated by
Leave a reply »
How can I get a list of users currently logged on? If you’re wondering how to find out how many users are currently logged into your Windows 10 computer, there are several ways to view who’s logged on. In this tutorial we’ll explain 2 methods to get a list of currently logged in users in Windows 10 / 8 / 7.
Method 1: See Currently Logged in Users Using Query Command
- Press the Windows logo key + R simultaneously to open the Run box. Type cmd and press Enter.
- When the Command Prompt window opens, type query user and press Enter. It will list all users that are currently logged on your computer.
Method 2: See Currently Logged in Users Using Task Manager
- Right-click on the taskbar and select Task Manager to launch Task Manager. If you’re using Windows 10/8, you might need to click the More details button at the bottom to see active processes.
- Click the Users tab at the top of Task Manager, you can see a list of currently logged in users and their status.
- Previous Post: Change Sync Frequency of Email Checking in Windows 10 Mail App
- Next Post: Customize or Add Items to Send To Menu in Windows 10
In Windows 11, there are several ways to check who is currently logged into the Windows or who you are logged in as locally. If you are on a shared network and want to check who is logged in to another Windows 11 computer remotely, there are several command lines you can use to query who is currently logged into that particular computer.
The remote method is especially useful when there are several people who often remotely login to a shared computer. If you try to login to a shared computer while someone else is already logged on, you will be given the option to continue or force the other user to logout or disconnect. Thus, it would be nice to remotely check who is currently logged into the shared computer first, before trying to login.
Also see: How to Restrict User Access to a Folder or Drive in Windows 11
Check who is logged in on Windows 11 using Command Prompt
Locally
- Search for Command Prompt via Start and open it.
- In the Command Prompt window, enter the following command to query who is currently logged in.
query user
- The user who is logged in will be shown under USERNAME along with other information such as logon time.
Alternatively, you can use the “whoami” command instead to check who you are logged in as in Windows 11. In Command Prompt, enter the following command to check “who am I logged in as” in the local computer (or the computer you remotely logged on to).
whoami
Remotely
- Search for and open Command Prompt via Start menu.
- In Command Prompt, enter the following command to query who is logged in on a Windows 11 remote computer. Replace the ComputerName with the actual computer name of the PC you want to check.
query session /server:ComputerName
You can also use query user instead of query session.
query user /server:ComputerName
- Command prompt will then shows details about the user who is currently logged into the remote computer.
In addition, you can also use the WMIC command line to check who is logged in on Windows 11 remotely. In the command prompt window, enter the following command. Replace the ComputerName with the actual computer name of the remote computer you are querying.
WMIC /NODE:"ComputerName" COMPUTERSYSTEM GET USERNAME
Alternatively, you can use the IP address of the remote computer instead of the computer name for this command to query who is logged in.
WMIC /NODE:"IPaddress" COMPUTERSYSTEM GET USERNAME
What to do if you encounter RPC or other error
If you encounter RPC error such as “The RPC service is unavailable” error while querying who is logged in on Windows 11, try to set the following registry value on the remote computer.
- Search for Registry Editor via Start and open it.
- Navigate to the following registry key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server
- Next, double-click AllowRemoteRPC.
- In the Value data field, enter “1” and then click OK to save the changes.
- Close Registry Editor and restart the remote computer for the changes to take effect.
Check who am I logged in as via Task Manager or Start menu
If you only want to find out who you are logged in as on a Windows 11 local computer or a computer you remotely logged in to, you can quickly do so via the Task Manager or the Start menu.
To open Task Manager in Windows 11, right-click the Start icon on the taskbar and then select Task Manager. Alternatively, you can press Ctrl + Alt + Del to open the lock screen and then select Task Manager to open it.
Next, in the Task Manager window, select the Users tab. From there, you can see which user is currently logged into the Windows 11 computer.
Another method to find out who is logged into Windows 11 is by simply opening the Start menu. Click the Start icon to open the Start menu. The currently logged in user will be shown at the bottom left corner of the Start menu.
-
Use the WMI Class to Get Logged on Users in PowerShell
-
Use the .NET Environment Class to Get Logged on Users in PowerShell
-
Use the
query
Command to Get Logged on Users in PowerShell
When we work with Windows, at some point, we’ll probably need to find out which users are currently logged on to a computer. Luckily, we can use PowerShell to get current users on local or remote computers.
This article will discuss several ways to use PowerShell to get current logged-in users on a computer. The methods we know will include native commands, .NET classes, and Windows Management Instrumentation (WMI) specific cmdlets.
Use the WMI Class to Get Logged on Users in PowerShell
Let us start with the PowerShell native cmdlets called Get-WMIObject
and Get-CimInstance
. These cmdlets allow us to fetch information, including the currently logged-on user, using the Windows Management Instrumentation or WMI classes on a local or remote computer.
Note
Get-WMIObject
is the older (deprecated) cmdlet and is only available to Windows PowerShell version 5.1. Conversely, the Get-CIMInstance
command is the newer, more secure cmdlet and is open to the latest PowerShell versions.
To use Windows PowerShell to get the current user, invoke either command targeting the Win32_ComputerSystem
class. The Win32_ComputerSystem
.NET class includes various properties, including the Username property.
To do so, open a Windows PowerShell window and run the commands below.
Example code:
# Use any of the commands
(Get-WMIObject -ClassName Win32_ComputerSystem).Username
(Get-CimInstance -ClassName Win32_ComputerSystem).Username
It is worth noting that querying the Win32_ComputerSystem
.NET class will only output the username of the currently logged-on user onto the computer (console session). Therefore, if the user logs on remotely (e.g., Remote Desktop), the username will be blank.
Both cmdlets return the same output, as shown below. If the currently logged-in user is a domain user account, the command will return the domain and the username (domain\username).
But for a local account, the output would be a local computer together with the username.
Output:
The Get-WMIObject
and Get-CimInstance
commands have a parameter called -ComputerName
, which accepts the computer’s name to query. Using this parameter means that we can query the same information from a remote machine in the network.
If we need to get only the user’s username without the domain, a solution is to separate the output using the split()
method.
The snippet below will split the username property into two using the backslash (\
) character as the delimiter. The [1]
part will use the cmdlet to output only the result at index [1].
It is worth noting that indexes start with 0; specifying index one will show the result at the second position.
Example code:
((Get-WMIObject -ClassName Win32_ComputerSystem).Username).Split('\')[1]
Windows PowerShell outputs the user part only, like the output below.
Output:
Use the .NET Environment Class to Get Logged on Users in PowerShell
PowerShell is an object-oriented language and shell. Everything that we work on is an object.
When we run a command, the output is an object. If we declare a variable, that variable is an object.
These objects have a hierarchy that defines the proper data type, similar to blueprints. These said blueprints are called .NET classes or simply classes.
The class associated with it is the .NET Environment
class. So how do we use the Environment
class in PowerShell to get the current user?
The Environment class contains a Username
property, whose value is the currently logged-in user’s username. To retrieve the username property value, run the command below in PowerShell.
Example code:
[System.Environment]::UserName
Aside from the Username
property, the Environment
class also contains a process to get the value of an environment variable. The method’s name is GetEnvironmentVariable
function.
To retrieve the current user using this method, run the command below.
Example code:
[System.Environment]::GetEnvironmentVariable('username')
Output:
Use the .NET WindowsIdentity Class to Get Logged on Users in PowerShell
The WindowsIdentity
.NET class is another .NET class we can invoke in Windows PowerShell to retrieve the current user. This class has a method called the GetCurrentName
function, which outputs an object that represents the current Windows user.
To retrieve the current user details, run the command below.
Example code:
[System.Security.Principal.WindowsIdentity]::GetCurrent()
The cmdlet returns the current user object properties, including the Name
property. The Name
property value follows the domain\user format.
Use the query
Command to Get Logged on Users in PowerShell
If we are a system admin or a domain user, we’ve logged on to a remote machine via the Remote Desktop Protocol or RDP at least once, perhaps to manage resources or use applications. Suppose we want to know who is currently logged on and using system resources.
Windows has a built-in command-line tool called the query
command to list all the currently logged-on users on a computer. The command also shows us if the user logged on via a remote desktop session or locally to the computer.
The query
legacy command contains two parameters pertinent to getting the logged-on users; session
and user
. The session
parameter displays all the computer sessions, while the user
parameter displays the users and their sessions.
For example, execute the command below to list the sessions on the current server.
Example code:
query user /server:$server
Output:
USERNAME SESSION NAME ID STATE IDLE TIME LOGON TIME
user01 console 1 Active none 3/27/2022 2:36 PM
After running the command, we’ll notice that quser
returns the sessions, but there are no blank sessions this time. The command also shows the users’ idle time and login timestamp.
Compared with other commands, the quser
is the more appropriate command in PowerShell to get current users.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
При расследовании различных инцидентов администратору необходимо получить информацию кто и когда заходил на определенный компьютер Windows. Историю входов пользователя в доменной сети можно получить из журналов контроллеров домена. Но иногда проще получить информацию непосредсвенно из логов компьютера. В этой статье мы покажем, как получить и проанализировать историю входа пользователей на компьютер/сервер Windows. Такая статистика поможет вам ответить на вопрос “Как в Windows проверить кто и когда использовал этот компьютере”.
Содержание:
- Настройка политики аудита входа пользователей в Windows
- Поиск событий входа пользователей в журнале событий Windows
- Анализ событий входа пользователей в Windows с помощью PowerShell
Настройка политики аудита входа пользователей в Windows
Сначала нужно включить политик аудита входа пользователей. На отдельностоящем компьютере для настройки параметров локальной групповой политики используется оснастка gpedit.msc. Если вы хотите включить политику для компьютеров в домене Active Directorty, нужно использовать редактор доменных GPO (
gpmc.msc
).
- Запустите консоль GPMC, создайте новую GPO и назначьте ее на Organizational Units (OU) с компьютерами и / или серверами, для которых вы хотите включить политику аудита событий входа;
- Откройте объект GPO и перейдите в раздел Computer Configuration -> Policies -> Windows Settings -> Security Settings –> Advanced Audit Policy Configuration -> Audit Policies -> Logon/Logoff;
- Включите две политики аудита Audit Logon и Audit Logoff. Это позволит отслеживать как события входа, так и события выхода пользователей. Если вы хотите отслеживать только успешные события входа, включите в настройках политик только опцию Success;
- Закройте редактор GPO и обновите настройки политик на клиентах.
Поиск событий входа пользователей в журнале событий Windows
После того как вы включили политики аудита входа, при каждом входе пользователя в Windows в журнале Event Viewer будет появляться запись о входе. Посмотрим, как она выглядит.
- Откройте оснастку Event Viewer (
eventvwr.msc
); - Разверните секцию Windows Logs и выберите журнал Security;
- Щелкните по нему правой клавишей и выберите пункт Filter Current Log;
- В поле укажите ID события 4624 и нажмите OK;
- В окне события останутся только события входа пользователей, системных служб с описанием
An account was successfully logged on
; - В описании события указано имя и домен пользователя, вошедшего в систему:
New Logon: Security ID: WINITPRO\a.khramov Account Name: a.khramov Account Domain: WINITPRO
Ниже перечислены другие полезные EventID:
Event ID | Описание |
4624 | A successful account logon event |
4625 | An account failed to log on |
4648 | A logon was attempted using explicit credentials |
4634 | An account was logged off |
4647 | User initiated logoff |
Если полистать журнал событий, можно заметить, что в нем присутствуют не только события входа пользователей на компьютер. Здесь также будут события сетевого доступа к этому компьютеру (при открытии по сети общих файлов или печати на сетевых принтерах), запуске различных служб и заданий планировщика и т.д. Т.е. очень много лишний событий, которые не относятся ко входу локального пользователя. Чтобы выбрать только события интерактивного входа пользователя на консоль компьютера, нужно дополнительно сделать выборку по значению параметра Logon Type. В таблице ниже перечислены коды Logon Type.
Код Logon Type | Описание |
---|---|
0 | System |
2 | Interactive |
3 | Network |
4 | Batch |
5 | Service |
6 | Proxy |
7 | Unlock |
8 | NetworkCleartext |
9 | NewCredentials |
10 | RemoteInteractive |
11 | CachedInteractive |
12 | CachedRemoteInteractive |
13 | CachedUnlock |
При удаленном подключении к рабочему столу компьютера по RDP, в журнале событий появится записи с Logon Type 10 или 3. Подробнее об анализе RDP логов в Windows.
В соответствии с этой таблицей событие локального входа пользователя на компьютер должно содержать Logon Type: 2.
Для фильтрации события входа по содержать Logon Type лучше использовать PowerShell.
Анализ событий входа пользователей в Windows с помощью PowerShell
Допустим, наша задача получить информацию о том, какие пользователи входили на этот компьютер за последнее время. Нам интересует именно события интерактивного входа (через консоль) с
LogonType =2
. Для выбора события из журналов Event Viewer мы воспользуемся командлетом Get-WinEvent.
Следующий PowerShell скрипт выведет история входа пользователей на текущий компьютер и представит ее в виде графической таблицы Out-GridView.
$query = @'
<QueryList>
<Query Id='0' Path='Security'>
<Select Path='Security'>
*[System[EventID='4624']
and(
EventData[Data[@Name='VirtualAccount']='%%1843']
and
EventData[Data[@Name='LogonType']='2']
)
]
</Select>
</Query>
</QueryList>
'@
$properties = @(
@{n='User';e={$_.Properties[5].Value}},
@{n='Domain';e={$_.Properties[6].Value}},
@{n='TimeStamp';e={$_.TimeCreated}}
@{n='LogonType';e={$_.Properties[8].Value}}
)
Get-WinEvent -FilterXml $query | Select-Object $properties|Out-GridView
Если нужно выбрать события входа за последние несколько дней, можно добавить pipe с таким условием:
|Where-Object {$_.TimeStamp -gt '5/10/22'}
Командлет Get-WinEvent позволяет получить информацию с удаленных компьютеров. Например, чтобы получить историю входов с двух компьютеров, выполните следующий скрипт:
'msk-comp1', 'msk-comp2' |
ForEach-Object {
Get-WinEvent -ComputerName $_ -FilterXml $query | Select-Object $properties
}
Если протокол RPC закрыт между компьютерами, вы можете получить данные с удаленных компьютеров с помощью PowerShell Remoting командлета Invoke-Command:
Invoke-Command -ComputerName 'msk-comp1', 'msk-comp2' {Get-WinEvent -FilterXml $query | Select-Object $properties}