Powershell 创建引用其他对象的自定义对象

Powershell 创建引用其他对象的自定义对象,powershell,amazon-web-services,tagging,psobject,Powershell,Amazon Web Services,Tagging,Psobject,我正在尝试使用另一个对象的数据输入创建一个新的自定义对象 $clusters = Get-EMRClusters $runningclusters = $clusters | Where-Object { $_.Status.State -eq "Running" -or $_.Status.State -eq "Waiting" } $runningclusters看起来像 id name status -- ---

我正在尝试使用另一个对象的数据输入创建一个新的自定义对象

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

id name status -- ---- ------ j-12345 cluster1 running j-4567 cluster2 running 我已尝试运行此:

$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

但是我对
$o
id
name
的输出只是对象本身,而不是id行。如何使一个对象看起来像上面我想要的对象?

您需要遍历每个集群对象。您可以循环浏览它们并将列添加到当前对象,如:

$runningclusters = $clusters |
Where-Object {$_.Status.State -eq "Running" -or $_.Status.State -eq "Waiting"} |
Add-Member -NotePropertyName pendingshutdown -NotePropertyValue $true -PassThru
或者可以为每个集群创建新对象。例:

$MyNewClusterObjects = $runningclusters | ForEach-Object {
    New-Object -TypeName psobject -Property @{
        id = $_.id
        name = $_.name
        status = $_.status.state
        PendingShutdown = $true
    }
}

您需要循环遍历每个集群对象。您可以循环浏览它们并将列添加到当前对象,如:

$runningclusters = $clusters |
Where-Object {$_.Status.State -eq "Running" -or $_.Status.State -eq "Waiting"} |
Add-Member -NotePropertyName pendingshutdown -NotePropertyValue $true -PassThru
或者可以为每个集群创建新对象。例:

$MyNewClusterObjects = $runningclusters | ForEach-Object {
    New-Object -TypeName psobject -Property @{
        id = $_.id
        name = $_.name
        status = $_.status.state
        PendingShutdown = $true
    }
}
仅用于向管道中的对象添加属性,例如:

$runningclusters = $clusters | Where-Object {
    $_.Status.State -eq "Running" -or
    $_.Status.State -eq "Waiting"
} | Select-Object *,@{n='PendingShutdown';e={$false}}
仅用于向管道中的对象添加属性,例如:

$runningclusters = $clusters | Where-Object {
    $_.Status.State -eq "Running" -or
    $_.Status.State -eq "Waiting"
} | Select-Object *,@{n='PendingShutdown';e={$false}}

非常感谢。对于第二种方法,列按
status,pendingshutton,name,id
的顺序返回,而不是按
id,name,status,pendingshutton
的所需顺序返回。有没有办法使对象与指定的顺序行匹配?在创建对象之前,先创建哈希表作为一个表。正如Ansgar所说。。。或者将最后一行更改为
}|选择对象id、名称、状态、挂起关闭
谢谢!对于第二种方法,列按
status,pendingshutton,name,id
的顺序返回,而不是按
id,name,status,pendingshutton
的所需顺序返回。有没有办法使对象与指定的顺序行匹配?在创建对象之前,先创建哈希表作为一个表。正如Ansgar所说。。。或者将最后一行更改为
}|选择对象id、名称、状态、挂起关闭