Powershell – Logoff Script on Remote Desktop Services

powershellrdwebremote-desktop-servicessessionwindows-server-2012-r2

I have a Remote Desktop services running on Server 2012 R2. My timeout settings have been set to end a session 60 minute after disconnection. This is good for all the users except one: That user's session has to be ended as soon as he is disconnected. I can't create another collection because I don't have a second session host.

I decided to create a super simple batch file that will force the user to log off such as this:

@ECHO off
logoff f

This, for some reason requires admin privileges and brings up the elevation prompt. So it's out of question at this point.

Then I created a powershell script such as this:

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))

{   
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
import-module RemoteDesktop
$name = [Environment]::Username
$session = get-rdusersession | Where-Object -Filter {$_.username -eq $name}
Invoke-RDUserLogoff -UnifiedSessionID $session.SessionID -HostServer $session.HostServer -Force

Again, this requires administrator rights and will not work too. It works for admins but nor for regular users.

Does anybody have an idea how I can accomplish this?

Best Answer

It turned out to be a lot simpler than I thought. Simply using and publishing "logoff.exe" under sys32 does the exact same job without the complexity of permissions.

Related Topic