Как завершить сессию пользователя windows

Несколько раз встречался с ситуацией, когда один из пользователей Windows Server с ролью RDS (Remote Desktop Services) запустил приложение, которое утекло и заняло всю доступную RAM. Удаленно подключиться к такому хосту по RDP невозможно. Чтобы завершить утекший процесс, нужно выполнить удаленный логофф пользователя. Для этого можно использовать встроенную команду logoff.

Синтаксис команды logoff.exe:

logoff /server:<servername> <session ID> /v

Команда logoff принимает ID сессии пользователя, которую нужно завершить. Чтобы вывести список активных сеансов пользователей на удаленном компьютере, выполните команду:

quser /server:RemoteComputerName

USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
admin console 1 Active none 1/25/2023 1:23 PM

quser - список активных сессий на удаленном компьютере Windows или RDS

В данном случае на компьютере выполнен локальный вход (console) под пользователем admin. ID этой сессии равно 1.

Можно получить ID сессии определенного пользователя:

quser /server:RemoteComputerName sidorov

Совет. Если пользователь подключен через Remote Desktop, в поле SESSIONNAME будет указано rdp-tcp#X.

Вы можете удаленно завершить сеанс пользователя по его ID сессии. Выполните команду:

logoff 1 /SERVER:RemoteComputerName /v

Logging off session ID 1

При завершении сеанса пользователя, будут завершены все его запущенные процессы.

Проверьте, что на удаленном компьютере не осталось активных сессий:

quser /server:RemoteComputerName

No User exists for *

Можно использовать небольшой скрипт, чтобы завершить все сеансы пользователей на нескольких терминальных серверах:

@echo off
setlocal
set servers=MSKRDS1 MSKRDS2
for %%s in (%servers%) do (
qwinsta /server:%%s | for /f "tokens=3" %%i in ('findstr /I "%username%"') do logoff /server:%%s %%i /v
)

Также для удаленного завершения сессий пользователей можно использовать встроенную утилиту rwinsta:

rwinsta rdp-tcp#12 /server:MSKRDS2

или

rwinsta 22 /server:MSKRDS2

rwinsta - сбросить удаленную сессию пользователя

Managing user sessions in a Windows environment is a critical task for system administrators. There are times when you need to terminate a user session, whether for maintenance, troubleshooting, or security reasons. The Windows Command Line provides powerful tools for managing user sessions efficiently. This article will explore how to kill a user session Windows Command Line, ensuring you can maintain control over your network and systems effectively.

Understanding User Sessions in Windows

A user session in Windows is an instance where a user logs into the system and interacts with it. These sessions are tracked and managed by the system, and administrators often need to monitor and control them. Scenarios where you might need to terminate a user session include:

  • Maintenance and Updates: Performing system maintenance or updates that require users to log off.
  • Troubleshooting: Addressing issues where a user’s session may be causing system problems.
  • Security: Terminating sessions that pose a security threat.

Tools for Managing User Sessions

Windows provides several command-line tools to manage user sessions:

  • Task Manager: Provides a graphical interface but can be accessed through the command line.
  • Command Line Tools: query, logoff, and tsadmin are powerful commands for session management.

Using Command Line Tools to Kill User Sessions

1. Query User Command
The query user command allows you to list all user sessions on a local or remote system. This is the first step in identifying the session you want to terminate.

Syntax:

CSS   Copy code
query user [username] [/server:servername]

Example:

graphql   Copy code
query user

This command lists all active user sessions on the local machine, displaying details like session name, user name, ID, and session state.

2. Logoff Command
The logoff command is used to terminate a user session. After identifying the session ID from the query user command, you can use logoff to end the session.

Syntax:

CSS   Copy code
logoff [sessionID] [/server:servername]

Example:

Copy code
logoff 2

This command logs off the session with ID 2 on the local machine. If you need to log off a user on a remote server, you would specify the server name.

3. Taskkill Command
The taskkill command is another powerful tool that can be used to terminate user processes and sessions.

Syntax:

CSS   Copy code
taskkill /ID [pid] /F

Example:

r   Copy code
taskkill /ID 1234 /F

This command forcibly terminates the process with process ID (PID) 1234. To use taskkill for a user session, you need to identify the PID of the user’s processes.

Also read: What Command Launches the Remote Desktop (RDP) Client for Windows?

Step 1: Open Command Prompt
Click Win + R, type cmd, & press Enter to open the Command Prompt.

Step 2: Query User Sessions
Use the query user command to list all user sessions.

graphql   Copy code
query user

Note the session ID of the user session you want to terminate.

Step 3: Logoff User Session
Use the logoff command with the session ID obtained from the previous step.

css   Copy code
logoff [sessionID]

For example:

Copy code
logoff 2

Step 4: Verify Termination
Use the query user command again to verify that the session has been terminated.

graphql   Copy code
query user

Managing Remote Sessions

Query Remote User Sessions
To query user sessions on a remote server, use the query user command with the /server parameter.

bash   Copy code
query user /server:servername

Logoff Remote User Sessions
Similarly, use the logoff command with the /server parameter to log off a user session on a remote server.

bash   Copy code
logoff [sessionID] /server:servername

Example

  1. Query Remote Sessions:
    bash   Copy code
    query user /server:remote_server_name
  2. Logoff Remote Session:
    bash   Copy code
    logoff 3 /server:remote_server_name

Advanced Management with PowerShell

PowerShell offers advanced capabilities for managing user sessions, including more complex scripts and automation.

Example PowerShell Script to Logoff User

powershell   Copy code
$session = (query user /server:remote_server_name | Where-Object { $_ -match 'username' }) -split ' +'
logoff $session[2] /server:remote_server_name

This script identifies the session ID for the specified username on a remote server and logs off the session.

Best Practices for Managing User Sessions

  1. Communication: Always communicate with users before terminating their sessions to avoid data loss and disruption.
  2. Documentation: Keep records of session terminations for auditing and troubleshooting purposes.
  3. Scheduled Maintenance: Schedule regular maintenance windows to minimize the impact on users.

Conclusion

Effectively kill user sessions Windows command line is crucial for maintaining system performance, security, and stability. By leveraging command-line tools like query user, logoff, and task kill, administrators can efficiently terminate user sessions as needed. Whether working on local or remote systems, these commands provide the flexibility and control required for comprehensive session management. Remember to follow best practices and communicate with users to ensure a smooth and efficient process.

Как завершить сессию пользователя на его рабочем месте? Домен , winserv 2019 , windows 10 рабочие места. На сервере можно сменить пароль, отключить учетку, задать время доступа, но нет Выйти на устройстве, Завершить все сеансы. Как это сделать удаленно?


  • Вопрос задан

  • 3920 просмотров

query session /server:имя_хоста > session.txt
for /f "skip=2 tokens=3," %%i in (session.txt) DO logoff %%i /server:имя_хоста
del session.txt

Вот что получилось в итоге:
узнать номер id
C:\Windows\system32>query session /server:TIM-EN-W10

СЕАНС ПОЛЬЗОВАТЕЛЬ ID СТАТУС ТИП УСТР-ВО
services 0 Диск
console aivanov 2 Активно

==================Завершить сеанс

C:\Windows\system32>logoff 2 /server:TIM-EN-W10

logoff происходит с закрытием всех программ, т.е не блокировка, не смена пользователя а прям ВЫХОД

Пригласить эксперта

enter-pssession и
quser\qwinsta
rwinsta

Войдите, чтобы написать ответ


  • Показать ещё
    Загружается…

Минуточку внимания

Skip to content

How to Log Off Another User in Windows 10

Although the concept of multiple users sharing one device or one PC is getting rarer by the day, there are still cases when you have to share PCs and switch users fast. Sometimes you need to end a session for another user signed in to your computer. Here are a number of methods you can use.

The situation can be different when you need to end a user session. For example, someone just forgot to sign out from his or her user account, and left running apps and opened docs, so the remain in your computer’s memory and consume its system resources. In this case, it could be useful to kick out the inactive session for the other user.

There are no third party tools required. This can be done using either Task Manager, Command Prompt or PowerShell.

  1. Open the Task Manager app.
  2. If it looks as follows, switch it to the full view using the «More details» link in the bottom right corner.
  3. Click on the Users tab.
  4. Right-click on a user account you want to log off.
  5. Select Sign off from the context menu.
    Windows 10 Logoff Another User

You are done.

Alternatively, there are a couple of console tools we can use for the same purpose. Let’s review them.

Log Off Another User from the Command Prompt

  1. Open an elevated command prompt.
  2. Type or copy-paste the following command:query session. This will list available user sessions.
  3. Note the ID column value for the user you want to sign off.
    Windows 10 Logoff Another User With Cmd

  4. Now, execute the command logoff <ID>. For example, logoff 1.

You are done.

Finally, you can use PowerShell, as follows.

Log Off Another User from with PowerShell

  1. Open PowerShell as Administrator.Tip: You can add «Open PowerShell As Administrator» context menu.
  2. Type or copy-paste the following command:$sessionID = ((quser /server:'you computer name' | Where-Object { $_ -match 'user name to sign off' }) -split ' +')[2]
  3. Now, execute the command logoff $sessionID.
    Windows 10 Logoff Another User PowerShell

The PowerShell method is great when you know the exact user name. You can save it as a script and sign out other users with one click when needed.

That’s it.

Related blog posts:

  • Find the Sign Out Log in Windows 10
  • All ways to sign out from Windows 10

Support us

Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:

If you like this article, please share it using the buttons below. It won’t take a lot from you, but it will help us grow. Thanks for your support!



October 14, 2019 updated by

Leave a reply »

How do I sign out other user accounts without restarting the computer? When someone forgets to log out of a public or shared PC, their account still consumes RAM in the background. To free up the resources being used by other logged-in accounts, you can log them off using Task Manager, Command Prompt and PowerShell.

Method 1: Log Off Another User Using Task Manager

Press the Ctrl + Shift + Esc keyboard shortcut to launch Task Manager. Go to the Users tab, it will list all users that are currently signed in to your system. Right-click on the user you want to log off and select the Sign off option.

You will get a warning that says the user’s unsaved data might be lost. Click on Sign out user when you need to proceed.

Method 2: Log Off Another User Using Command Prompt

Open the Command Prompt with administrative rights, run the query session command to see all users currently logged into the computer. Take note of the session ID of the user you want to sign out.

Next, run the following command to log off your desired account by specifying the session ID.
logoff ID

This method doesn’t give you any alert or confirmation that the user you’re signing out will lose unsaved work.

Method 3: Log Off Another User Using PowerShell

Open Windows PowerShell with administrative rights, and type the following commands. Replace “Server01” with your computer’s name and substitute “pcunlocker” with the name of the account you want to log out.
$server = 'Server01'
$username = 'pcunlocker'
$sessionId = ((quser /server:$server | Where-Object { $_ -match $userName }) -split ' +')[2]
logoff $sessionId /server:$server

Once logged off, the user account is no longer listed in Task Manager. Signing a user out this way has the same risk of losing all unsaved data as the above method.

  • Previous Post: Fix: Windows 10 Keeps Going to Sleep After 2 Minutes
  • Next Post: 3 Methods to Check Your Motherboard Model in Windows 10

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Настройка terminal windows server 2019
  • Эмулятор windows 2000 на андроид
  • Как убрать ошибку 0x8007007b на windows 10
  • Kyocera 2035dn драйвер windows 10
  • Драйвер для принтера samsung ml 1710p для windows 10