2016-09-20 50 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' –