You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell哈希表返回时无法显示全部列问题求助

问题解决:PowerShell自定义对象集合无法显示全部列

你的问题出在每个PSCustomObject只包含当前循环的动态属性,PowerShell输出对象集合时,默认会以第一个对象的属性列表作为显示列,后面对象的额外属性不会自动追加显示。

修改思路

要让所有列都显示,必须保证集合里的每个对象都包含全部需要的属性,对应行的属性赋值随机数,其他属性留空($null)。

修改后的脚本

Param(
    [array]$ArrayItem = ("Hello","to","the","World")
)
$inLine = @()
[int]$i=0

# 先定义所有要包含的属性:固定属性+所有动态列
$allProperties = @('Date', 'Title') + $ArrayItem

foreach ($item in $ArrayItem) {
    $RandomNum = Get-Random -Maximum 100
    Write-Host "$item - $RandomNum"

    # 初始化所有属性为$null,用[ordered]保证列顺序和预期一致
    $properties = [ordered]@{}
    foreach ($prop in $allProperties) {
        $properties[$prop] = $null
    }

    # 赋值固定属性和当前列的随机数
    $properties['Title'] = "Tracking-$i"
    $properties['Date'] = Get-Date -DisplayHint Time -Format "HH:mm:ss"
    $properties[$item] = $RandomNum

    $inLine += New-Object -TypeName PSCustomObject -Property $properties
    $i++
}
$inLine

输出效果

Date     Title      Hello to  the World
----     -----      ----- --  --- -----
16:02:34 Tracking-0    87
16:02:34 Tracking-1        45
16:02:34 Tracking-2            12
16:02:34 Tracking-3                78

关键修改点

  • 提前定义$allProperties包含所有要显示的列,确保每个对象都具备这些属性
  • 使用[ordered]保证属性顺序和你期望的一致(可选,但能让列顺序和$ArrayItem完全匹配)
  • 每个对象先初始化所有属性为$null,再赋值对应行的有效数据

内容的提问来源于stack exchange,提问作者chathae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 07:33:26