0

I am trying to create a new custom object with data input from another object.

$clusters = Get-EMRClusters 
$runningclusters = $clusters | Where-Object {
    $_.Status.State -eq "Running" -or
    $_.Status.State -eq "Waiting"
}

$runningclusters looks like

id            name        status
--            ----        ------
j-12345       cluster1    running
j-4567        cluster2    running

I want to create a new PSobject $o with a 4th column named PendingShutdown that's a boolean.

id            name        status    pendingshutdown
--            ----        ------    ---------------
j-12345       cluster1    running   False
j-4567        cluster2    running   False

I have tried running this:

$o = New-Object PSObject
$o | Add-Member -NotePropertyName id -NotePropertyValue $runningclusters.id
$o | Add-Member -NotePropertyName name -NotePropertyValue $runningclusters.name
$o | Add-Member -NotePropertyName status -NotePropertyValue $runningclusters.status.state
$o | Add-Member -NotePropertyName PendingShutdown -NotePropertyValue $true

But my output for $o for the columns id and name are just objects themselves, not rows of IDs. How do I make an object to look like my desired object above?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Montel Edwards
  • 400
  • 5
  • 14

2 Answers2

2

You need to loop through each of the cluster-objects. You can loop through them and add the column to the current object, like:

$runningclusters = $clusters |
Where-Object {$_.Status.State -eq "Running" -or $_.Status.State -eq "Waiting"} |
Add-Member -NotePropertyName pendingshutdown -NotePropertyValue $true -PassThru

Or you could create new objects per cluster. Ex:

$MyNewClusterObjects = $runningclusters | ForEach-Object {
    New-Object -TypeName psobject -Property @{
        id = $_.id
        name = $_.name
        status = $_.status.state
        PendingShutdown = $true
    }
}
Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • Thank you! For the second method, the columns are returned in the order of `status,pendingshutdown, name, id` not the desired order of `id, name, status, pendingshutdown`. Is there a way to make the object match the row of the orders specified? – Montel Edwards Mar 19 '17 at 19:05
  • Create the hashtable as an [ordered hashtable](http://stackoverflow.com/a/39521208/1630171) before creating the object. – Ansgar Wiechers Mar 19 '17 at 19:13
  • As Ansgar said... or change the last line to `} | Select-Object id, name, status, pendingshutdown` – Frode F. Mar 19 '17 at 19:18
2

Simply use calculated properties for adding properties to objects in a pipeline, e.g. like this:

$runningclusters = $clusters | Where-Object {
    $_.Status.State -eq "Running" -or
    $_.Status.State -eq "Waiting"
} | Select-Object *,@{n='PendingShutdown';e={$false}}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328