powershell: Check RDP port number remotely

I am creating a script to check details of Remote desktop connection.

$ts = get-WMIObject Win32_TerminalServiceSetting  -computername $s -Namespace ROOT\CIMV2\TerminalServices

With above script i can check RDP is enaled or not. But i need to check port number to be used in RDP.

I am aware 3389 is getting used but in my environment some servers RDP configured on other ports.

I need to fetch the port number. I checked in ROOT\CIMV2\TerminalServices WMI Class but port number detail is not there.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp

On this location i can see there is a dword (PortNumber) that contain the port number details.

Can we check some other way because by checking registry we need to start remote registry service is running and i am afraid sometimes they are stopped and we can't run it.


Solution 1:

I'm not sure about remote registry, its usually enough to have WinRM started. you can check the port number by using a combination of Invoke-Command and Get-itemProperty.

Invoke-Command -HideComputerName computer_machine { Get-ItemProperty  -Path HKLM:\SYSTEM\CurrentControlSet\Control\Termin*Server\WinStations\RDP*CP\ -Name PortNumber | select PortNumber}

Solution 2:

I have found the easiest way to know your port number if you are using Windows 10 and windows server 2012.

get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\'-name portnumber