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
相关产品推荐
相关产品推荐

