Is there a powershell command I can use to kick "disconnected" users off a server? I can write the script once I know the single line to kick a single user.
For example, I want to kick the 8 users seen in the dialog below.
Is there a powershell command I can use to kick "disconnected" users off a server? I can write the script once I know the single line to kick a single user.
For example, I want to kick the 8 users seen in the dialog below.
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!
Here you go:
@echo off
(set STATE=Disconnected)
REM !! IMPORTANT set length in 4th from last line !!
FOR /f "Skip=1 tokens=3,4" %%i in ('qwinsta') do (
IF /I NOT "%%i"=="The" (
call :checkpath %%i "%%j"
)
)
::pause
GOTO :EOF
:checkpath
set id=%1
set STATUS=%~2
:: !! The last number in the next line needs to
:: be the length of the STATE string
SET root=%STATUS:~0,12%
IF /I NOT "%ROOT%"=="%STATE%" GOTO :EOF
@echo on
Session ID %ID% is %STATUS%. Logging off...
@echo off
logoff %ID% /server:YOURSERVERNAME