2016-09-20 119 views
1

我试图显示一些数据,我的脚本在PSObject中生成,所以我可以导出到CSV,但唯一显示的对象是我先添加到数组中的那个对象。无法显示PSObject

[email protected]("1","2","3") 
[email protected]("4") 
[email protected]() 
$pass | % { 
    $obj+=New-Object PSObject -Property @{Pass=$_} 
} 
$fail | % { 
    $obj+=New-Object PSObject -Property @{Fail=$_} 
} 
$obj 

我也试过,但我得到其中值不在该列的表,这是我不希望显示一个空行:

[email protected]("1","2","3") 
[email protected]("4") 
[email protected]() 
$pass | % { 
    $obj+=New-Object PSObject -Property @{Pass=$_;Fail=""} 
} 
$fail | % { 
    $obj+=New-Object PSObject -Property @{Pass="";Fail=$_} 
} 
$obj 

我的期望结果:

Pass Fail 
---- ---- 
1  4 
2 
3 

我正在使用Powershell V2。

回答

0

当你自己想出来的时候,PowerShell只输出的第一项的属性。它的没有设计打印您正在使用它的方式期待的输出。


作为一种变通方法,您可以使用for圈 “建设” 所需输出:

[email protected]("1","2","3") 
[email protected]("4") 
[email protected]() 

for ($i = 0; $i -lt $pass.Count; $i++) 
{ 
    if ($fail.Count -gt $i) 
    { 
     $currentFail = $fail[$i] 
    } 
    else 
    { 
     $currentFail = "" 
    } 

    $obj+=New-Object PSObject -Property @{Fail=$currentFail;Pass=$pass[$i];} 
} 
$obj | select Pass, Fail 

输出:

Pass Fail 
---- ---- 
1 4 
2   
3  
+0

太好了,非常感谢。 –

+0

不客气。请注意,如果'$ pass.count'小于'$ fail.count',您将不会看到所有记录。如果情况可能如此,则必须采用脚本。 –

2

另一个答案是正确的 - 你”重新使用对象错误。这就是说,这里有一个函数可以帮助你使用它们!

Function New-BadObjectfromArray($array1,$array2,$array1name,$array2name){ 
    if ($array1.count -ge $array2.count){$iteratorCount = $array1.count} 
    else {$iteratorCount = $array2.count} 
    $obj = @() 
    $iteration=0 
    while ($iteration -le $iteratorCount){ 
     New-Object PSObject -Property @{ 
      $array1name=$array1[$iteration] 
      $array2name=$array2[$iteration] 
     } 
     $iteration += 1 
    } 
    $obj 
} 

[email protected]("1","2","3") 
[email protected]("4") 

New-BadObjectfromArray -array1 $fail -array2 $pass -array1name "Fail" -array2name "Pass" 
+0

我收到一个异常:'索引超出了数组的范围。' –

+0

我再次运行它 - 我必须默默继续 - 你至少得到了输出吗? –

+0

如果我设置了'$ ErrorActionPreference'为SilentlyContinue,我收到一张行: '不合格合格 ---- 4 1' –