【问题标题】:Can't display PSObject无法显示 PSObject
【发布时间】:2016-09-20 12:09:18
【问题描述】:

我正在尝试在 PSObject 中显示我的脚本生成的一些数据,这样我就可以导出到 CSV,但唯一显示的对象是我首先添加到数组中的那个。

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

我也试过这个,但我在表格中显示一个空行,其中值不在该列中,这是我不想要的:

$pass=@("1","2","3")
$fail=@("4")
$obj=@()
$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。

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案1】:

    另一个答案是正确的——你使用了错误的对象。话虽如此,这里有一个功能可以帮助您错误地使用它们!

    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
    }
    
    $pass=@("1","2","3")
    $fail=@("4")
    
    New-BadObjectfromArray -array1 $fail -array2 $pass -array1name "Fail" -array2name "Pass"
    

    【讨论】:

    • 我收到一个异常:Index was outside the bounds of the array.
    • 我又跑了一次——我的必须默默地继续——你至少得到输出了吗?
    • 如果我将 $ErrorActionPreference 设置为 SilentlyContinue,我只会收到一行:Fail Pass ---- ---- 4 1
    • 喜欢函数名xD
    • $PSVersionTable.PSVersion.Major ?我的是 5 岁。
    【解决方案2】:

    正如您自己发现的那样,PowerShell 仅输出数组中 第一项 的属性。它并非设计来以您使用它的方式打印您期望的输出。


    作为一种解决方法,您可以使用for 循环来“构建”您想要的输出:

    $pass=@("1","2","3")
    $fail=@("4")
    $obj=@()
    
    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     
    

    【讨论】:

    • 不客气。请注意,如果 $pass.count 小于 $fail.count,您将不会看到所有记录。如果是这种情况,您必须使用脚本。
    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 2016-01-27
    • 2017-01-12
    • 2013-06-19
    • 2020-02-01
    • 2019-08-28
    相关资源
    最近更新 更多