Powershell Log Off Remote Session

前端 未结 11 1219
情话喂你
情话喂你 2020-12-02 13:15

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 re

11条回答
  •  眼角桃花
    2020-12-02 14:02

    Log off all users from a machine:

    try {
       query user /server:$SERVER 2>&1 | select -skip 1 | foreach {
         logoff ($_ -split "\s+")[-6] /server:$SERVER
       }
    }
    catch {}
    

    Details:

    • the try/catch is used when there are no users are on the server, and the query returns an error. however, you could drop the 2>&1 part, and remove the try/catch if you don't mind seeing the error string
    • select -skip 1 removes the header line
    • the inner foreach logs off each user
    • ($_ -split "\s+") splits the string to an array with just text items
    • [-6] index gets session ID and is the 6th string counting from the reverse of the array, you need to do this because the query output will have either 8 or 9 elements depending if the users connected or disconnected from the terminal session

提交回复
热议问题