Powershell注销远程会话

我试图制定一个Powershell命令来远程注销用户。 我们有一个非常不稳定的程序的终端服务器,有时会锁定会话。 我们必须远程注销用户,但我试图编写一个Powershell语句来注销运行该脚本的人员。 我搜索了一下,发现这个命令:

Invoke-Command -ComputerName MyServer -Command {shutdown -l}

但是,该命令返回“不正确的功能”。 我可以在括号中成功运行其他命令,例如Get-Process。

我的想法是把它放到一个脚本中,用户可以运行它们从服务器上注销自己的脚本(因为当它锁定时,它们不能通过GUI访问开始菜单或ALT + CTRL + END)。

流程如下:Bob通过RDP登录到MyServer,但他的会话冻结。 在他的本地桌面上,他可以运行MyScript(包含类似于上面的命令),它将在MyServer上注销他的会话。


也许令人惊讶的是,您可以使用logoff命令注销用户。

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.

会话ID可以使用qwinstaquery session )或quserquery user )命令(请参阅此处)确定:

$server   = 'MyServer'
$username = $env:USERNAME

$session = ((quser /server:$server | ? { $_ -match $username }) -split ' +')[2]

logoff $session /server:$server

这是一个伟大的脚本解决方案,用于远程或本地登录人员。 我正在使用qwinsta获取会话信息并从给定的输出中构建一个数组。 这使得迭代每个条目并仅注销实际用户非常容易,而不是系统或RDP侦听器本身,它们通常只是抛出拒绝访问错误。

$serverName = "Name of server here OR localhost"
$sessions = qwinsta /server $serverName| ?{ $_ -notmatch '^ SESSIONNAME' } | %{
$item = "" | Select "Active", "SessionName", "Username", "Id", "State", "Type", "Device"
$item.Active = $_.Substring(0,1) -match '>'
$item.SessionName = $_.Substring(1,18).Trim()
$item.Username = $_.Substring(19,20).Trim()
$item.Id = $_.Substring(39,9).Trim()
$item.State = $_.Substring(48,8).Trim()
$item.Type = $_.Substring(56,12).Trim()
$item.Device = $_.Substring(68).Trim()
$item
} 

foreach ($session in $sessions){
    if ($session.Username -ne "" -or $session.Username.Length -gt 1){
        logoff /server $serverName $session.Id
    }
}

在该脚本的第一行中,如果在本地运行,则给$ serverName适当的值或localhost。 我使用此脚本在用户尝试移动某些文件夹之前踢出用户。 为我预防“使用中的文件”错误。 另外需要注意的是,这个脚本必须以管理员用户身份运行,否则您可能会被拒绝尝试登录某人。 希望这可以帮助!


添加纯DOS命令,如果有人如此倾向。 是的,这仍然适用于Win 8和Server 2008 + Server 2012。

Query session /server:Server100

将返回:

SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
rdp-tcp#0         Bob                       3  Active  rdpwd
rdp-tcp#5         Jim                       9  Active  rdpwd
rdp-tcp                                 65536  Listen

要注销会话,请使用:

Reset session 3 /server:Server100
链接地址: http://www.djcxy.com/p/89655.html

上一篇: Powershell Log Off Remote Session

下一篇: How to schedule a task wether the user is logged on or not in PowerShell?