Windows/Powershell: Changing Remote Desktop Protocol Port based on Servers in a User Defined OU

Created: 12/27/19

Updated: 12/27/19

A while back I wrote up how to change the RDP protocol port on a server via command line. Here is the same kind of protocol change but with a Powershell script.

# Change RDP Port for Servers – Select All

# Define User Input Variables

$OUName = Read-Host “Enter Organization Unit of Servers that you want RDP Port Changed”
$DomainName = Read-Host “Enter Domain Name without the .com/.edu/.local ending of Servers that you want RDP Port Changed”
$DomainExtension = Read-Host “Enter Domain Extension (Example = .com/.edu/.local without the dot) of the domain the Servers that you want RDP Port Changed are apart of”
# This will prompt you to input the port number you want ot use for Remote Desktop Connection aka RDP
$RDPPort = Read-Host “Enter Desired Remote Desktop Protocol Port for Servers”

# Apply a different RDP (default 3389) to Servers in the specified OU for the domain in question

$Servers = Get-ADComputer -Filter * -SearchBase “CN=$OUName,DC=$DomainName, DC=$DomainExtension”
Foreach ($Server in $Servers) {
Invoke-Command -ComputerName $ServerHostname -ScriptBlock {
param ($Server)
Set-ItemProperty -Path “HKLM:\System\CurrentControlSet\Control\Terminal Server\Winstations\RDP-Tcp\” -Name PortNumber | Select-Object PortNumber -Value 8989
New-NetFirewallRule -DisplayName “Remote Desktop – TCP-Inbound – $RDPPort” -Direction Inbound -Protocol TCP -Profile Any -LocalPort $RDPPort -Action allow
New-NetFirewallRule -DisplayName “Remote Desktop – UDP-Inbound – $RDPPort” -Direction Inbound -Protocol UDP -Profile Any -LocalPort $RDPPort -Action allow

# This is a invoke commmand asking if you want to reboot after applying this change

[ValidateSet(‘Yes’, ‘No’)]$Reboot = Read-Host “Want to Restart? Enter Yes/No”
If ($Reboot -eq ‘Yes’) { Restart-Computer -Force }
} -ArgumentList $Server