Menu

Remote Desktop Session Hosts and Drain Mode Script

June 30, 2016 - Remote Desktop Scripts

UPDATE: This script is now included in the free Remote Desktop Commander Lite utility. Click here for more details.

Remote Desktop Services admins often have a frequent need to take their Remote Desktop Session Host servers in/out of “Drain Mode.” Drain mode, for the uninitiated, places the RDSH server in a state where it will no longer accept new connections, but will allow existing sessions to continue working until they sign off. In a full Windows Server 2012 RDS deployment, Server Manager gives you a menu option that will let you turn drain mode on/off.

Recently, a question was posted on the Remote Desktop Services Technet Forum regarding enabling/disabling drain mode for a Windows Server 2012 session host WITHOUT a full RDS deployment in place. Fortunately, this is possible with a a bit of clever Powershell code.

Placing RDS Servers in Drain Mode – PowerShell Script example

Here’s the script I’ve written that will take Remote Desktop Session Hosts in and out of drain mode. For downloaded scripts that you trust, you may need to invoke Set-ExecutionPolicy Bypass before PowerShell will run them. FYI – We add a digital signature to all our scripts you can inspect first to make sure they’ve not been tampered with.

RDS Drain Mode PowerShell Script Code

DrainMode.ps1 – Click to Download

Parameter list:

RDServers is a comma-delimited list of all Remote Desktop Session Hosts you wish to enable/disable new connections on. E.g. “RDSH01″,”RDSH02” .. To run against a single server, simply omit the commas (e.g. “RDSH01”)

DrainLevel sets the drain mode. Set to 1 to turn it on, Set to 0 to it off.

param(
[string]$RDServers, [int]$DrainLevel
)
$RDSArray = $RDServers -split ','
foreach ($RDS in $RDSArray)
{
    $TempRDS = $RDS.replace("`"","")
    if($TempRDS)
    {
        if($DrainLevel -eq 1)
        {
            Write-Host ("Turning On Drain Mode For System " + $TempRDS)
        }
        else
        {
            Write-Host ("Turning Off Drain Mode For System " + $TempRDS)
        }   
        $WMIHandle = Get-WmiObject -Class "Win32_TerminalServiceSetting" -Namespace "root\CIMV2\terminalservices" -ComputerName $TempRDS -Authentication PacketPrivacy -Impersonation Impersonate
        $WMIHandle.SessionBrokerDrainMode=$DrainLevel
        $WMIHandle.put() > $null
    }
}
Andy Milford is the CEO and Founder of RDPSoft, and is a Microsoft MVP in the Enterprise Mobility / Remote Desktop Services area. Prior to starting RDPSoft, Andy was the CEO and Founder of Dorian Software, a log management company acquired by Ipswitch in late 2009. He loves creating easy-to-use yet powerful software solutions for SMBs and emerging enterprise companies.

Leave a Reply

Your email address will not be published. Required fields are marked *