Skip to content

Instantly share code, notes, and snippets.

@lidopaglia
Created July 2, 2014 15:49
Show Gist options
  • Save lidopaglia/5ce38e7fcf384173cffc to your computer and use it in GitHub Desktop.
Save lidopaglia/5ce38e7fcf384173cffc to your computer and use it in GitHub Desktop.
Connect to one or more hosts via RDP
<#
This Gist was created by ISEGist
07/02/2014 11:49:27
#>
#requires -Version 4.0
<#
.SYNOPSIS
Make an RDP connection.
.DESCRIPTION
Continuously tests one or more hosts for TCP connectivity on RDP port (default port is 3389) and
establishes an RDP session via mstsc.exe once the host is available. This cmdlet will continue to
test for connectivity until the timeout value is reached or the host comes online. The default timeout
value is 5 minutes.
.PARAMETER ComputerName
One or more computers to establish an RDP session with.
.PARAMETER Port
The TCP port used to test RDP availability to a given host. The
specified port is also used to connect to the specified host via
mstsc.exe The default value is 3389.
.PARAMETER TimeOut
The time out duration in minutes. Should a given host never
come back online the cmdlet will expire once it reaches the
timeout value. The default timeout value is 5 minutes.
.PARAMETER AsJob
Supports running the command as a background job.
.EXAMPLE
Connect-RDP -ComputerName SERVER01
.EXAMPLE
Write-Output SERVER01,SERVER02 | Connect-RDP -AsJob
.EXAMPLE
Connect-RDP localhost -Port 37000
#>
function Connect-RDP
{
[CmdletBinding()]
Param(
[Parameter(Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName=$true)]
[string[]]
$ComputerName,
[int]
$Port = '3389',
[int]
$TimeOut = '5',
[switch]
$AsJob
)
Process
{
foreach ($Name in $ComputerName)
{
[scriptblock]$sb = {
Param($Name,$Port,$TimeOut)
$sw = [system.diagnostics.stopwatch]::startNew()
do
{
$params=@{
ComputerName = $Name
Port = $Port
InformationLevel = 'Quiet'
}
try
{
$Online = Test-NetConnection @params -ErrorAction Stop
}
catch
{
Write-Error $_.Exception.Message
break;
}
Write-Verbose "$Name`: Waiting to connect. Time out in $($TimeOut - $sw.Elapsed.TotalMinutes) min."
sleep 5
}
until($Online -or ($sw.Elapsed.TotalMinutes -gt $TimeOut))
if($Online)
{
& mstsc /v:$Name`:$Port
}
}
$Params = @{
ScriptBlock = $sb
ArgumentList = $Name,$Port,$TimeOut
}
if($AsJob)
{
Start-Job @Params | Out-Null
}
else
{
Invoke-Command @Params
}
}
}
}
Set-Alias -Name rdp -Value Connect-RDP -Force
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment