In this guide, you will learn how to log off users from remote computers.
Users will often forget to sign out of their computers. This can be a problem if you need to reboot the computer or perform maintenance on it.
The good news is there is a built-in Windows command that can log off the users on a remote computer. These steps will work on Windows 10, 11, and Server OS versions.
Let’s check it out.
Step 1. Check Who is Logged on the Remote Computer
First, you need to use the quser command to see who is logged onto the computer and also get their session ID number. Open the command prompt and run the below command. Change pc1 to your target computer.
quser /server:pc1
The above command will get all logged on users from pc1.
In the screenshot above, you can see user “adam.reed” and “robert.allen.da” is logged into PC1. Robert is disconnected and adam is Active. I’ll take note of the user’s ID numbers (1 and 2).
Step 2. Use The Logoff Command
Now that we have the session IDs we can use the logoff command to log out the users on the remote computer.
Logoff 1 /server:pc1
The above command will log off the user with session ID 1 from pc1.
Note: Even though the command has the /server switch it will work with client operating systems like Windows 10 and 11. In this example, pc1 is a windows 10 computer.
Now, if I run the quser command you will see adam.reed is no longer logged in.
Related Content
How to Check Windows Server Uptime
Run PowerShell command on Remote Computer
Несколько раз встречался с ситуацией, когда один из пользователей 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
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.
There are multiple ways to log off the current user on a Windows system using the command line. The version of the commands below will depend on the Windows version, the interface you are using to log off the user (e.g. Remote Command Prompt, RMM, Local Command Prompt) etc..
The command to force the current user to log off immediately using the command line in Windows is:
shutdown /l /f /t 00
Sometimes you will need to use a “-” instead of a “/”
shutdown -l -f -t 00
If you’d like to log off the session giving the current user the chance to save any work you would just exclude the “/f”
shutdown /l
or
shutdown -l
On some remote management systems you can’t issue the shutdown command. In these cases what you need to do is find out the current user’s active session number by issuing the following command:
query user
You will then be able to see the current user’s Id and issue the logoff command instead:
logoff 1
Where 1 is the ID of the user you are logging off after performing the query user command.
The following command has been tested on Windows XP, Windows 7, Windows 8, Windows 8.1, Windows 10. Your mileage may vary on other version of windows.
Here is a quick and easy way to remotely log off end users who are still logged into their computers. This is especially useful when you are trying to do maintenance.
End users are sometimes logged into their computers for far too long. It seems like every time you’d like to do some maintenance on the computer that requires a user logging out, they don’t seem to do it or the computer is idling with them logged in!
Luckily, we can take this into our own hands by forcing a logoff remote from another computer.
Using PowerShell, we can create a script that reaches out to one or more remote Windows computers, checks to see if anyone is logged in and, if so, logs them out. We can even log off all users if we so desire.
Before we get too crazy though, we first need to figure out how to find which users are logged into a remote computer.
Checking Who Is Logged-in
There are a few ways to do that but I’ve chosen to use the quser command. This is a non-PowerShell command but we can still just as easily use it from within PowerShell.
You can play around with this command by running it locally on your Windows computer to get an idea of the output.
PS> quser
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
>administrator console 1 Active none 9/22/2018 11:04 AM
However, we’ll be using PowerShell to parse this string output so you don’t have to worry about it in the first place!
The quser command also can query remote computers using the /server switch, however, I have chosen not to use this method because we now have the advantage of using PowerShell Remoting. Instead, we can run quser by itself
on the remote computer.
PS> Invoke-Command -ComputerName 'REMOTECOMPUTER' -ScriptBlock { quser }
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
abertram rdp-tcp#7 2 Active 7 9/26/2018 4:57 PM
Remote Logoff in PowerShell
Now that you know of how to find the logged in users, we now need to figure out how to log off a user. I’ve chosen to use the logoff command. The logoff command is another non-PowerShell command, but is easy enough to
call from within a script.
In the example above, ‘abertram’ is logged into the remote computer in session 2. Using the logoff command, we simply need to pass the session ID to the command as an argument and it will dutifully log the user off as expected.
PS> Invoke-Command -ComputerName 'REMOTECOMPUTER' -ScriptBlock { logoff 2 }
I can run quser again on the remote computer and we can now see that it has been logged off.
PS> Invoke-Command -ComputerName 'REMOTECOMPUTER' -ScriptBlock {quser}
No User exists for *
+ CategoryInfo : NotSpecified: (No User exists for *:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : REMOTECOMPUTER
Remotely Logoff a Specific User
We now need to put these two commands together to allow us to specify a username rather than a session ID to log off a user account. To do that, we need to run quser, filter the output by username and then parse the session ID from that
output sending it to the logoff command.
$scriptBlock = {
$ErrorActionPreference = 'Stop'try {
## Find all sessions matching the specified username
$sessions = quser | Where-Object {$_ -match 'abertram'}
## Parse the session IDs from the output
$sessionIds = ($sessions -split ' +')[2]
Write-Host "Found $(@($sessionIds).Count) user login(s) on computer."
## Loop through each session ID and pass each to the logoff command
$sessionIds | ForEach-Object {
Write-Host "Logging off session id [$($_)]..."
logoff $_
}
} catch {
if ($_.Exception.Message -match 'No user exists') {
Write-Host "The user is not logged in."
} else {
throw $_.Exception.Message
}
}
}## Run the scriptblock's code on the remote computer
PS> Invoke-Command -ComputerName REMOTECOMPUTER -ScriptBlock $scriptBlockFound 1 user login(s) on computer.
Logging off session id [rdp-tcp#10]...
You can see above when Invoke-Command is running with the scriptblock created, it will detect the user logged in and immediately log them off. Pretty cool! Don’t stop here; read our eBook, «How to Automate Using PowerShell,» for other automation hacks.