Как узнать имя пользователя на удаленном компьютере?
25.03.2021
itpro
Active Directory, PowerShell, Windows 10, Windows Server 2016
комментариев 7
Довольно часто администратору нужно быстро узнать имя пользователя, который выполнил вход на удаленном компьютере Windows. В это статье мы рассмотрим несколько утилит и PowerShell скриптов, которые помогут вам узнать имена пользователей, залогиненых на удаленных компьютерах в сети.
Утилиты PSLoggedOn и Qwinsta
В комплекте утилит SysInternals PSTools от Microsoft есть консольная утилита PSLoggedOn.exe, которую можно использовать для получения имени пользователя, который вошел на удаленный компьютер, а также список подключенных к нему SMB сеансов.
Скачайте утилиту и запустите ее в формате:

Как вы видите, утилита вернула имя залогиненного пользователя (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. Чтобы получить список сессий с удаленного компьютера, выполнит команду:

Утилита возвращает список всех сессий (активных и отключенных по таймауту) на RDS сервере или десктопной редакции Windows 10 (даже если вы разрешили к ней множественные RDP подключения).
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 есть параметр –ComputerName, который можно использовать для получения доступа к WMI объектам на удаленном компьютере. Следующая команда вернет имя пользователя с удаленного компьютера:
(Get-WmiObject -class Win32_ComputerSystem –ComputerName wks215s1).Username

Данная команда показывает только пользователя, вошедшего на консоль (не через RDP).
Если нужно получить только имя пользователя на компьютере (без домена), воспользуетесь следующими командами:
$userinfo = Get-WmiObject -ComputerName ‘wks215s1’ -Class Win32_ComputerSystem
$user = $userinfo.UserName -split ‘\\’
$user[1]

Get-CimInstance –ComputerName wks215s1 –ClassName Win32_ComputerSystem | Select-Object UserName
(Get-CimInstance -ComputerName wks215s1 -ClassName Win32_ComputerSystem).CimInstanceProperties | where<$_.Name -like "UserName">| select value
![]()
GetCiminstance использует WinRM для подключения к удаленным компьютерам, поэтому на них нужно включить и настроить WinRM через GPO или командой:
PowerShell скрипт для проверки пользователей на удаленных компьютерах
Если вам нужно собрать информацию о пользователях сразу с нескольких компьютерах, можете использовать следующую PowerShell функцию получить имена пользователей.
На вход функции Get-LoggedUser нужно передать имена компьютеров, на которых нужно проверить имена пользователей:

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

Также обратите внимание, что вы можете хранить в свойствах компьютеров в 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
Предыдущая статья Следующая статья
Get Logged In Users Using Powershell
A while back I posted my initial script to find the users that are logged into a server and log them off remotely. That was several years ago and I thought I would take another crack at it to try to improve the speed, improve the formatting and add some dedicated switches with a bit more flexibility. Lastly, I wanted to change that ugly, unconventional name to something more Powershell approved. I call this new function Get Logged In Users.
Table Of Contents
The underlying structure is still going to be using query session so that hasn’t changed. What has changed is now we can specify a specific user or find where a user is logged on in a domain. Another note is the ability to log them off using a simple switch so that can definitely come in handy if you’re checking a log of systems.
Get Logged In Users Using Powershell
Looking back I don’t know why I added the ActiveDirectory Module and made it run as an administrator. That is simply not needed and not required to run this function. However, I would highly recommend you run this on a Windows 10 machine or Server 2016 and later with Powershell 5 because well let’s face it, we’re in 2020.
Parameters
-ComputerName
Description: This will specify the ComputerName that you would like to check. If no ComputerName is specified, it will check the local computer.
-UserName
Description: If the specified username is found logged into a machine, it will display it in the output.
How To Run Get Logged In User Powershell Script
In order to the run the script there are a couple of things you need to do. First and foremost, you need to set your execution policy to RemoteSigned or bypass. This is a standard with running any Powershell script.
Next you need to dot source the script since it is a function. To dot source the script do the following:
- Copy the script above and save it any location. In this example I’ll save it to my C:\_Scripts folder.
- Within the Powershell Window type: . .\_Scripts\Get-LoggedInUser.ps1 – Note the two dots before the backslash.
Get Logged On Users On Remote Computers
The best thing I love about this script is your ability to get who is logged into a remote computer. This mitigates the need to physically log into computer and checking that way. Since this Powershell script allows you to query remote servers and computers, it makes it highly automatable and very scalable. Using this script, you can check 1 server or 1,000 servers and it would be the same amount of effort for the person who is running it. It’s awesome and I love how you can do it all from your own Windows 10 computer.
You can also find where a user is logged on in a domain very easily. Depending on how many machines you’re going to be iterating through, it can obviously take some time but it can be done. Here is a simple code snippet of how to get where a user is logged in to.

Conclusion
So there you have it, a quick and easy solution to a problem that many IT Administrators have come across in their sysadmin journey. I am well aware that you can also do this via group policy if you wanted to go that route, or you can do this via some GUI tool but I always like to get my hands dirty with Powershell.
Thanks again for taking the time to visit and go ahead and drop a comment if you have any questions about the script or its intended fuctions. Also, don’t forget to check out our Youtube Channel for visual video content and our own personal Powershell gallery full of real world scripts.
Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)
I am searching for a simple command to see logged on users on server. I know this one :
but this will not provide me the info I need. It returns : domain Manufactureer Model Name (Machine name) PrimaryOwnerName TotalPhysicalMemory
I run Powershell 3.0 on a Windows 2012 server.
gives me not the exact answers I need. I would love to see as well the idle time, or if they are active or away.
10 Answers 10
In search of this same solution, I found what I needed under a different question in stackoverflow: Powershell-log-off-remote-session. The below one line will return a list of logged on users.
![]()
Since we’re in the PowerShell area, it’s extra useful if we can return a proper PowerShell object .
I personally like this method of parsing, for the terseness:
Note: this doesn’t account for disconnected ("disc") users, but works well if you just want to get a quick list of users and don’t care about the rest of the information. I just wanted a list and didn’t care if they were currently disconnected.
If you do care about the rest of the data it’s just a little more complex:
Выводим список пользователей на удаленном компьютере
Иногда требуется выяснить, кто из пользователей в данный момент работает на удаленном компьютере. Это очень просто сделать с помощью PowerShell и WMI.
При входе в систему пользователя запускается экземпляр процесса explorer.exe, поэтому узнав, кто является владельцем этого процесса мы выясним и то, кто в данный момент находится в системе. Для этого создаем скрипт следующего содержания:
$ComputerName = Read-Host ″Enter remote computer name″
$credential = Get-Credential
Get-WMIObject Win32_Process -filter ‘name=″explorer.exe″’ -computername $computername -Credential $credential |
ForEach-Object <
$owner = $_.GetOwner()
‘<0>\<1>’ -f $owner.Domain, $owner.User > |
Sort-Object |
Get-Unique |
ForEach-Object <
$rv = 1 | Select-Object ComputerName, User
$rv.ComputerName = $computername
$rv.User = $_
$rv
>
Запускаем скрипт, указываем имя компьютера, учетные данные для подключения и получаем список пользователей, залогинившихся на этом компьютере.