I am trying to formulate a Powershell command to remotely log off a user. We have a terminal server with a very unstable program that sometimes locks sessions. We have to remotely log off a user but I'm trying to write a Powershell statement that will log off the person who ran the script. I Googled around, and found this command:
Invoke-Command -ComputerName MyServer -Command {shutdown -l}
However, the command returns "incorrect function." I can run other commands successfully in the brackets, such as Get-Process.
The idea is for me to put that into a script that users can run to log themselves off of the server (since when it locks, they cannot access the start menu or ALT+CTRL+END to do it through the GUI).
The flow would be this: Bob logs into MyServer via RDP but his session freezes. On his local desktop, he can run MyScript (containing a command similar to above) which will log off his session on MyServer.
The logoff command will terminate a user's current session in a local or remote server or workstation. If we run the help command with the code below, we can see that the logoff cmdlet uses a few parameters like the session name or id and the server name, which are both critical. Example Code: Copy logoff /?
The Exit-PSSession cmdlet ends interactive sessions that you started by using the Enter-PSSession cmdlet. You can also use the exit keyword to end an interactive session. The effect is the same as using Exit-PSSession .
The simplest way is to use the Remote Desktop/Terminal Services command-line tool, logoff.exe (For details, at the PowerShell prompt, type logoff /? ). To log off the current active session, type logoff with no arguments.
Perhaps surprisingly you can logoff users with the logoff
command.
C:\> logoff /? Terminates a session. LOGOFF [sessionname | sessionid] [/SERVER:servername] [/V] [/VM] sessionname The name of the session. sessionid The ID of the session. /SERVER:servername Specifies the Remote Desktop server containing the user session to log off (default is current). /V Displays information about the actions performed. /VM Logs off a session on server or within virtual machine. The unique ID of the session needs to be specified.
The session ID can be determined with the qwinsta
(query session
) or quser
(query user
) commands (see here):
$server = 'MyServer' $username = $env:USERNAME $session = ((quser /server:$server | ? { $_ -match $username }) -split ' +')[2] logoff $session /server:$server
Adding plain DOS commands, if someone is so inclined. Yes, this still works for Win 8 and Server 2008 + Server 2012.
Query session /server:Server100
Will return:
SESSIONNAME USERNAME ID STATE TYPE DEVICE
rdp-tcp#0 Bob 3 Active rdpwd
rdp-tcp#5 Jim 9 Active rdpwd
rdp-tcp 65536 Listen
And to log off a session, use:
Reset session 3 /server:Server100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With