PowerShell: Starting Remote Desktop Once Server Available

This is a simple but useful bit of PowerShell. Have you ever been waiting on a server to reboot and ended up pinging it or trying to start a remote desktop session several times before it’s back up and you can log in? This script pings a server (or any computer) every 15 seconds until the server responds, then starts a remote desktop session.

param ([Parameter(Mandatory=$true)][string]$URL)#get the parameter and set it as the variable $URL

While (!(Test-Connection -ComputerName $URL -Quiet -Count 1)) { #Loops until Test-Connection reaches the server and returns true. Only tries one ping at a time
	Start-Sleep -s 15 #pauses for 15 seconds. Easily editable to different time lengths
}

mstsc /v:$URL #starts a remote desktop session

To use it, just save and run the script, passing the hostname or IP address as a parameter:

PowerShell screenshot showing passing an IP address as a parameter.

And if you want it as a one-liner you can copy and paste rather than saving it, use the following and replace the IP address at the beginning with the target IP address or hostname:

$URL = "192.168.0.3"; While (!(Test-Connection -ComputerName $URL -Quiet -Count 1)) { Start-Sleep -s 15 } ; mstsc /v:$URL

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.