Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Here is how to extract tags into a flat object along with other properties

$region = 'us-west-2'
$instances = (Get-Ec2Instance -Region $region).Instances | select `
    @{Name="ServerName";Expression={$_.tags | where key -eq "Name" | select Value -expand Value}},`
    InstanceType ,`
    InstanceId,`
    ImageId,`
    @{Name="Role";Expression={$_.tags | where key -eq "Role" | select Value -expand Value}},`
    @{Name="Group";Expression={$_.tags | where key -eq "Group" | select Value -expand Value}},`
    @{Name="Subsystem";Expression={$_.tags | where key -eq "subsystem" | select Value -expand Value}},`
    @{Name="State";Expression={$_.State.Name}},`
    @{Name="Region";Expression={$region}}

$instances | Sort-Object -Property State, ServerName | Format-Table
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top