我有一个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来枚举它的属性,并将它们添加到parent属性以展平这个结构。
但是,我无法成功推断属性是否为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
-------------------------------------------------------------
但是,我无法有条件地检查这个ia PSCustomObject。我尝试的所有条件都属于其他条件。我试过用[Dictionary]和[HashTable]替换[PSCustomObject]。请注意,检查类型不会有帮助,因为它们看起来都是PSNoteProperty。
如何检查属性实际上是PSCustomObject,因此需要展平?
答案 0 :(得分:2)
以下代码将确定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"
}
}
答案 1 :(得分:0)
要检查变量是否属于给定类型,您不应该使用比较运算符-eq
,而是键入operator -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"
}