2013-02-27 73 views
1
PS C:\> $array 

ReadWrite(AllHostsSpecified) : 
ReadOnly(AllHostsSpecified) : 
ReadWrite(NegateSpecified) : 
ReadWrite(Negate)   : 
SecFlavor     : sys 
ActualPathname    : 
ReadOnly(AllHosts)   : 
ReadOnly(Name)    : 
ReadWrite(Name)    : 
Anon       : 
Root       : {vin1,vin2,vin3,vin4...} 
ReadOnly(NegateSpecified) : 
ReadWrite(AllHosts)   : 
NosuidSpecified    : False 
Nosuid      : 
ReadOnly(Negate)    : 
Pathname      : /vol/vin_binaries 

嗨,我有属性根这是一种动态性能和可从(VIN1,VIN2,VIN3,VIN4 .......)其也可以得到即使改变层出不穷。PowerShell中的迭代子属性的对象

现在,当我做一个出口CSV我需要得到的输出对象如下

ReadWrite(AllHostsSpecified) : 
ReadOnly(AllHostsSpecified) : 
ReadWrite(NegateSpecified) : 
ReadWrite(Negate)   : 
SecFlavor     : sys 
ActualPathname    : 
ReadOnly(AllHosts)   : 
ReadOnly(Name)    : 
ReadWrite(Name)    : 
Anon       : 
Root (Property 1)       : vin1 
Root (Property 1)       : vin2 
Root (Property 1)       : vin3 
Root (Property 1)       : vin4 
. 
. 
. 
. 

Root (Property n)       : vinn 

ReadOnly(NegateSpecified) : 
ReadWrite(AllHosts)   : 
NosuidSpecified    : False 
Nosuid      : 
ReadOnly(Negate)    : 
Pathname      : /vol/vin_binaries 

是有这个可以实现的方式?像在for循环中遍历Root的所有属性?

回答

0

尝试这样:

filter ExpandProperties { 
    $obj = $_ 
    $obj | gm -MemberType *property | % { 
     #Find objects with array value 
     if(@($obj.($_.Name)).Count -gt 1) { 
      $count = 1 
      $prop = $_.Name 
      $obj.($prop) | % { 
       #Foreach value in the property 
       $obj | Add-Member NoteProperty -Name "$prop (Property $($count))" -Value $_ 
       $count++ 
      } 
     } 
    } 
    #Output object 
    $obj 
} 

$o1 = New-Object psobject -Property @{ 
    Name = @("Name1", "Name2") 
    Root = @("vin1","vin2") 
} 
$o2 = New-Object psobject -Property @{ 
    Name = "Name2" 
    Root = @("vin1","vin2","vin3") 
} 
$o = $o1, $o2 

$o | ExpandProperties 


Name    : {Name1, Name2} 
Root    : {vin1, vin2} 
Name (Property 1) : Name1 
Name (Property 2) : Name2 
Root (Property 1) : vin1 
Root (Property 2) : vin2 

Name    : Name2 
Root    : {vin1, vin2, vin3} 
Root (Property 1) : vin1 
Root (Property 2) : vin2 
Root (Property 3) : vin3 

这也显示了原始数组属性(如 “根”。)。如果你想排除它,你需要在函数内部使用select -exclude ...。但是,这会创建一个新的“pscustomobject”(你失去了原始的对象类型),所以我没有在上面的解决方案中包含这个。

+0

嗨格雷默,感谢您的回复,但我想在飞行中做到这一点..输出$ array – PowerShell 2013-02-27 06:54:43

+0

你不能在飞行中。 PowerShell使用数组来收集多个对象/值。你需要创建一个“过滤器”来完成这项工作。 Mine适合您的情况,但不应该很难将代码转换为检测并扩展所有分组属性。我没有powershell可用atm自己转换它。 – 2013-02-27 07:35:33

+0

忽略第一行,忘记删除它们。要使用数组扩展每个属性,您需要创建一个使用“get-member”来获取属性的“过滤器”,然后使用ex。 “计数”只获得具有数组值的道具,然后使用我的循环来扩展它们全部 – 2013-02-27 07:46:18