Wednesday, June 14, 2017

Enable and Disable New Remote Desktop Connections with Powershell

Enable and Disable New Remote Desktop Connections with Powershell

I was doing maintenance this morning on a Remote Desktop farm that contains few Session Collections and 15 + Servers, so I had to Deny all new connections from the farm.

Because I am lazy and don't want to click on GUI too many times, I wanted to do it on powershell. My goal is actually automatise most of the regular maintenance tasks, so this script comes handy. To my supprice, Google didn't find any ready scripts to this, so I had to write it myself.

Here are two scripts, Deny connections and Allow connections. It is easy also to put Allow/Deny as parameter, but in my case, this is more useful. 

This is how it works:
1) Get all RD Sessionhosts to $Hosts variable
2) For each loop to allow/deny connections
3) Write host

Deny New Connections:
$Hosts = Get-RDServer | where 'Roles' -eq "RDS-RD-Server" | Select -Expand Server

 ForEach($Hostx in $Hosts)
{
$Hostx
set-RDSessionHost $Hostx -NewConnectionAllowed No
}

Write-Host -ForegroundColor Red "New Connections are disabled"

Allow New Connections
$Hosts = Get-RDServer | where 'Roles' -eq "RDS-RD-Server" | Select -Expand Server

 ForEach($Hostx in $Hosts)
{
$Hostx
set-RDSessionHost $Hostx -NewConnectionAllowed Yes
}

Write-Host -ForegroundColor Red "New Connections are enabled"