Snippet: Extending Connect-MSTSC for fun and profit

If you’ve ever come across Jaap Brasser’s Connect-MSTSC script, you’ll know it’s a pretty cool script. If you have a cloud service such as AWS, and you haven’t leveraged this script in conjunction with Get-EC2PasswordData, then frankly you’re doing something wrong.

I’ve had several variations around this script in our AWS utility script for a while now. There’s Connect-EC2Instance, Connect-RobotArmyv2Group and a few other variations. And there’s the one I put together today, which demonstrates a couple of things, so I thought I’d share

  1. Using Filters to find EC2 instances with particular extended properties
  2. Leveraging open-source code to make your life exponentially easier.

First of all, filters. If you do a Get-Help on Get-EC2Instance, you’ll see the filter property prominently advertised, but what you won’t immediately see is how to use it. What -Filter expects to be handed is an object array of type Amazon.EC2.Model.Filter.

So let’s have a look at what that is

New-Object -typeName Amazon.EC2.Model.Filter | Get-Member 

   TypeName: Amazon.EC2.Model.Filter

Name        MemberType    Definition
----        ----------    ----------
Value       AliasProperty Value = Values
Equals      Method        bool Equals(System.Object obj)
GetHashCode Method        int GetHashCode()
GetType     Method        type GetType()
ToString    Method        string ToString()
Name        Property      string Name {get;set;}
Values      Property      System.Collections.Generic.List[string] Values {get;set;}

OK, so it expects a Name/Value or Name/Values structure. That’s pretty easy to create in an ad-hoc fashion, like so

@{ Name = "private-ip-address"; Values = "10.123.26.144" }

So, we can use this to find an instance with a given IP address, or a given tag, or a given keypair. There’s a whole list of filter properties in the detailed Get-Help output for Get-EC2Instance. So let’s put this together with Get-EC2PasswordData to give us a simple script that will find the Admin password and connect to an instance immediately

Function Connect-ByIp
{
param
(
  $ip
)

  $instance = Get-EC2Instance -filter @{ Name = "private-ip-address"; Values = $ip }
  $instanceid = $instance.RunningInstance.InstanceId
  $password = Get-EC2PasswordData -InstanceId $instanceid -Decrypt -PemFile \\tsclient\c\pemfiles\keypair.pem 
  Connect-Mstsc -ComputerName $ip -User Administrator -Password $password
}

And there you have it. A valuable script now has added value as an AWS tool. Win.

One reply

  1. Jaap Brasser says:

    Excellent, great to see the script used in this way. I never used it to connect to AWS instances but I like the work you did on the script.

Leave a Reply to Jaap Brasser Cancel reply

Your email address will not be published. Required fields are marked *