【问题标题】:Create a custom object referencing other objects创建引用其他对象的自定义对象
【发布时间】:2017-03-19 18:45:04
【问题描述】:

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

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

$runningclusters 看起来像

id 名称状态
-- ---- ------
j-12345 cluster1 正在运行
j-4567 cluster2 正在运行

我想创建一个新的 PSobject $o,其第 4 列名为 PendingShutdown,它是一个布尔值。

id 名称状态pendingshutdown
-- ---- ------ ---------------
j-12345 cluster1 运行 False
j-4567 cluster2 运行 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

但我对$oidname 列的输出只是对象本身,而不是ID 行。如何使对象看起来像上面我想要的对象?

【问题讨论】:

    标签: powershell amazon-web-services tagging psobject


    【解决方案1】:

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

    $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
        }
    }
    

    【讨论】:

    • 谢谢!对于第二种方法,列按status,pendingshutdown, name, id 的顺序返回,而不是id, name, status, pendingshutdown 的所需顺序。有没有办法使对象与指定的订单行匹配?
    • 在创建对象之前将哈希表创建为ordered hashtable
    • 正如 Ansgar 所说...或将最后一行更改为} | Select-Object id, name, status, pendingshutdown
    【解决方案2】:

    只需使用calculated properties 为管道中的对象添加属性,例如像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-12
      • 1970-01-01
      • 2015-03-31
      • 2018-04-19
      • 2023-03-21
      • 2017-04-22
      • 1970-01-01
      • 2020-02-27
      相关资源
      最近更新 更多