检查属性是否为PowerShell v3中的PSCustomObject



我创建了一个PSCustomObject数组,其中包含几个属性。有些属性是整型,有些是字符串,还有一些是我猜测的字典对象(对象是从Invoke-RestMethod返回的)。下面是一个例子:

> $items[0]
id       : 42
name     : Modularize the widget for maximum reuse
priority : {[id, 1], [order, 1], [name, High]}
project  : {[id, 136], [name, Wicked Awesome Project]}

最后,我想做的是"扁平化"这个结构,这样我就可以管道到Export-CSV并且保留所有数据。每个属性将成为一列。例子:

id             : 42
name           : Modularize the widget for maximum reuse
priority_id    : 1
priority_order : order
priority_name  : High
project_id     : 135
project_name   : Wicked Awesome Project

所以,我的想法是枚举属性,如果任何一个是Dictionary/HashTable/PSCustomObject枚举它的属性,并将它们添加到父属性中,以平展此结构。

然而,我还不能成功地推断属性是否为Dictionary/HashTable/PSCustomObject。我像这样遍历所有属性。

 foreach($property in $item.PsObject.Properties)
 {
     Write-Host $property
     Write-Host $property.GetType()
     Write-Host "-------------------------------------------------------------"
     # if a PSCustomObject let's flatten this out
     if ($property -eq [PsCustomObject])
     {
        Write-Host "This is a PSCustomObject so we can flatten this out"
     }
     else
     {
        Write-Host "Use the raw value"
     }
 }

对于看起来是PSCustomObject的属性,它会打印出以下内容:

 System.Management.Automation.PSCustomObject project=@{id=135}
 System.Management.Automation.PSNoteProperty
 -------------------------------------------------------------

然而,我无法有条件地检查这是PSCustomObject。我尝试过的所有条件都属于else条件。我已经尝试用[Dictionary]和[HashTable]替换[PSCustomObject]。注意,检查类型是没有用的,因为它们看起来都是PSNoteProperty。

我如何检查属性实际上是一个PSCustomObject,因此需要被扁平化?

下面的代码将决定一个PSCustomObject的属性是否也是一个PSCustomObject。

foreach($property in $item.PsObject.Properties)
{
    Write-Host $property
    Write-Host $property.GetType()
    Write-Host "-------------------------------------------------------------"
    # if a PSCustomObject let's flatten this out
    if ($property.TypeNameOfValue -eq "System.Management.Automation.PSCustomObject")
    {
       Write-Host "This is a PSCustomObject so we can flatten this out"
    }
    else
    {
       Write-Host "Use the raw value"
    }
}

要检查变量是否为给定类型,不应该使用比较运算符-eq,而应该使用类型运算符-is:

$psc = New-Object -TypeName PSCustomObject
if ($psc -is [System.Management.Automation.PSCustomObject]) {
    'is psc'
}
if ($psc -is [Object]) {
    'is object'
}
if ($psc -is [int]) {
    'is int'
} else { 
    "isn't int"
}

最新更新