Список залогиненных пользователей windows

— Ой, у меня ничего не работает, помогите!
— Не переживайте, сейчас всё исправим. Назовите имя компьютера…
(классика жанра из звонков в техподдержку)

Хорошо, если у вас есть инструмент а-ля BgInfo или ваши пользователи знают про шорткат Windows+Pause/Break и умеют его нажимать. Встречаются даже редкие экземпляры, которые успели выучить имя своей машины. Но часто у звонящего вдобавок к его основной проблеме появляется вторая: узнать имя/IP-адрес компьютера. И нередко на решение этой второй проблемы уходит куда больше времени, чем первой (а надо было всего лишь обои поменять или вернуть пропавший ярлык :).
А ведь намного приятнее услышать что-то вроде:
— Татьяна Сергеевна, не беспокойтесь, уже подключаюсь…

А надо для этого не так уж и много.

Специалисту техподдержки достаточно лишь выучить наизусть имена машин и помнить, кто за какой работает.

Перед описанием решения, которым мы пользуемся сейчас, я кратко рассмотрю другие варианты, чтобы

раскритиковать их в пух и прах

объяснить свой выбор.

  1. BgInfo, Desktop Info и им подобные. Если много денег, есть и платные. Суть в том, что на десктоп выводится техническая информация: имя машины, IP-адрес, логин и т.д. В Desktop Info можно даже графики производительности запилить на половину экрана.
    Не устраивает то, что для того же Bginfo, например, пользователю нужно сворачивать окна, чтобы увидеть нужные данные. Еще мы с коллегами не раз наблюдали у BgInfo характерный артефакт, когда новый текст выводится поверх старого.
    Некоторых пользователей раздражает тот факт, что админы рисуют пугающее 192.168.0.123 на мордочке растянувшегося на рабочем столе котика портят эстетику фоновой картинки, и, разумеется, это жутко демотивирует и напрочь убивает рабочий настрой.
  2. Ярлык а-ля «Кто я» (не пытайтесь добавить ему знак вопроса в конце :). Классический ярлык на рабочем столе, за которым прячется аккуратный или не очень скрипт, выводящий нужную информацию в виде диалогового окна. Иногда вместо ярлыка на рабочий стол кладут сам скрипт, что ИМХО моветон.
    Недостаток в том, что для запуска ярлыка, как и в первом случае, нужно сворачивать все открытые окна (баловней судьбы, у которых на рабочей машине открыто единственное окно с пасьянсом, в расчет не берём). Кстати, а ваши пользователи знают, куда нужно тыкнуть, чтобы свернуть все окна? Правильно, пальцем в глаз админу.

Также кэп подсказывает, что у обоих описанных выше способов основной недостаток в том, что в получении информации участвует пользователь,

который может быть подслеповат, глуп и вообще соврать.

Вариант с повышением компьютерной грамотности, когда все знают, где в Windows смотреть имя своей машины, рассматривать не буду: дело благородное, но очень трудное. А если в компании текучка кадров, то и вовсе гиблое. Что там говорить, в большинстве случаев и логин-то свой не помнят.

Душу излил, а теперь к делу.
За основу была взята идея хабровчанина mittel из этой статьи.
Суть задумки в том, что при входе пользователя в Windows логон-скрипт заносит нужную информацию (время и имя машины) в определенный атрибут учётной записи пользователя. А при выходе из системы отрабатывает аналогичный логофф-скрипт.

Сама идея мне понравилась, а вот в реализации кое-что не устроило.

  1. Групповая политика, в которой прописаны логон- и логофф-скрипты для пользователей, применяется ко всему домену, поэтому скрипты будут отрабатывать на любой машине, на которую логинятся пользователи. Если у вас наряду с рабочими станциями используются терминальные решения (например, Microsoft RDS или продукты Citrix), такой подход будет неудобным.
  2. Данные заносятся в атрибут Department учетной записи пользователя, на который у рядового пользователя есть доступ только на чтение. Помимо атрибута учётной записи пользователя, скрипт также вносит изменения в атрибут Department учётной записи компьютера, который по умолчанию пользователи также менять не могут. Поэтому чтобы решение работало, автор предлагает изменить стандартые настройки безопасности для объектов AD.
  3. Формат даты зависит от настроек локализации на конечной машине, поэтому с одной машины можем получить 10 ноября 2018 14:53, а с другой 11/10/18 2:53 p.m.

Для устранения этих недостатков было сделано следующее.

  1. GPO линкуется не к домену, а к OU с машинами (я разделяю пользователей и машины по разным OU и другим советую). При этом для loopback policy processing mode выставлен режим merge.
  2. Скрипт будет заносить данные только в учетную запись пользователя в атрибут Info, который пользователь может менять самостоятельно для своей учётной записи.
  3. Изменен кусок кода, генерирующий значение атрибута

Теперь скрипты выглядят так:

SaveLogonInfoToAdUserAttrib.vbs

On Error Resume Next
Set wshShell = CreateObject("WScript.Shell")
strComputerName = wshShell.ExpandEnvironmentStrings("%COMPUTERNAME%")
Set adsinfo = CreateObject("ADSystemInfo")
Set oUser = GetObject("LDAP://" & adsinfo.UserName)
strMonth = Month(Now())
If Len(strMonth) < 2 then
  strMonth = "0" & strMonth
End If
strDay = Day(Now())
If Len(strDay) < 2 then
  strDay = "0" & strDay
End If
strTime = FormatDateTime(Now(),vbLongTime)
If Len(strTime) < 8 then
  strTime = "0" & strTime
End If
strTimeStamp = Year(Now()) & "/" & strMonth & "/" & strDay & " " & strTime
oUser.put "info", strTimeStamp & " <logon>" & " @ " & strComputerName
oUser.Setinfo

SaveLogoffInfoToAdUserAttrib.vbs

On Error Resume Next
Set wshShell = CreateObject("WScript.Shell")
strComputerName = wshShell.ExpandEnvironmentStrings("%COMPUTERNAME%")
Set adsinfo = CreateObject("ADSystemInfo")
Set oUser = GetObject("LDAP://" & adsinfo.UserName)
strMonth = Month(Now())
If Len(strMonth) < 2 then
  strMonth = "0" & strMonth
End If
strDay = Day(Now())
If Len(strDay) < 2 then
  strDay = "0" & strDay
End If
strTime = FormatDateTime(Now(),vbLongTime)
If Len(strTime) < 8 then
  strTime = "0" & strTime
End If
strTimeStamp = Year(Now()) & "/" & strMonth & "/" & strDay & " " & strTime
oUser.put "info", strTimeStamp & " <logoff>" & " @ " & strComputerName
oUser.Setinfo

Кто первым найдет все отличия между логон- и логофф-скриптом, тому плюс в карму. :)
Также для получения наглядной информации создан такой небольшой PS-скрипт:

Get-UsersByPCsInfo.ps1

$OU = "OU=MyUsers,DC=mydomain,DC=com"
Get-ADUser -SearchBase $OU -Properties * -Filter * | Select-Object DisplayName, SamAccountName, info | Sort DisplayName | Out-GridView -Title "Информация по логонам" -Wait

Итого всё настраивается на раз-два-три:

  1. создаем GPO с нужными настройками и линкуем его к подразделению с рабочими станциями пользователей:

  2. идем пить чай (если AD с большим количеством пользователей, то чая нужно много :)
  3. запускам PS-скрипт и получаем результат:

    В верхней части окна есть удобный фильтр, в котором можно отбирать данные по значениям одного или нескольких полей. Клик по столбцам таблицы сортирует записи по значениям соответствующих полей.

Можно красиво «упаковать» наше решение.

Для этого добавим ярлык для запуска скрипта специалистам техподдержки, у которого в поле «объект» будет что-то такое:
powershell.exe -NoLogo -ExecutionPolicy Bypass -File "\\server\share\Scripts\Get-UsersByPCsInfo.ps1"

Если сотрудников техподдержки много, то можно раздать ярлык с помощью GPP.

Несколько замечаний напоследок.

  • На машине, откуда запускается PS-скрипт, должен быть установлен модуль Active Directory для PowerShell (для этого достаточно добавить средства администрирования AD в компонентах Windows).
  • бОльшую часть атрибутов своей учётной записи пользователь по умолчанию редактировать не может. Учитывайте это, если решите использовать атрибут, отличный от Info.
  • Проинформируйте всех причастных коллег о том, какой атрибут будете использовать. Например, тот же Info используется для интерактивного добавления заметок к ящику пользователя в админке Exchange Server и кто-то легко может его затереть, либо опечалился, когда добавленную им информацию затрет ваш скрипт.
  • Если у вас несколько сайтов Active Directory, то делайте поправку на задержки репликации. Например, если вы хотите получить актуальную информацию о пользователях с AD-сайта A, а запускаете скрипт с машины из AD-сайта B, то можно сделать так:
    Get-ADUser -Server DCfromSiteA -SearchBase $OU -Properties * -Filter * | Select-Object DisplayName, SamAccountName, info | Sort DisplayName | Out-GridView -Title "Информация по логонам" -Wait

    DCfromSiteA — имя контроллера домена сайта A (по умолчанию командлет Get-AdUser подключается к ближайшему контроллеру домена)

Источник картинок

Буду признателен, если вы пройдете короткий опрос ниже.

Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.

Чем пользуетесь?

27.22% bginfo, Desktop info etc. (бесплатное ПО)49

0.56% платные аналоги bginfo1

6.67% сделаю так, как в статье12

3.89% не актуально, т.к. использую VDI/RDS etc.7

21.11% пока не использую ничего, но задумываюсь38

28.89% мне не нужно собирать такие данные52

11.67% другое (поделитесь в комментариях)21

Проголосовали 180 пользователей. Воздержались 50 пользователей.

If you want to find all the Signed in Users in Windows 11 or Windows 10, here is how you can do that. It is possible to find the name of all signed in users on your computer with the help of Start Menu, Command Prompt, and Task Manager. You can follow any of the methods as per your requirements.

How to find all signed in users in Windows 11/10 

Let’s assume that you have changed something in the Registry Editor, and you need to restart your computer to get the change. If your computer has only one user, you can simply restart it. However, if you have multiple users and you use all those users’ accounts for different purposes, it might be complicated for you. Many people often use different user accounts to do different tasks or for different members of the family. If you do the same, you need to save the work in those user accounts to retain all the data after the restart. That is why you need to know about the signed-in users’ names.

How to find all Signed in Users using Start Menu

To find all Signed-in Users in Windows 11/10 using Start Menu, follow these steps:

  1. Press the Windows key or click the Start Menu button
  2. Click on the profile picture.
  3. Find the username with Signed in tag.

First, you need to open the Start Menu on your computer. For that, you can either press the Windows key on your keyboard or click on the Start Menu button visible on the Taskbar.

Once the Start Menu is opened, you need to click on your profile picture or name. Here you can find all the users. You need to find the usernames with Signed in tag.

How to find all signed in users in Windows 11/10 

Those accounts are currently signed in to your computer.

For your information, you can do the same thing with the help of Command Prompt, Windows PowerShell, or Windows Terminal. You can open any of these utilities and use the same command to get the job done. However, for this example, we are going to use the traditional Command Prompt.

Read: How to list all Users in Windows 11

Find out who is logged in using Command Prompt

To find all signed-in users using Command Prompt, follow these steps:

  1. Search for cmd in the Taskbar search box.
  2. Click on the search result.
  3. Enter this command: query user
  4. Find the list of users.

Let’s check out more about these steps.

First, you need to open the Command Prompt. For that, you can search for cmd in the Taskbar search box and click on the individual search result.

Then enter this command:

query user

It lists down all the signed in users on the prompt.

How to find all signed in users in Windows 11/10 

You can check the USERNAME column for this purpose. Also, it displays the current user account using an arrow (>).

How to see all signed-in users in Windows using Task Manager

To see all signed in users in Windows 11/10 using Task Manager, follow these steps:

  1. Press Ctrl+Shift+Escto open Task Manager.
  2. Switch to the Users tab.
  3. Find the signed in users.

Let’s delve into these steps in detail.

Like Command Prompt and the Start Menu methods, you can use the Task Manager to see all the signed in users on Windows 11/10.

For that, press Ctrl+Shift+Esc to open the Task Manager on your computer. Then, switch to the Users tab.

How to find all signed in users in Windows 11/10 

Here you can find all the signed-in users.

How can I see what users are logged in?

To see what users are logged in to Windows 11/10, you can follow any of the above-mentioned guides. It is possible to see the list using Task Manager, Start Menu, and Command Prompt. In the Command Prompt, enter this command: query user.

How do I see all users on my computer?

To see users on your computer, you can get the help of Windows PowerShell. For that, you can open the PowerShell or the PowerShell instance in Windows Terminal. Then, enter this command: net user. It lists down all the users on your screen.

Read: How to create a new User Account or Profile in Windows 11/10.

Довольно часто администратору нужно быстро узнать имя пользователя, который выполнил вход на удаленном компьютере Windows. В это статье мы рассмотрим несколько утилит и PowerShell скриптов, которые помогут вам узнать имена пользователей, залогиненых на удаленных компьютерах в сети.

Содержание:

  • Утилиты PSLoggedOn и Qwinsta
  • Получаем имя пользователя на удаленном компьютере через PowerShell
  • PowerShell скрипт для проверки пользователей на удаленных компьютерах

Утилиты PSLoggedOn и Qwinsta

В комплекте утилит SysInternals PSTools от Microsoft есть консольная утилита PSLoggedOn.exe, которую можно использовать для получения имени пользователя, который вошел на удаленный компьютер, а также список подключенных к нему SMB сеансов.

Скачайте утилиту и запустите ее в формате:

psloggedon \\RemoteCompName

утилита PSLoggedOn

Как вы видите, утилита вернула имя залогиненного пользователя (Users logged on locally), а также список пользователей, которые по сети используют ресурсы с этого компьютера (Users logged on via resource shares).

Если нужно получить только имя пользователя, вошедшего локально, используйте опцию –l:

Psloggedon.exe \\wks215s1 –l

Утилита Psloggedon подключается к реестру и проверяет в нем имя пользователя, вошедшего локально. Для этого должна быть включена служба RemoteRegistry. Вы можете запустить ее и настроить автозапуск службы с помощью PowerShell:

Set-Service RemoteRegistry –startuptype automatic –passthru
Start-Service RemoteRegistry

Также можно получить список сессий на удаленном компьютере с помощью встроенной утилиты
qwinsta
. Эта утилита должна быть знакома любому администратору, управляющему терминальными серверами с Remote Desktop Services. Чтобы получить список сессий с удаленного компьютера, выполнит команду:

qwinsta /server:dc01

qwinsta - список сессий пользователей на компьютере

Утилита возвращает список всех сессий (активных и отключенных по таймауту) на RDS сервере или десктопной редакции Windows 10 (даже если вы разрешили к ней множественные RDP подключения).

Если при подключении к удаленному серверу через qwinsta вы получаете ошибку Error 5 Access Denied, проверьте что на удаленном компьютере разрешено удаленное управление пользователями через RPC. Включите, если нужно через реестр следующей командой или через GPO:

reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v "AllowRemoteRPC" /t "REG_DWORD" /d "1" /f

Получаем имя пользователя на удаленном компьютере через PowerShell

Вы можете получить имя пользователя, который залогинен на компьютере через WMI класс Win32_ComputerSystem. Откройте консоль PowerShell и выполните команду:

Get-WmiObject -class Win32_ComputerSystem | Format-List Username

Команда вернула имя пользователя, который выполнил вход на компьютер.

Get-WmiObject -class Win32_ComputerSystem Username

У командлета Get-WmiObject есть параметр –ComputerName, который можно использовать для получения доступа к WMI объектам на удаленном компьютере. Следующая команда вернет имя пользователя с удаленного компьютера:

(Get-WmiObject -class Win32_ComputerSystem –ComputerName wks215s1).Username

Get-WmiObject ComputerName Username имя пользователя с удаленного компьютера windows

Данная команда показывает только пользователя, вошедшего на консоль (не через RDP).

Также для получения информации с удаленных компьютеров можно использовать PSRemoting с помощью командлета Invoke-Command.

Если нужно получить только имя пользователя на компьютере (без домена), воспользуетесь следующими командами:

$userinfo = Get-WmiObject -ComputerName 'wks215s1' -Class Win32_ComputerSystem
$user = $userinfo.UserName -split '\\'
$user[1]

powershell скрипт вывести имя пользователя с удаленного компьютера

В современных версиях PowerShell Core (pwsh.exe) вместо Get-WmiObject нужно использовать CIM командлет Get-CimInstance:

Get-CimInstance –ComputerName wks215s1 –ClassName Win32_ComputerSystem | Select-Object UserName

Или

(Get-CimInstance -ComputerName wks215s1 -ClassName Win32_ComputerSystem).CimInstanceProperties | where{$_.Name -like "UserName"}| select value

Get-CimInstance узнать имя пользователя с удаленного компьютера

GetCiminstance использует WinRM для подключения к удаленным компьютерам, поэтому на них нужно включить и настроить WinRM через GPO или командой:

WinRM quickconfig

PowerShell скрипт для проверки пользователей на удаленных компьютерах

Если вам нужно собрать информацию о пользователях сразу с нескольких компьютерах, можете использовать следующую PowerShell функцию получить имена пользователей.

function Get-LoggedUser
{
    [CmdletBinding()]
    param
    (
        [string[]]$ComputerName 
    )
    foreach ($comp in $ComputerName)
    {
        $output = @{'Computer' = $comp }
        $output.UserName = (Get-WmiObject -Class win32_computersystem -ComputerName $comp).UserName
  [PSCustomObject]$output
    }
}

На вход функции Get-LoggedUser нужно передать имена компьютеров, на которых нужно проверить имена пользователей:

Get-LoggedUser wks215s1,wks215s2,dc01

Get-LoggedUser - powershell скрипт для получения имени залогиненых пользователей

Если для какого-то компьютера функция вернула пустое имя пользователя, значит на компьютер никто не залогинен.

Можно получить имена пользователей, которые работают на компьютерах в домене Active Directory. Для получения списка компьютеров нужно использовать командлет Get-ADComputer. В следующем примере мы получим имена пользователей, которые работают за активными компьютерами в определенном OU домена. Чтобы скрипт работал быстрее перед тем, как обратится к обратится к удаленному компьютеру, я добавил проверку его доступности по сети через ICMP пинг с помощью командлета Test-NetConnection:

function Get-LoggedUser
{
    [CmdletBinding()]
    param
    (
        [string[]]$ComputerName 
    )
    foreach ($comp in $ComputerName)
    {
        if ((Test-NetConnection $comp -WarningAction SilentlyContinue).PingSucceeded -eq $true) 
            {  
                $output = @{'Computer' = $comp }
                $output.UserName = (Get-WmiObject -Class win32_computersystem -ComputerName $comp).UserName
            }
            else
            {
                $output = @{'Computer' = $comp }
                         $output.UserName = "offline"
            }
         [PSCustomObject]$output 
    }
}
$computers = (Get-AdComputer -Filter {enabled -eq "true"} -SearchBase 'OU=Kazan,DC=winitpro,DC=loc').Name
Get-LoggedUser $computers |ft -AutoSize

Также обратите внимание, что вы можете хранить в свойствах компьютеров в AD имя пользователя, который выполнил вход. Для этого можно использовать логон скрипт, описанный в статье “Set-ADComputer: добавляем информацию о пользователе в свойства компьютеров AD”

После этого вам не нужно сканировать все компьютеры, чтобы найти где залогинен определенный пользователь. Можно найти компьютер пользователя простым запросом к Active Directory:

$user='dvpetrov'
$user_cn=(get-aduser $user -properties *).DistinguishedName
Get-ADComputer -Filter "ManagedBy -eq '$user_cn'" -properties *|select name,description,managedBy|ft

Table of Contents

  • 1. Introduction to the Problem Statement
  • 2. Using the query Command
  • 3. Using Get-Process
  • 4. Using  query Command on Remote Server
  • 5. Invoke-Command with Win32_LogonSession and Win32_LoggedOnUser for Remote Server
  • 6. Getting One Currently Logged-on User
    • 6.1 Using whoami Command
    • 6.2 Using Get-WmiObject for Detailed Information
    • 6.3 Using Invoke-Command for Remote Execution
    • 6.4 Using Remote WMI Queries
  • 7. Conclusion

This topic can be interpreted as getting all current logged-on users and retrieving one logged-on user in PowerShell. Let’s learn both interpretations.

1. Introduction to the Problem Statement

In network and system administration, it’s often necessary to determine which users are currently logged on to a system. This information can be critical for security, auditing, or managing system resources. PowerShell, with its powerful scripting capabilities, offers several methods to retrieve logged-on user information. We’ll explore these methods, providing examples and expected outputs. The goal is to identify the best approach for different scenarios, considering factors like detail, performance, and environment (local or remote).

2. Using the query Command

One of the quickest ways to get logged-on users is by using the query user command.

Example:

Output:

USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME

user1                 console             1  Active      none   6/17/2021 8:00 AM

user2                 rdptcp#3           2  Active      1+00   6/17/2021 9:30 AM

Explanation:

  • Displays a list of all users logged on, along with session details, idle time, and logon time.

Performance:

  • Quick and efficient for local system checks.

3. Using Get-Process

We can inspect user-owned processes to infer logged-on users.

Example:

GetProcess | WhereObject {$_.UserName} | FormatTable UserName Unique

Output:

UserName

DOMAIN\user1

DOMAIN\user2

Explanation:

We can use the PowerShell command Get-Process | Where-Object {$_.UserName} | Format-Table UserName -Unique to gather information about the processes running on our computer, specifically focusing on the unique usernames associated with these processes. Let’s break it down:

  • Get-Process: This cmdlet allows us to retrieve information about the processes currently running on our computer. It provides a list of all process objects active on the local system.
  • | (Pipe): In PowerShell, we use the pipe character to pass the output of one command as input to another. In this instance, it’s used to send the output of Get-Process to the Where-Object cmdlet.
  • Where-Object {$_.UserName}: Where-Object is a cmdlet that filters objects based on specified criteria. Here, {$_.UserName} is the criterion. The $_ symbol represents each object (process) in the pipeline, and .UserName accesses its UserName property. This filter allows us to select only those processes that have an associated username, essentially excluding system processes and those not linked to a user account.
  • Format-Table UserName -Unique: Finally, we format the output using Format-Table. This cmdlet arranges our data in a table format, focusing on the UserName property of the process objects. The -Unique parameter ensures that each username is listed only once, even if multiple processes are running under the same user account.

By running this command, we effectively get a table of unique usernames for users running processes on our system, providing a clear view of user activity in terms of process execution. It provides an indirect way to identify all active users based on process ownership.

Performance:

  • May take longer on systems with many processes but offers comprehensive user activity insights.

4. Using  query Command on Remote Server

We can use query user or qwinsta command on a remote machine directly. These commands display information about user sessions on a Terminal server or a Remote Desktop Session Host server.

Example:

query user /server:DESKTOPTHAT

USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME

john                  console            15  Active       2:26  03/05/2023 6:32 AM

mary                                     16  Disc         2:26  03/05/2023 2:01 PM

query session /server:DESKTOPTHAT

SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE

services                                    0  Disc

console           John                     15  Active

                   Mary                     16  Disc

Explanation:

  • query user displays a list of all users logged on, along with session details, idle time, and logon time on remote machine.
  • Don’t forget to replace the DESKTOP-THAT with your remote computer name. Here, the /server: was used to specify the remote computer/PC name.

Performance:

  • Effective for remote administration but dependent on network and remote system performance.

5. Invoke-Command with Win32_LogonSession and Win32_LoggedOnUser for Remote Server

To filter only the remote logged-on users and exclude local users using PowerShell, you’ll need to use a combination of WMI (Windows Management Instrumentation) queries and additional filtering to distinguish between local and remote sessions.

The Win32_LoggedOnUser class does not directly distinguish between local and remote logins. However, you can use the Win32_LogonSession class in conjunction with Win32_LoggedOnUser to determine the nature of the user sessions. Remote sessions typically have a LogonType value of 10 (RemoteInteractive) in Win32_LogonSession.

Here’s an example of how we might approach this:

  • Query Win32_LogonSession to find sessions with LogonType of 10.
  • Use the resulting session identifiers to query Win32_LoggedOnUser.
  • Correlate these to get the usernames of remote users.

This can be done with a script block in Invoke-Command:

Invoke-Command -ComputerName «RemoteServer» -ScriptBlock {

    $remoteSessions = Get-WmiObject -Class Win32_LogonSession | Where-Object { $_.LogonType -eq 10 }

    $remoteUserSessions = Get-WmiObject -Class Win32_LoggedOnUser

    foreach ($session in $remoteSessions) {

        $remoteUserSessions | Where-Object { $_.Antecedent -match «LogonSession=’$($session.LogonId)'» } | ForEach-Object {

            $_ | Select-Object -ExpandProperty Dependent

        }

    }

}

This script does the following:

  • Retrieves all logon sessions with LogonType 10 (remote interactive sessions).
  • Retrieves all logged-on user sessions.
  • Filters the logged-on user sessions to include only those that match the remote interactive session IDs.
  • Extracts and displays the user information associated with these remote sessions.

Please note that running this script requires appropriate administrative permissions on the remote machine and that PowerShell remoting is properly configured and enabled. Also, the output might need further formatting or processing, depending on your specific requirements.

6. Getting One Currently Logged-on User

In certain scenarios, we might need to identify just one user who is currently logged in, particularly in single-user environments such as personal workstations. PowerShell provides a simple method to fetch the username of the currently active user.

6.1 Using whoami Command

The whoami command is a quick way to find out the current user’s login name.

Example:

Output:

Explanation:

  • whoami simply returns the domain and username of the user currently logged on to the system.
  • This command is best used in environments where only one user is expected to be active at a time.

Performance:

  • The whoami command is extremely fast and efficient since it directly queries the current user context.

6.2 Using Get-WmiObject for Detailed Information

For more detailed information, including the domain and the username of the currently logged-on user, Get-WmiObject can be utilized.

Example:

GetWmiObject Class Win32_ComputerSystem | SelectObject UserName

Output:

UserName

domain\username

Explanation:

This command queries the Win32_ComputerSystem class and retrieves the UserName property, showing the domain and username.

  • Get-WmiObject: This is a PowerShell cmdlet that is used to retrieve Windows Management Instrumentation (WMI) information. WMI is a Windows feature that provides a standardized way to query and set system information and configurations.
  • -Class Win32_ComputerSystem: This part of the command specifies the WMI class from which to retrieve information. Win32_ComputerSystem is a WMI class that provides information about a computer system, like its manufacturer, model, and other system-level details.
  • | (Pipe): In PowerShell, the pipe character is used to pass the output of one command as input to another command. Here, it’s used to pass the output of Get-WmiObject to the Select-Object cmdlet.
  • Select-Object UserName, Name: This cmdlet is used to select specific properties from the objects passed to it. In this case, it’s selecting two properties: UserName and Name.
    • UserName refers to the account name of the user currently logged onto the Windows system.
    • Name refers to the name of the computer system.

So, when we run this command, it will fetch information about the computer system, specifically the username of the currently logged-in user and the name of the computer, and display it. This command is particularly useful in administrative scripts where we need to log or check which user is currently using a specific machine. It is useful for scripts where we need to programmatically access the current user’s details.

Performance:

  • Slightly slower than whoami but provides additional context, which can be beneficial in scripts.

6.3 Using Invoke-Command for Remote Execution

We can use Invoke-Command to execute a command on a remote machine. This cmdlet allows us to run scripts or commands on remote computers.

Example:

Invoke-Command -ComputerName «RemoteServer» -ScriptBlock { whoami }

or

InvokeCommand ComputerName «RemoteServer» ScriptBlock { GetWmiObject Class Win32_ComputerSystem | SelectObject UserName }

Output:

  • The first command will output the username of the currently logged-on user on RemoteServer.
  • The second command will provide detailed user information, including the domain and username.

Explanation:

  • The -ComputerName parameter specifies the remote computer.
  • The -ScriptBlock parameter contains the command to be executed on the remote system.
  • You must have appropriate permissions and the remote computer must be configured to allow PowerShell remoting.

Performance:

  • Performance may vary based on network conditions, remote system load, and configuration.
  • It’s an effective method for retrieving user information remotely but requires proper setup for PowerShell remoting.

6.4 Using Remote WMI Queries

Alternatively, we can use WMI directly for querying remote systems without using Invoke-Command.

Example:

Get-WmiObject -Class Win32_ComputerSystem -ComputerName «RemoteServer» | Select-Object UserName

Output:

UserName

domain\username

Explanation:

  • This command remotely queries the Win32_ComputerSystem class on RemoteServer.
  • It directly retrieves the UserName property, showing the currently logged-on user.

Performance:

  • Similar to Invoke-Command, but it may be more straightforward in environments where WMI is readily accessible and configured for remote queries.

7. Conclusion

Determining logged-on users in PowerShell can be achieved using various methods, each suited to specific needs. The query user command provides a quick overview, while Get-WmiObject and Get-Process offer more detail, especially useful for administrative scripts. For remote systems, Invoke-Command extends these capabilities across the network. Choosing the right method depends on the specific environment, the level of detail needed, and whether the query is local or remote. Each approach has its own performance considerations and should be selected based on the context of the task.

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

  1. Search for Command Prompt via Start and open it.
  2. In the Command Prompt window, enter the following command to query who is currently logged in.
    query user
  3. The user who is logged in will be shown under USERNAME along with other information such as logon time.
    Windows 11 Check Who is Logged in

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

Who am I logged in as Windows 11

Remotely

  1. Search for and open Command Prompt via Start menu.
  2. 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
  3. Command prompt will then shows details about the user who is currently logged into the remote computer.
    Check who is logged in Windows 11 remotely

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

WMIC command check users logged in

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

Command to check who is logged in Windows 11 remotely

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.

  1. Search for Registry Editor via Start and open it.
  2. Navigate to the following registry key.
    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server
  3. Next, double-click AllowRemoteRPC.
  4. In the Value data field, enter “1” and then click OK to save the changes.
  5. Close Registry Editor and restart the remote computer for the changes to take effect.

Allow Remote RPC Registry Windows 11

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.

How to see who is logged in Windows 11

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.

Start menu currently logged in user Windows 11

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows server release history
  • Gtx 980 windows 10 driver
  • Свободные антивирусы для windows
  • Joanna stingray walking through windows перевод
  • Windows 11 local account