Powershell command to kick disconnected users off a server Powershell command to kick disconnected users off a server powershell powershell

Powershell command to kick disconnected users off a server


I can't try this:

$pc = qwinsta /server:YourServerName | select-string "Disc" | select-string -notmatch "services"if ($pc){  $pc| % {   logoff ($_.tostring() -split ' +')[2] /server:YourServerName   }}


In my opinion, the easiest way would be to use logoff.exe that already exists on your machine. for instance to log off the first disconnected user in your screenshot:

logoff 3 /server:YOURSERVERNAME


Here's a great scripted solution for logging people out remotely or locally. I'm using qwinsta to get session information and building an array out of the given output. This makes it really easy to iterate through each entry and log out only the actual users, and not the system or RDP listener itself which usually just throws an access denied error anyway.

$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    }}

In the first line of this script give $serverName the appropriate value or localhost if running locally. I use this script to kick users before an automated process attempts to move some folders around. Prevents "file in use" errors for me. Another note, this script will have to be ran as an administrator user otherwise you can get accessed denied trying to log someone out. Hope this helps!