Get-EC2Instance |%{ $_.RunningInstance } |
select-object InstanceId,LaunchTime,@{Name='Value'; Expression={$_.Tag.Value} }, @{Name='Key'; Expression={$_.Tag.Key} }
enter image description here
Each Value and Key have multiple values as you can see in the screenshot. How to rewrite the code so the output can look like:
enter image description here
Tony Hinkle
4,7627 gold badges25 silver badges35 bronze badges
asked Jun 23, 2015 at 23:44
1 Answer 1
Here's one solution; it's not the most elegant, but hopefully solves your problem:
For Your Use Case
Get-EC2Instance | `
%{
$x = $.RunningInstance;
$x.Tag | select-object
@{Name="InstanceId"; Expression={$x.InstanceId}}
,@{Name="LaunchTime"; Expression={$x.LaunchTime}}
,@{Name="Value"; Expression={$_.Value}}
,@{Name="Key"; Expression={$_.Key}};
}
Simple Demo
cls
$x = @(
(New-Object –TypeName PSObject –Prop @{Name='one';List=@('a','b','c');})
,(New-Object –TypeName PSObject –Prop @{Name='two';List=@('d','e','f');})
,(New-Object –TypeName PSObject –Prop @{Name='three';List=@('g','h','i');})
,(New-Object –TypeName PSObject –Prop @{Name='four';List=@('j','k','l');})
,(New-Object –TypeName PSObject –Prop @{Name='five';List=@('m','n','o');})
)
#show what the preparation code produced:
#$x | select Name, List
#show the output we're after
$x | %{$n=$_.Name; $_.List | select @{Name="Name";Expression={$n}},@{Name="ListValue";Expression={$_}}}
answered Jun 24, 2015 at 0:02
6 Comments
minisch
Hi That doesnt solve my problem. $x.Tag doesnt contain the instance and launchtime values.
Matt
@minisch then make a simple change for your debugging. This answer has a correct logical approach to your problem.
JohnLBevan
@minisch: the code doesn't take
InstanceId
or LaunchTime
from $x.Tag
, but from $x
directly. Take a closer look and you'll see value and key come from $_
which represents $x.Tag
whilst InstanceId
and LaunchTime
come from $x
.minisch
$output | %{$n=$_.InstanceId; $_.Key | select @{Name="InstanceID";Expression={$n}},@{Name="Key";Expression={$_}}} I tried this command it worked exactly the way I wanted but when I add additional "Value" column doesnt work: $output | %{$n=$_.InstanceId; $_.Key; $_.Value | select @{Name="InstanceID";Expression={$n}},@{Name="Key";Expression={$_}},@{Name="Value";Expression={$_}}} Any idea why it doesnt work?
JohnLBevan
ps. I've created a cmdlet which may help (i.e. you can just call the cmdlet rather than having to tweak the more complex code above: codereview.stackexchange.com/questions/94509/… - not yet perfect, but being on code review its imperfections will soon be highlighted / can be resolved (or a better alternative found).
|
lang-bash