Несколько раз встречался с ситуацией, когда один из пользователей 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
В данном случае на компьютере выполнен локальный вход (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
Как завершить сессию пользователя на его рабочем месте? Домен , winserv 2019 , windows 10 рабочие места. На сервере можно сменить пароль, отключить учетку, задать время доступа, но нет Выйти на устройстве, Завершить все сеансы. Как это сделать удаленно?
-
Вопрос задан
-
3866 просмотров
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
Войдите, чтобы написать ответ
-
Показать ещё
Загружается…
Минуточку внимания
A Windows administrator can use the logoff command to log off a user session remotely from any Windows computer in the network. In this article, we’ll show how to get a list of sessions on a remote computer using the quser command and end the user session with logoff.
Using Command Prompt to Remotely Logoff Users
Before killing a user’s session in Windows, you need to get the user’s session ID. You can list sessions on the remote computer using the built-in quser console tool. Open a command prompt as an administrator and run the command:
quser /server:server_name
Note. To connect to a remote computer server_name, your account must be a member of the local Administrator group.
The quser command will list all sessions on the remote host, including the console session (SESSIONNAME=Console) and RDP user sessions (SESSIONNAME=rdp-tcp#X).
Note. You can also use the qwinsta command to get a list of user sessions on a remote computer:
qwinsta /server:server_name
Find the user in the list whose session you want to end. For example, we want to logoff the administrator session with the ID = 2.
To end a user session remotely, use the following command:
Logoff sessionID /server:ComputerName
In our example, this is:
Logoff 2 /server:server_name
Check that the user session has ended:
quser /server:server_name
If you want to log off a specific user by username, use the following PowerShell script:
$server = 'dc02' $username = 'administrator' $session = ((quser /server:$server | ? { $_ -match $username }) -split ' +')[2] logoff $session /server:$server
Possible errors when executing the logoff command:
- Could not logoff session ID 2, Error code 5
Error [5]:Access is denied.
This means that you don’t have permissions on this session or you are using a non elevated command prompt. - Error 0x00000005 enumerating sessionnames
Error [5]:Access is denied.
You are running the logoff command under a local user with administrator privileges. For such users, the Remote UAC policy is enabled by default. To disable UAC remote restrictions for local users, create the LocalAccountTokenFilterPolicy registry parameter on the target host with a value of 1.reg add "\\server_name\HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
- Error 0x000006BA enumerating sessionnames
Error [1722]: The RPC server is unavailable.
Enable RemoteRPC on the remote machine server_name:reg add "\\server_name\HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v AllowRemoteRPC /t Reg_Dword /d 0x1 /f
Logoff Remote Desktop Services Users Using PowerShell
You can use the command prompt to remotely log off user sessions on Windows Server hosts with Remote Desktop Services (RDS) deployed. An RDS server can have multiple user sessions active at the same time.
If you plan to put the RDShost into maintenance mode or install updates, you need to logoff all user sessions remotely. To do this, you first need to put the RDS host in the Drain mode (in this mode, the RDS host blocks new RD connections):
Invoke-Command -ComputerName NYRDS1 ScriptBlock{ change logon /drain }
Now you can end all sessions remotely using a PowerShell script:
$Server='rds01' try { query user /server:$Server 2>&1 | select -skip 1 | % {logoff ($_ -split "\s+")[-6] /server:$Server /V} } catch {}
Or, you can only logoff RDS user sessions in a disconnected state:
$Server='rds01' try { query user /server:$Server 2>&1 | select -skip 1 | ? {($_ -split "\s+")[-5] -eq 'Disc'} | % {logoff ($_ -split "\s+")[-6] /server:$Server /V} } catch {}
Cyril Kardashevsky
I enjoy technology and developing websites. Since 2012 I’m running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.
Для того, чтобы выключить, перезагрузить компьютер или завершить сеанс пользователя, в PowerShell можно воспользоваться методами WMI-класса Win32_OperatingSystem.
Для начала выведем список методов класса:
Get-WmiObject Win32_OperatingSystem | Get-Member -MemberType Method
Если вам надо просто перезагрузить или выключить компьютер, то подойдут методы Reboot и Shutdown соответственно. К примеру, для перезагрузки надо выполнить такую команду:
(Get-WmiObject Win32_OperatingSystem -EnableAllPrivileges).Shutdown()
Обратите внимание на ключ EnableAllPrivileges. Повышение привилегий необходимо для данной операции, без него команда завершится с ошибкой.
Следующий метод Win32Shutdown в качестве аргумента принимает параметр (Flags), с помощью которого можно выбрать необходимое действие. Параметр представляет из себя битовую маску и может принимать следующие значения:
Log Off (0) — выход из системы. Останавливает все процессы, связанные с контекстом безопасности текущего пользователя, завершает его сеанс и отображает диалоговое окно входа в систему.
Forced Log Off (4) — принудительный выход из системы. Выход производится незамедлительно, не дожидаясь завершения процессов пользователя. Это может привести к некорректному завершению работы программ и потере данных.
Shutdown (1) — завершение работы. Завершает работу системы и выключает питание компьютера. При этом все запущенные процессы останавливаются, а содержимое памяти сохраняется на диск. Во время завершения работы система обращается к каждому запущенному приложению и ждет от него подтверждения того, что его можно безопасно завершить.
Forced Shutdown (5) — принудительное завершение работы. Завершает работу системы и выключает питание компьютера. При принудительном завершении работы все запущенные программы и службы, включая WMI, отключаются незамедлительно. Из-за этого может произойти потеря данных, а при запуске на удаленном компьютере вы не сможете увидеть результат выполнения команды.
Reboot (2) — перезагрузка. Завершение работы и перезагрузка компьютера.
Forced Reboot (6) — принудительная перезагрузка. При использовании метода принудительной перезагрузки все запущенные программы и службы незамедлительно завершаются, из за чего может произойти потеря данных.
Power Off (8) — выключение. Завершение работы системы и выключение питания компьютера (если это поддерживается).
Forced Power Off (12) — принудительное выключение. Завершение работы системы и выключение питания компьютера. При принудительном выключении все запущенные программы и службы незамедлительно завершаются, из за чего может произойти потеря данных.
К примеру команда для завершения сеанса пользователя (logoff) будет выглядеть так:
(Get-WmiObject Win32_OperatingSystem -EnableAllPrivileges).Win32Shutdown(0)
Ну и самый продвинутый метод Win32ShutdownTracker, который имеет четыре параметра — задержку (Timeout), комментарий (Comment), код причины (ReasonCode) и действие (Flags). Действия указываются аналогично предыдущему методу. Коды причины можно посмотреть здесь, хотя если особой необходимости в них нет, можно просто поставить 0. Для примера принудительно завершим работу системы, укажем таймаут 60 секунд и добавим комментарий:
(Get-WmiObject Win32_OperatingSystem -EnableAllPrivileges).Win32ShutdownTracker(60,"Force shutdown",0,5)
Примечание. Для операций LogOff, независимо от указанной задержки выход из системы происходит незамедлительно. Добавить комментарий также невозможно.
Several commands are available in Windows that allow you to shutdown or restart a local or remote computer. In this article, we’ll look at how to use the shutdown command and the PowerShell cmdlets Restart-Computer and Stop-Computer to shutdown/restart Windows.
Contents:
- Using the Shutdown Command on Windows
- How to Shutdown or Restart a Remote Windows Computer?
- Restart or Shutdown Windows with PowerShell
Using the Shutdown Command on Windows
The Shutdown.exe is a built-in Windows command line tool that allows you to reboot, shutdown, put your computer to sleep, hibernate, or end a user session. In this guide, we’ll show the basic examples of using the shutdown command in Windows. All commands discussed above are run in the Run dialog box — Win+R
->, in the command prompt (cmd.exe) or PowerShell.
The shutdown command has the following syntax: shutdown [/i | /l | /s | /r | /g | /a | /p | /h | /e | /o] [/hybrid] [/soft] [/fw] [/f] [/m \\computer][/t xxx][/d [p|u:]xx:yy [/c "comment"]]
As you can see, the command has quite a lot of options and can be used to shutdown/restart a local or remote computer.
How to shutdown windows from the command prompt
To shutdown Windows, use the shutdown command with the /s key.
shutdown /s
Reboot Windows from the CMD
To reboot your computer, use the /r parameter. After running it, Windows will be gracefully restarted.
shutdown /r
End a User Session
To end the current user session (logoff), run this command
shutdown /l
This command works in the same way as logoff.exe command.
How to hibernate Windows using the shutdown command?
To hibernate your computer, run this command:
shutdown /h
In the hibernate mode, all the contents of memory are written to the hiberfil.sys file on the local disk and the computer goes into sleep mode with reduced power consumption.
Notify logged-in users of an impending reboot or shutdown
You can notify all logged-on Windows users about the upcoming shutdown/reboot of the computer or server by sending a pop-up message to all active sessions. As a rule, this feature is used on RDS servers with several users working on them at the same time in their RDP sessions.
shutdown /r /c “This server will be restarted in 60 seconds.”
Delayed shutdown/reboot of a computer using the timer
You can shutdown or restart the computer with a certain delay (on a timer). Using the /t option, you can specify the time span after which the computer/server will be shutdown or rebooted. Thus you can provide your users some time to save open files and close the apps correctly. It is convenient to use this option together with the notification message. In this example, we inform the users that Windows will be shutdown in 10 minutes (600 seconds).
shutdown /s /t 600 /c "The server will be shutdown in 10 minutes. Save your work!"
A user will be warned about the scheduled shutdown:
You’re about to be signed out
If the delay is too long (for example, 60 minutes/3,600 seconds), a pop-up window appears in the lower right corner of the screen:
You’re about to be signed out. Your Windows will shutdown in 100 minutes.
How to stop/cancel/abort system shutdown in Windows
Windows waits 60 seconds by default without doing anything after running shutdown or reboot command. An administrator can cancel the restart or shutdown of the device by running this command during this time:
shutdown /a
After you cancel the shutdown, you’ll see the following pop-up message in the lower right corner of the screen:
Logoff is cancelled. The scheduled shutdown has been cancelled.
Restart Windows immediately
To shutdown or reboot a computer immediately without waiting for 60 seconds, specify 0 as a value of the /t parameter. For example:
shutdown /r /t 0
The /f key is very important. I use it almost always when shutting down or restarting Windows Server hosts. This attribute allows to force close all running programs and processes without waiting for confirmation from the user (we won’t wait till the users confirm closing all applications on the RDS server since we can never get it).
The next command will restart the computer and automatically run all registered apps after reboot (apps registered in the system using RegisterApplicationRestart API are meant here).
shutdown /g
Create a restart shortcut on Windows Desktop
To make it more convenient for users, you can create a desktop shortcut to restart or shutdown a computer with the required parameters. Such a shortcut may be useful when you need to restart the computer from the RDP session when there are no options to restart or shutdown the computer in the Start menu.
How to restart Windows at a specific time (on schedule)?
If you want your computer or server to restart/shutdown at a specific time, you can add the shutdown command with the parameters to Windows Task Scheduler (taskschd.msc
).
For example, this Scheduler task will restart the computer daily at 12 AM.
Or you can create a new Scheduler task with PowerShell:
$Trigger= New-ScheduledTaskTrigger -At 00:00am -Daily
$User= "NT AUTHORITY\SYSTEM"
$Action= New-ScheduledTaskAction -Execute "shutdown.exe" -Argument "–f –r –t 120"
Register-ScheduledTask -TaskName "RebootEvertyNight_PS" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force
How to Shutdown or Restart a Remote Windows Computer?
You can use the shutdown.exe command to reboot a remote computer. To do this, the remote computer must be accessible over the network, and the account u you are using must be a member of the local Administrators group on the remote computer (server):
shutdown /r /t 120 /m \\192.168.1.210
If all the conditions described above are met, but when running the shutdown command the error “Access denied (5)” appears, you need to allow remote access to the administrative shares (C$, ADMIN$) on the remote computer by changing the value of LocalAccountTokenFilterPolicy parameter to 1.
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v "LocalAccountTokenFilterPolicy" /t REG_DWORD /d 1 /f
If you need to provide user credentials to connect to a remote computer, you can use the commands:
net use \\192.168.13.111 /u:corp\username
shutdown /s /t 60 /f /m \\192.168.13.111
If you need to restart multiple computers remotely, you can save the list of computers to a text file, and start a remote reboot of all computers using a simple PowerShell script:
$sh_msg = "Your computer will be automatically restarted in 10 minutes. Save your files and close running apps"
$sh_delay = 600 # seconds
$computers = gc C:\PS\PC-list.txt
foreach ($comp in $computers)
{
& 'C:\Windows\System32\SHUTDOWN.exe' "-m \\$comp -r -c $sh_msg -t $sh_delay"
}
Restart multiple computers with a Shutdowm.exe GUI
For those who don’t feel comfortable working in the command prompt, there is a graphical interface for the shutdown.exe command. To call the Remote Shutdown Dialog GUI, use the command:
shutdown /i
As you can see, you can add multiple computers in the remote shutdown dialog to be rebooted/shutdown, specify the notification text, and specify the reason for the shutdown to be saved in the Windows event log.
Restart or Shutdown Windows with PowerShell
The following two commands are available in Windows PowerShell to shutdown and reboot the computer: Restart-Computer and Stop-Computer. Both commands allow you to shutdown or restart a local or remote computer (over the network).
To restart Windows, run:
Restart-Computer -force
To shutdown your computer:
Stop-Computer
By default, the reboot will start in 5 seconds. You can increase the delay before reboot:
Restart-Computer –Delay 60
Both cmdlets have a -ComputerName
parameter that allows you to specify a list of remote computers to perform the action on.
For example, to shutdown two Windows servers remotely:
Stop-Computer -ComputerName "mun-srv01", "mun-srv02"
You can specify administrator credentials to connect to a remote host:
$Creds = Get-Credential
Restart-Computer -ComputerName mun-srv01-Credential $Creds
WMI and DCOM are used to connect to remote computers (they must be enabled and configured). If WMI is not configured, the following error will appear when running the command:
Restart-Computer : Failed to restart the computer wks-11222 with the following error message: Access is denied. Exception from HRESULT: 0x80070005 (E_ACCESSDENIED).
If WinRM (Windows Remote Management) is enabled on the remote computer, you can use WSman instead of WMI to connect:
Restart-Computer -ComputerName wks-11222 -Protocol WSMan
If there are active user sessions on the remote computer, an error will appear:
Restart-Computer : Failed to restart the computer wks-11222 with the following error message: The system shutdown cannot be initiated because there are other users logged on to the computer.
To force a reboot, you need to add the -Force parameter:
Restart-Computer -ComputerName wks-11222 –Force
You can use the -For
option to restart your computer and wait until it becomes available. For example, you want to make sure that the remote computer reboots successfully and the WinRM service is started on it, allowing you to connect to it through WS-Management:
Restart-Computer -ComputerName wks-11222 -Wait -For WinRM
Restarting computer wks-11222 Verifying that the computer has been restarted.
You can wait for the Remote Desktop Service (RDP) or any other Windows service to start:
Restart-Computer -ComputerName wks-11222 -Wait -For TermService
If you need to restart multiple computers at the same time, you can use the parallel command execution available in PowerShell 7.x (see how to update PowerShell).
For example, you can get a list of Windows Servers hosts in a specific Active Directory container (Organizational Unit) using the Get-ADComputer cmdlet and restart them at the same time:
$Computers = (Get-ADComputer -Filter 'operatingsystem -like "*Windows server*" -and enabled -eq "true"' -SearchBase "OU=Servers,DC=woshub,DC=com").Name
$Computers | ForEach-Object -Parallel { Restart-Computer -ComputerName $_ -Force} -ThrottleLimit 3