Windows logout from cmd

Windows : logoff from command line

We can logoff a user session by clicking on the Logoff button in the start menu. We can logoff from command prompt(CMD) too using shutdown command. You need to run the below command.

Shutdown is a Windows in-built command. We don’t have to install it separately. Note that we can run this command from windows Run window also. This command works on all windows editions. (XP, Vista, Server 2k3/2k8, Windows 7)

There’s another command Logoff which also serves the same purpose. This command can be used to logoff sessions on the remote computers also. Find syntax below for this.

To logoff on the current system

This does not accept user name and passwords so it uses the credentials of the current logged in user on the host system.

How to force logoff without waiting for user confirmation to terminate the running applications?

The above commands do forced logoffs.В They kill all the applications one by one and at the end logs off the user.

If I want to login from command line, how do I set it up?

Open Task manager, click on Users, Right Click, manage user account, it will open control panel. It the path above, open cmd from here. shutdown -l to log out.
Login again. It works.

need to logoff but cannot

i need to log out from anther user with the user name
sameing like that…
logoff username:moss /server:172.19.19.50

logoff logoff

Область применения: Windows Server (половина ежегодного канала), Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012 Applies to: Windows Server (Semi-Annual Channel), Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012

Выполнит выход пользователя из сеанса на удаленный рабочий стол сервере узла сеансов и удалит сеанс. Logs off a user from a session on a Remote Desktop Session Host server and deletes the session.

Синтаксис Syntax

Параметры Parameters

Параметр Parameter Описание Description
Указывает имя сеанса. Specifies the name of the session. Это должен быть активный сеанс. This must be an active session.
Указывает числовой идентификатор, определяющий сеанс на сервере. Specifies the numeric ID which identifies the session to the server.
/server: /server: Указывает сервер узла сеансов удаленный рабочий стол, содержащий сеанс, для которого пользователь должен выйти из системы. Specifies the Remote Desktop Session Host server that contains the session whose user you want to log off. Если не указано, используется сервер, на котором активна в данный момент. If unspecified, the server on which you are currently active is used.
/v /v Отображает сведения о выполняемых действиях. Displays information about the actions being performed.
/? /? Отображение справки в командной строке. Displays help at the command prompt.

Комментарии Remarks

Вы всегда можете выйти из сеанса, к которому в данный момент выполнен вход. You can always log off yourself from the session to which you are currently logged on. Однако необходимо иметь разрешение « полный доступ» для выхода пользователей из других сеансов. You must, however, have Full Control permission to log off users from other sessions.

Выход пользователя из сеанса без предупреждения может привести к утрате данных в сеансе пользователя. Logging off a user from a session without warning can result in loss of data at the user’s session. Необходимо отправить пользователю сообщение с помощью команды MSG , чтобы предупредить пользователя перед выполнением этого действия. You should send a message to the user by using the msg command to warn the user before taking this action.

Если параметр или не указан, функция выхода из системы выполняет выход пользователя из текущего сеанса. If or isn’t specified, logoff logs the user off from the current session.

После выхода пользователя из системы все процессы завершаются, а сеанс удаляется с сервера. After you log off a user, all processes end and the session is deleted from the server.

Пользователь не может выйти из сеанса консоли. You can’t log off a user from the console session.

Примеры Examples

Для выхода пользователя из текущего сеанса введите: To log off a user from the current session, type:

Для выхода пользователя из сеанса с помощью идентификатора сеанса, например сеанса 12, введите: To log off a user from a session by using the session’s ID, for example session 12, type:

Для выхода пользователя из сеанса с использованием имени сеанса и сервера, например Session TERM04 на сервере Server1, введите: To log off a user from a session by using the name of the session and server, for example session TERM04 on Server1, type:

How to log off on windows 10 by using cmd?

What is the cmd-command for log off and shut down computer?

Would appreciate any help.

***Post moved by the moderator to the appropriate forum category.***

Replies (2) 

There are a lot of command line in CMD you can use to logoff a computer. When you type the command «shutdown /» in CMD, it will show you the list of command controls you can use with it as for your options. With what you have stated, «shutdown /l» with the letter «L» meaning logoff, would be the most appropriate.

Let us know if this answers your question.

25 people found this reply helpful

Was this reply helpful?

Sorry this didn’t help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

We have noticed that the post has been inactive for quite some time. We’d like to check if Nick Dich was able to answer your question.

If so, we highly encourage you to inform our Community by clicking on Yes or marking the post as an answer. This will help other members who may have the same issue as you. Otherwise, don’t hesitate to update us so we can further assist you.

13 people found this reply helpful

Was this reply helpful?

Sorry this didn’t help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

Log Off Another User in Windows 10

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.

To Log Off Another User in Windows 10,

  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.

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.
  4. Now, execute the command logoff . For example, logoff 1 .

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 .

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.

Related blog posts:

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

Share this post

About Sergey Tkachenko

Sergey Tkachenko is a software developer from Russia who started Winaero back in 2011. On this blog, Sergey is writing about everything connected to Microsoft, Windows and popular software. Follow him on Telegram, Twitter, and YouTube.

1 thought on “ Log Off Another User in Windows 10 ”

To note, the logoff command is not available on Windows 10 Home editions.

Выполнить LOGOFF для всех пользователей, кроме себя

Всем привет! Решил попросить помощи экспертов, так как не могу находить ответ на мой вопрос нигде.

Выполнить «Выход из Системы» другим учетным записям а свою учетку не трогать. Вот например на данном скриншоте:

Как вы видите здесь 2 аналогические учетки под именем «test1». Одна активная ( моя ), другая неактивная. Возможно ли программно выполнить Log Off всех аналогических учетках кроме своей активной? Помогите пожалуйста разобраться

Disconnect / Logoff отключенных ЛОКАЛЬНЫХ пользователей из ПК
Добрый день коллеги, знатоки. в силу определенных сложностей и процессов, появилась задача, которую.

Число совершенно,если она равна сумме всех своих делителей кроме самого себя
Число совершенно,если она равна сумме всех своих делителей кроме самого себя. Пример :6=1+2+3.

Как вывести всех пользователей, привязанных к роли, кроме текущего (того, кто тоже в этой роли)?
Есть роль User (identity).Текущий пользователь заходит в приложение и видит список всех.

Logoff пользователей на «терминалке» с исключением по текстовому файлу
Добрый день, прошу помочь со скриптом на PowerShell нужно сделать «logoff» пользователей на.

Slackerok, Вам лучше знать.
Значит делаю для всех ID, у которых нет надписи «Активно».

По логу видно что logoff !ID! не выполняет свою функцию. Опять переходит в начало цикла и пытается отключить уже проверенного пользователя. И так до бесконечности.
Пауза после операции logoff не выполняется.

Если то
echo logoff !ID! выводит logoff 5
echo logoff «!ID!» выводит logoff «5»
Причем если пользователь с кодом 5 есть, то команда logoff 5 работает корректно.

Классный скрипт!
А можно сделать так, чтобы пассивные сессии закрывались не в момент выполнения скрипта, а по прошествии определённого времени (например, двух часов)?
То есть, перейдя из статуса Active в Disconnected, начинался бы отсчёт времени, а по пришествии двух часов (если конечно пользователь не вернулся в систему) его сессия автоматически отключается…

Добавлено через 15 минут
В дополнение:
На одном сайте я нашёл такую утилиту idlelogoff, но к сожалению у неё есть один серьёзный недостаток – она закрывает не только сессии со статусом Disconnected (по прошествии заданного времени) но и активную сессию, если в ней не было сделано за это время какое-либо действие.

Всем привет, автору респект.)

Отвечаю на крайний поставленный вопрос, тем более, что у меня так же возникла подобная необходимость.
Задача у меня была схожая.
1. Выявить не активных пользователей на терминальном сервере
2. Если через пол часа пользовательская сессия продолжает быть не активной — logoff

Для данных целей были созданы 2 скрипта на основе скрипта автора.
1-й выявляет не активных пользователей и записывает их во временный файл + создает задачу в шедуллере
с запуском 2-го скрипта со временем исполнения через 30 минут от текущего.
2-й скрипт открывает временный файл со списком пользователей к разлогиниванию (если онный существует)
и проверяет их по списку — если пользователь продолжает быть не активным — logoff.

Первый скрипт загнал так же в шедулер с выполнением каждые 5 минут.
В первом скрипте необходимо поменять переменные admin и pass на свои.

Что то я накосячил со своими скриптами. Они конечно работают, но логика не правильная.
Получается что если пользователь не активен и 1-й скрипт его пометил как «не активного» и после этого в течении полу часа, скажем через 20 минут он заходил снова на терминалку и вышел, то 2-й скрипт все равно его терминирует.

Наверно нужно, чтобы в случае, если пользователь снова заходил на терминал в течении определенного времени, то он бы удалялся из списка на logoff и/или время разлогинивания добавлялось относительно последнего входа.

Думаю надо сделать так.
1. Скрипт формирует временный файл с не активными пользователями следующего формата:
«имя пользователя» «ID» «время logoff» (где время logoff — текущее+время через которое он должен быть разлогинен. В моем случае — 30 минут).

2. Второй скрипт, или тот же, проверяет временный файл (если он существует) и проверяет:
— если пользователь активен в текущей сессии, но он присутствует в файле на logoff — удаляет его из файла.

3. Второй скрипт, или то же, открывает файл со списком пользователей на logoff и
— если время на logoff (третья колонка в файле) совпадает с текущим — logoff пользователя.

Данный скрипт должен запускаться через шедуллер каждую минуту.
Как то так. Есть мысли у кого?

Читайте также:  Глобальная переменная окружения windows
Оцените статью