Seeking Script Feedback

Hello,

I have been working on a POC where I wanted to leverage AWS EC2 Instance Connect Endpoint to RDP to EC2 instances from Azure Virtual Desktop which will be acting as a Bastion Host.

The way EC2 Instance Connect Endpoint is by opening a private tunnel to the VPC where the instance is located over a local port of the local machine (in this case, Azure Virtual Desktop).

Even though I intend to have a pool of Azure Virtual Desktop Session Hosts, I will have about 100+ SSO users connecting to the Session Hosts and establishing RDP session to the EC2 instances.

This will obviously lead to a conflict in choosing the port over which a given user will try to establish the RDP connection.

I have been working on a script where I publish the already used up ephemeral ports which are consumed by aws process. The idea would be to put the script as perhaps a Logon script, so every time a user logs in, the script autoruns and displays which ports are already consumed by aws process and suggest them not to use it for the given Session Host. Perhaps even open up a webpage that mentions the port numbers not to use, every time someone logs to the Session Hosts.

Need some feedback around the script on if it could be optimized better or composed in a better way following Powershell best practices.

#Find PID of all established connections which uses ephemeral ports
$connections= Get-NetTCPConnection -State Established | Where-Object {($_.LocalPort -ge 49812) -and ($_.LocalAddress -eq '127.0.0.1')}

$existingprocess = @($connections.OwningProcess)

#Find PID of aws.exe
$awsprocess = (Get-Process aws).Id

#Compare both PIDs
if ($existingprocess -contains $awsprocess) {
        $localport = ($connections | Where-Object {$_.OwningProcess -eq $awsprocess}).LocalPort
        Write-Host "Please DO NOT use following ports for establishing RDP connection: " $localport | Format-Table
}
else {
    Write-Host "Please select ONLY following port range for establishing RDP connection: 49812 - 65535"
}

Amitabh,
Welcome back to the forum. :wave:t3: … long tim no see. :wink:

I didn’t get exactly what you’re talking about and I don’t have experiences with AWS EC2 or Azure Virtual Desktop … but …

… wouldn’t it be more helpful and actually more professional when you recommend a port or even better offer a limited choice of ports to be used by users instead of listing ports they cannot use? :thinking: :man_shrugging:t3: :wink:

Hello Olaf,

Thank you for welcoming me back. I do agree with your comments and have been working on making the script ‘more inclusive’. I have updated the script accordingly in this comment section. Not sure how to edit the original post rather…

#Find PID of all established connections which uses ephemeral ports
$connections= Get-NetTCPConnection -State Established | Where-Object {($_.LocalPort -ge 49812) -and ($_.LocalAddress -eq '127.0.0.1')}

if ($null -eq $connections) {
    Write-Host "No previous TCP connections are established over ephemeral ports for localhost"
}
elseif ($connections) {
    $existingprocess = @($connections.OwningProcess)
}

#Find PID of aws.exe
$awsprocess = Get-Process aws -ErrorAction SilentlyContinue
if ($null -eq $awsprocess) {
    Write-Host "No previous aws process are running"
}
elseif ($awsprocess) {
    $awsprocessid = (Get-Process aws).Id
}

#Compare both PIDs
if ($existingprocess -contains $awsprocessid) {
        $localport = @(($connections | Where-Object {$_.OwningProcess -eq $awsprocessid}).LocalPort)
        Write-Host "Please DO NOT use following ports for establishing RDP connection: "`n $localport | Format-Table
}
else {
    Write-Host "Please select ONLY following port range for establishing RDP connection: 49812 - 65535."
    Write-Host "Choosing a random port ...."
}

#Ask user to pass the instance ID of the EC2 machine to connect and the awsprofile name they would be using
$instanceId = Read-Host -Prompt "Put in the Instance ID to which you want to connect"
$awsprofile = Read-Host -Prompt "Put the AWS Profile name you are going to use. You are expected to input the exact profile name during SSO sign in the coming steps"
#Generate Random Emhemeral Port
$randomport = Get-Random -Minimum 49812 -Maximum 65535
while ($localport -contains $randomport) {
    $randomport = Get-Random -Minimum 49812 -Maximum 65535
}
Write-Host "Generated Random Port number to use: $randomport"
Write-Host "
**Please use the random generated port to initiate an Remote Desktop session to the previously provided instance only.**

**For another instance ID, the script needs to be rerun and it will generate another random Port to initiate Remote Desktop session to the second instance.**

**If you use the same Port number to connect to multiple instances, it will not work. Rather, it will keep reinitiating the sessions for the first instance Id which was provided.**
" -ForegroundColor Red -BackgroundColor Yellow -NoNewline

#Start a new PowerShell session for the AWS SSO configuration
$configureProcess = Start-Process Powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command `"aws configure sso`"" -PassThru
$configureProcess.WaitForExit()

#Wait for the user to complete the SSO configuration in the new session. Once the SSO configuration is completed, continue with opening the tunnel
Write-Host "AWS SSO configuration completed. Continuing with opening EIC tunnel."

<# This bit doesn't work yet.
#Initiate RDP Session
$machinename = "localhost:$randomport"
Start-Process Powershell -ArgumentList "/v:$machinename -NoProfile -ExecutionPolicy Bypass -Command `"$env:windir\system32\mstsc.exe`"" -Wait
#>
#Create EIC Endpoint tunnel
Invoke-Expression "aws ec2-instance-connect open-tunnel --instance-id $instanceId --remote-port 3389 --local-port $randomport --profile $awsprofile"

While the original intent of the thread still remains, where I am trying to understand from PowerShell experts if there are rooms of improvement in the way I have approached on the script, I am however, subjected to an ongoing issue where I am looking for some assistance as well. Should I club both the requests in same thread, or should my query become part of a new thread?

There is an edit button (the pen) underneath each post - sometimes hidden behind the gear symbol.

Asking for reviews is a kind of asking for opinions. And that’s - as far as I’m concerned - not the best idea in an internet forum. :wink:
We mostly focus on helping on one particular issue with a given code snippet at a time. If you post a complete script there are usually so many issues that it’s going to be hard to answer every aspect of it in a forum.

Anyway there are forums dedicated to this kind of requests. You may try it there as well:

Now … your code … I already mentioned I don’t know exactly what you’re trying to achieve with your code. So here are just a few of my opinions. :wink:

  • Your code is way too talkative … Why announcing that there are no previous TCP connections and no aws processes? Does that provide any benefit for the user? :thinking:
  • You still tell the user what NOT to do “Please DO NOT use following ports …” Don’t do that! :point_up_2:t3:
  • Asking for free text input with Read-Host is - as far as I’m concerned - always a bad idea and very much error prone. :point_up:t3: I’d prefer to offer a limited choice for the user to choose from. Either with a dot Net snippet with the method “PrompForChoice” or - a little more PowerShelly - with an Out-GridView. :+1:t3:
  • You’re calling another PowerShell instance from inside your already running PowerShell instance to run an external program (aws). Why? :man_shrugging:t3:
  • You’re calling another PowerShell instance from inside your already running PowerShell instance again to run an external program (mstsc.exe). Why? :man_shrugging:t3:

Again … IMHO your question is way to broad or vague. I’d recommend to be as specific as possible with your questions. Pick one issue - ask for it - if that’s solved move on to the next issue.

There is ALWAYS room for improvement. :wink: You may find this helpful: