Script to disconnect RDP sessions

I have about 12 users that will normally remote into our server to do some quickbooks work, I need then to log off the server when they are done working, this usually does not happen they will exit from QB but leave the session open. This causes me problems as I have several applications doing automated task every night. I need a batch file/Script that I can set to run every night at a certain time and completely log them off the server except myself the admin. As a courtesy I would like to send everyone logged on a quick message letting them know that "the server will log you off save your work you have 2 minutes"  then log everyone off the server again EXCEPT the admin.  I am running a Windows 2012 R2 server.
padillrrProject CoordinatorAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Will SzymkowskiSenior Solution ArchitectCommented:
What I would recommend instead of using a script is using Group Policy to accomplish this. You can configure the Session Time Limits which will logoff Disconnected or Idle sessions. You can then apply this to all of your Servers and enable loopback policy so that it does not affect the Administrator.

GPO is the more controlled approach.

See the below link for details.
https://technet.microsoft.com/en-us/library/cc753112(v=ws.10).aspx

Will.
0
padillrrProject CoordinatorAuthor Commented:
We are not using the server with any type of LDAP it is setup as an application server
0
Will SzymkowskiSenior Solution ArchitectCommented:
You do not do this on the server you use Group Policy Management Console for this.  

If you do not have an AD environment you can. Accomplish the same thing using local policy.

Use gpedit.msc to open local policy.

Follow the rest of the steps from the first link I posted.

Will.
0
oBdACommented:
For the fun of it, a plain batch script.
It's currently in test mode and will only display the msg and logoff commands it would normally run.
Remove the uppercase ECHOs in lines 73 and 85 to run it for real. These are just for initial testing.
The script has a second safeguard: after it spits out a csv with session information, you have to confirm the logging off.
To skip the confirmation for unattended execution, call it with the /Logoff:True argument.
@echo off
setlocal enabledelayedexpansion
REM Set to True to exclude the session running the script from being logged off, to False otherwise:
set ExcludeCurrent=True
REM Set to True to exclude the console session from being logged off, to False otherwise:
set ExcludeConsole=False
REM Set to True to exclude active sessions from being logged off, to False otherwise:
set ExcludeActive=False
REM A space separated list of users to be excluded from logoff:
set ExcludeUsers=Administrator
set Wait=15
set Message=Please save your work NOW, you will be logged off in %Wait% seconds, starting at %Time%!

REM Default values for command line options:
set Server=%ComputerName%
set Logoff=False
if /i "%~1"=="/?" goto Syntax
if /i "%~1"=="-?" goto Syntax
if /i "%~1"=="/help" goto Syntax
if /i "%~1"=="-help" goto Syntax
call :GetArgs %*

set /a SessionCount = 0
for /f "skip=1 delims=" %%a in ('query.exe session /server:%Server%') do (
	set Line=%%a
	if "!Line:~0,1!"==" " (set Current=False) else (set Current=True)
	call :Trim !Line:~1,18!
	set SessionName=!Trim!
	call :Trim !Line:~19,21!
	set User=!Trim!
	call :Trim !Line:~40,6!
	set SessionId=!Trim!
	call :Trim !Line:~48,8!
	set Status=!Trim!
	if not "!User!"=="" (
		set /a SessionCount += 1
		set Session[!SessionCount!].Server=!Server!
		set Session[!SessionCount!].Current=!Current!
		set Session[!SessionCount!].Name=!SessionName!
		set Session[!SessionCount!].User=!User!
		set Session[!SessionCount!].Id=!SessionId!
		set Session[!SessionCount!].Status=!Status!
		set Session[!SessionCount!].Logoff=True
	)
)
echo "Server","User","Current","Name","Id","Status","Logoff"
for /l %%i in (1, 1, %SessionCount%) do (
	if /i "!Session[%%i].Status!"=="Active" (
		if /i "%ExcludeActive%"=="True" set Session[%%i].Logoff=False
	)
	if /i "!Session[%%i].Name!"=="console" (
		if /i "%ExcludeConsole%"=="True" set Session[%%i].Logoff=False
	)
	if /i "!Session[%%i].Current!"=="True" (
		if /i "%ExcludeCurrent%"=="True" set Session[%%i].Logoff=False
	)
	for %%a in (%ExcludeUsers%) do (
		if /i "%%~a"=="!Session[%%i].User!" set Session[%%i].Logoff=False
	)
	echo "!Session[%%i].Server!","!Session[%%i].User!","!Session[%%i].Current!","!Session[%%i].Name!","!Session[%%i].Id!","!Session[%%i].Status!","!Session[%%i].Logoff!"
)
If /i not "%Logoff%"=="True" (
	set Confirm=n
	>CON echo.
	set /p Confirm=Enter "y" to log off the users indicated above: >CON
	if /i not "!Confirm!"=="y" goto :eof
)

echo Informing users:
for /l %%i in (1, 1, %SessionCount%) do (
	if /i "!Session[%%i].Logoff!"=="True" (
		echo   - User '!Session[%%i].User!' in session !Session[%%i].Id!
		ECHO msg.exe !Session[%%i].Id! /Server:%Server% /Time:%Wait% "%Message%"
	)
)

echo Waiting %Wait% seconds before logging off the remaining users.
set /a Pings = Wait + 1
ping.exe -4 -n %Pings% localhost >NUL

echo Logging off users:
for /l %%i in (1, 1, %SessionCount%) do (
	if /i "!Session[%%i].Logoff!"=="True" (
		echo   - User '!Session[%%i].User!' in session !Session[%%i].Id!
		ECHO logoff.exe !Session[%%i].Id! /Server:%Server%
	)
)
echo Done.
goto :eof

:Trim
set Trim=%*
goto :eof

:GetArgs
if "%~1"=="" goto :eof
for /f "tokens=1* delims=/:" %%a in ("%~1") do if not "%%b"=="" set %%a=%%b
shift
goto :GetArgs

:Syntax
echo Logs off RDP users after sending them a message.
echo.
echo Syntax:
echo %~nx0 [/Server:^<Server^>] [/Logoff:{True ^| False}]
echo /Server: The RDS server to run against; default: %Server%.
echo /Logoff: If False, waits for confirmation after listing the sessions; default: %Logoff%.
echo.
echo Settings:
echo Wait before logoff:      %Wait% seconds
echo Exclude active sessions: %ExcludeActive%
echo Exclude console session: %ExcludeConsole%
echo Exclude current session: %ExcludeCurrent%
echo Exclude users:
for %%a in (%ExcludeUsers%) do echo    %%a
goto :eof

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Windows Batch

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.