Windows – Reconnect a Remote Desktop connection after rebooting the host

remote desktopremote-accesswindows

I often find myself connecting to a workstation or server with Remote Desktop to perform a task which requires a reboot. In these cases, I usually need to reconnect after the host comes back online to ensure everything went as planned or to continue my work. In these cases, I will typically launch "ping -t" in a command prompt to let me know when I can reconnect.

However, I will occasionally get distracted with something else while waiting for the host to come back online and forget to come back to it. It would be really nice to be alerted when the host is back online and allow me to reconnect (ideally with a single click).

Does anyone know of an easy way to accomplish this? I'm thinking there must be a free utility available, or perhaps it could be done with a PowerShell script.

Best Answer

Quick and dirty Powershell script that I use daily:

<#
.Synopsis
Checks for and connects to RDP on a given server.
.Description
This script tests for an open port 3389 (standard Windows RDP), and if it finds it, passes the IP to mstsc.exe. Otherwise it retries indefinitely. Ctrl+C will halt the script.
.Parameter ip
IP or FQDN of a Windows machine to test. Only takes one argument.
.Parameter wait
Will assume that the machine is still up, wait until it stops responding (even once), and then try to connect. Good for machines that are about to reboot.
.Parameter Verbose
Will print a line each time it tries unsuccessfully.
.Example
rdpupyet.ps1 ITG-SRV-INF01 -Verbose
#>
[CmdletBinding()]
param($ip, [switch]$wait)

function Get-DownYet ($ip) {
    Write-Verbose "Waiting for $IP to shut down."
    do {
        try {$up = New-Object System.Net.Sockets.TCPClient -ArgumentList $ip,3389}
        catch {$up = $false}
    }
    until ($up -eq $false)
    Write-Verbose "$IP no longer responding."
}

Write-Verbose "Testing RDP Connection... Ctrl+C to quit."

if ($wait) {Get-DownYet $ip}
do {
    try {$success = New-Object System.Net.Sockets.TCPClient -ArgumentList $ip,3389}
    catch {Write-Verbose "RDP not active. Retrying."}
}
while (!$success)

mstsc.exe /v:$ip /admin

Doesn't time out, I'm afraid. But that could be easily added, along with a quick beep on successful response.
The bit I'm more happy with (taken from a currently unremembered source on the internet) is that this won't try and connect when the server comes responds to ping - instead, only when the standard RDP port is accessible.