Powershell:对象的对象上的格式表?

Powershell:对象的对象上的格式表?,powershell,powershell-5.0,Powershell,Powershell 5.0,我有一个PSCustomObjects数组列表,可以用Format表输出,看起来像预期的那样 Name Property1 Property2 Property3 ---- --------- --------- --------- name1 value1 value2 value3 现在,PSCustomObject的一个属性需要包含两个(或多个)值,因此我决定采用面向对象的方法,将该属性也更改为PSCustomObject,最终生成包含

我有一个PSCustomObjects数组列表,可以用Format表输出,看起来像预期的那样

Name    Property1   Property2   Property3
----    ---------   ---------   ---------
name1   value1      value2      value3
现在,PSCustomObject的一个属性需要包含两个(或多个)值,因此我决定采用面向对象的方法,将该属性也更改为PSCustomObject,最终生成包含对象的对象列表,然后输出如下所示:

Name    Property1   Property2                     Property3
----    ---------   ---------                     ---------
name1   value1      @{Sub1=valueX; Sub2=valueY}   value3
Name    Property1   Sub1     Sub2     Property3
----    ---------   ----     ----     ---------
name1   value1      valueX   valueY   value3
我要搜索的是Format Table的某种递归输出,它将内部对象展开,如下所示:

Name    Property1   Property2                     Property3
----    ---------   ---------                     ---------
name1   value1      @{Sub1=valueX; Sub2=valueY}   value3
Name    Property1   Sub1     Sub2     Property3
----    ---------   ----     ----     ---------
name1   value1      valueX   valueY   value3
这有可能吗? 或者在建立对象列表时,我必须回退到“正常”列表吗


谢谢大家!

您需要递归地做的就是发现叶值的“路径”,然后为它们生成属性表达式选择器:

function Format-FlatTable {
  [CmdletBinding()]
  param(
    [Parameter(ValueFromPipeline=$true)]
    [psobject]$InputObject
  )

  begin {
    function Get-FlatSelector {
      param(
        [psobject]$Object,
        [string]$Prefix
      )

      # Enumerate all properties
      $object.psobject.Properties |ForEach-Object {
        # Nested custom object, let's recurse
        if($_.Value -is [System.Management.Automation.PSCustomObject]){
          Get-FlatSelector $_.Value -Prefix $_.Name 
        }
        else {
          if($prefix){
            # We're not at the root level anymore, construct a property expression table
            @{Name="$prefix.$($_.Name)";Expression=[scriptblock]::Create("`$_.$prefix.$($_.Name)")}
          }
          else{
            # Still at the root level, we can select value properties by name alone
            $_.Name
          }
        }
      }
    }
  }

  process
  {
    # Use the first input object to determine how to flatten
    $selectors = Get-FlatSelector $InputObject[0]

    # Use `Format-Table` to only select flattened property values
    $InputObject |Format-Table $selectors
  }
}
这将生成与所需格式类似的表格式,但不会产生任何命名冲突:

[pscustomobject]@{
Name='Name1'
属性1='value1'
Property2=[pscustomobject]@{
Sub1='valueX'
Sub2=‘ValueY’
}
Property3='value3'
}|格式平台
输出:

Name  Property1 Property2.Sub1 Property2.Sub2 Property3
----  --------- -------------- -------------- ---------
Name1 value1    valueX         ValueY         value3

我正在考虑一个内置的解决方案,但感谢您提供的代码