How to access list value in Get-EC2Instance's RunningInstance method?

Anthony Neace picture Anthony Neace · Aug 6, 2013 · Viewed 9.3k times · Source

I'm trying to retrieve the instanceid, public dns name, and "Name" tag from the object returned by get-ec2instance.

$instances = foreach($i in (get-ec2instance)) '
{ $i.RunningInstance | Select-Object InstanceId, PublicDnsName, Tag }

Here's the output:

InstanceId                              PublicDnsName                     Tag
----------                              -------------                     ---
myInstanceIdHere                        myPublicDnsName                   {Name}
...                                     ...                               {Name}

I would like to be able to access {Name} using the line of code above and print its value in this output. I've done a little bit of research since this initial posting, and found...

PS C:\Users\aneace\Documents> $instances[0].Tag.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     List`1                                   System.Object

Between this and the AWS docs, I think Tag refers to this list, but I'm not certain. I can access a table that prints key and value columns by calling $instances[0].Tag, but my problem now is that I would like that Value to be the output to my first table instead of the {Name} object. Any suggestions?

Answer

latkin picture latkin · Aug 7, 2013

Per the documentation, the Tag property is a list of Tag objects. So in general, there will be multiple keys/values stored there. Are you assuming that in your case there is only 1?

Select-Object allows you to grab not just raw property values, but calculated values as well. Let's say you just want a comma-delimited list of the Values from the Tag objects in the list. Here's how you would do it:

$instances = Get-EC2Instance `
             |%{ $_.RunningInstance } `
             | Select-Object InstanceId,PublicDnsName,@{Name='TagValues'; Expression={($_.Tag |%{ $_.Value }) -join ','}}

The elements of $instances will now have a property TagValues which is a string consisting of the Value from all Tags associated with the instance.