如何反转pscustomobject的属性?

时间:2018-03-15 07:28:31

标签: arrays powershell stack reverse

是否可以撤消[Pscustomobject]

的属性

我必须按队列顺序设置资源。测试结束后,我必须按相反的顺序拆除资源。

下面是示例代码。

$volume= @{Name='Vol1';size = "100gb"}
$VolumeCollection = @{Name = 'VolColl'; Volume = $volume}
$ResourceQueue = [pscustomobject]@{
    Volume = $Volume
    VolumeCollection = $VolumeCollection
}

function SEtup-Resources
{
    param
    (
        [psobject]$resource
    )

    $resource.PSObject.Properties | foreach-object {
        switch ($_.name) {
            "volume" { 
                "Volume is created"
            }
            "VolumeCollection" {
                "volcoll is created"
            }
        }
    }
}

function TearDown-Resources
{
    param
    (
        [psobject]$resource
    )

    # I have to reverse the object properties

    $resource.PSObject.Properties | foreach-object {
        switch ($_.name) {
            "volume" { 
                "Volume is deleted"
            }
            "VolumeCollection" {
                "volcoll is deleted"
            }
        }
    }
}

Write-host "-------------------------"
Write-host "Setup resources"
Write-host "-------------------------"
SEtup-Resources -resource $ResourceQueue

Write-host "-------------------------"
Write-host "teardown resources"
Write-host "-------------------------"
TearDown-Resources -resource $ResourceQueue

结果应为

-------------------------
Setup resources
-------------------------
Volume is created
volcoll is created
-------------------------
teardown resources
-------------------------
volcoll is deleted
volume is deleted

但我无法找到扭转对象属性的方法。如何在PowerShell中反转pscustomobject属性?

2 个答案:

答案 0 :(得分:2)

如果您只需要更改少数属性的顺序,您可以手动将它们列为Select-Object

$ResourceQueue | Select-Object VolumeCollection, Volume

对于更通用的解决方案,可以使用Get-Member来获取属性数组,使用[Array]::reverse来反转 然后按Select-Object按顺序获取属性。我出来了:

$props = @()
$MyObject | Get-Member | ForEach-Object { $props += $_.name }
[Array]::Reverse($props)
$MyObject | Select-Object $props

答案 1 :(得分:1)

你可以这样做:

$object = '' | select PropertyA, PropertyB, PropertyC
$object.PropertyA = 1234
$object.PropertyB = 'abcd'
$object.PropertyC = 'xyz'
$properties = ($object | Get-Member -MemberType NoteProperty).Name
[Array]::Reverse($properties)
$object | select $properties

结果是

PropertyC PropertyB PropertyA
--------- --------- ---------
xyz       abcd           1234