If you’ve ever had to put a large number of 2008+ Windows Terminal/Remote Desktop servers in “drain mode” using the gui admin tool, you know it can be slow and tedious. Faced with doing this on a Saturday night for about 30 servers I decided to make life a little quicker and easier by building a powershell script. While my long term goal is to figure out how to drain an entire farm, for now I’m pretty satisfied to be able to do it from PowerShell pretty quickly.
There are two scripts. Drain-RDserver.ps1 and Undrain-RDserver.ps1. Both require a single parameter “-RDserver” followed by the server name. Drain changes the “User logon mode” to “Allow reconnections, but prevent new logons.” This could be changed to the “Allow reconnections, but prevent new logons until the server is restarted” by modifying the script. Undrain puts the server back in “Allow all connections” mode.
Big thanks to SourceDaddy’s article which got me started on the right path. (http://sourcedaddy.com/windows-7/preparing-server-maintenance.html)
Here is the code:
###Drain-RDServer # Input computer name param ( [string]$RDServer = $(throw "-RDserver is required") ) $RDSH = Get-WmiObject -Class "Win32_TerminalServiceSetting" -Namespace "root\CIMV2\terminalservices" -ComputerName $RDServerdra -Authentication PacketPrivacy -Impersonation Impersonate $RDSH.SessionBrokerDrainMode=1 $RDSH.put() > $null Write-Host "$RDServer is set to:" switch ($RDSH.SessionBrokerDrainMode) { 0 {"Allow all connections."} 1 {"Allow incoming reconnections but prohibit new connections."} 2 {"Allow incoming reconnections but until reboot prohibit new connections."} default {"The user logon state cannot be determined."} }
###Undrain-RDServer # Input computer name param ( [string]$RDServer = $(throw "-RDserver is required") ) $RDSH = Get-WmiObject -Class "Win32_TerminalServiceSetting" -Namespace "root\CIMV2\terminalservices" -ComputerName $RDServer -Authentication PacketPrivacy -Impersonation Impersonate $RDSH.SessionBrokerDrainMode=0 $RDSH.put() > $null Write-Host "$RDServer is set to:" switch ($RDSH.SessionBrokerDrainMode) { 0 {"Allow all connections."} 1 {"Allow incoming reconnections but prohibit new connections."} 2 {"Allow incoming reconnections but until reboot prohibit new connections."} default {"The user logon state cannot be determined."} }
Very good code, thank you.
But the RDS Management Console 2012 always displays : Session Available = true
I haven’t had a chance to test with 2012+. If someone out there finds some edits are required feel free to post back.
From my testing and from similar posts about this topic I’ve found that your definitions for Drain Mode values 1 & 2 are reversed. 1 is for “until reboot”. I am using Windows Server 2008 R2 but not sure if there is a differences between Windows versions.
thank you for this great post!
i confirm the Server Manager is not reflecting the change made directly into the wmi that is a problem.