private/start/Start-EC2RemoteDesktopInternal.ps1

function Start-EC2RemoteDesktopInternal
{
    [CmdletBinding(PositionalBinding = $false)]
    param(
        [Parameter(Mandatory = $false)]
        [string] $ProfileName,

        [Parameter(Mandatory = $false)]
        [string] $Region
    )

    Set-Region -Region $Region
    Set-Profile -ProfileName $ProfileName

    Write-ProgramHeader

    $awsProfile = Get-ConnectionProfile
    Write-ConnectionProfile -AwsProfile $awsProfile

    $ec2Instances = Get-Instance
    if (-not $ec2Instances) { return }

    Write-Instance -Instances $ec2Instances

    $instanceId = Read-UserInstanceSelection -Ec2Instances $ec2Instances
    if (-not $instanceId) { return }

    Write-InstanceCredential -InstanceId $instanceId

    try
    {
        $localPort = Get-EphemeralPort
        $session = Start-PortForwardingSession -InstanceId $instanceId -LocalPort $localPort
        $ssmProcess = Start-SessionManagerPlugin -Session $session -Region $awsProfile.Region
        $rdpProcess = Start-WindowsRemoteDesktop -Port $localPort

        while (-not $rdpProcess.HasExited -and -not $ssmProcess.HasExited)
        {
            Start-Sleep -Milliseconds 50
        }
    }
    finally
    {
        Stop-WindowsRemoteDesktop -Process $rdpProcess
        Stop-SessionManagerPlugin -Process $ssmProcess
        Stop-PortForwardingSession -SessionId $session.Response.SessionId
    }
}