我正在尝试使用另一个对象的数据输入创建一个新的自定义对象。
$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
我想创建一个新的PSobject $o
,其中第4列名为PendingShutdown
,这是一个布尔值。
id name status pendingshutdown -- ---- ------ --------------- j-12345 cluster1 running False j-4567 cluster2 running False
我试过这个:
$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行。如何使对象看起来像上面我想要的对象?
答案 0 :(得分:2)
您需要遍历每个群集对象。您可以遍历它们并将列添加到当前对象,例如:
$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
}
}
答案 1 :(得分:2)
只需使用calculated properties向管道中的对象添加属性,例如像这样:
$runningclusters = $clusters | Where-Object {
$_.Status.State -eq "Running" -or
$_.Status.State -eq "Waiting"
} | Select-Object *,@{n='PendingShutdown';e={$false}}