如何用PowerShell单行代码枚举格式化Rest API返回的嵌套PSCustomObject
问题描述
通过Invoke-RestMethod调用Rest API后得到一个System.Management.Automation.PSCustomObject类型的变量,其成员信息如下:
TypeName: System.Management.Automation.PSCustomObject Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() ha NoteProperty System.Management.Automation.PSCustomObject ha=@{id=ha; name=ha; alias=(ha1); mac=80:80:2c:xx:xx:xx; ip=0.0.0.0; mask=0; link=True; speed=1000,0; duplex=1; tx_packets=151567878; ... modem NoteProperty System.Management.Automation.PSCustomObject modem=@{id=modem; name=modem; alias=; mac=00:00:00:00:00:00; ip=0.0.0.0; mask=0; link=False; speed=0,0; duplex=0; tx_packets=0; rx_pac... port1 NoteProperty System.Management.Automation.PSCustomObject port1=@{id=port1; name=port1; alias=(wan1); mac=80:80:2c:xx:xx:xx; ip=xxx.xxx.xxx.xxx; mask=28; link=True; speed=1000,0; duplex=1; tx_pa... port2 NoteProperty System.Management.Automation.PSCustomObject port2=@{id=port2; name=port2; alias=(wan2); mac=80:80:2c:xx:xx:xx; ip=xxx.xxx.xxx.xxx; mask=28; link=True; speed=1000,0; duplex=1; tx_pa...
需要用单行PowerShell代码对该变量进行枚举并格式化,得到如下格式的表格输出:
id name alias mac ip mask link speed duplex -- ---- ----- --- -- ---- ---- ----- ----- ha ha (ha1) 80:80:2c:xx:xx:xx 0.0.0.0 0 True 1000,0 1 modem modem 00:00:00:00:00:00 0.0.0.0 0 False 0,0 0 port1 port1 (wan1) 80:80:2c:xx:xx:xx xxx.xxx.xxx.xxx 28 True 1000,0 1 port2 port2 (wan2) 80:80:2c:xx:xx:xx xxx.xxx.xxx.xxx 28 True 1000,0 1
解决方案
使用以下单行PowerShell代码即可实现需求(将$yourResultVar替换为实际的结果变量名):
$yourResultVar | Get-Member -MemberType NoteProperty | ForEach-Object { $yourResultVar.$($_.Name) } | Format-Table id, name, alias, mac, ip, mask, link, speed, duplex -AutoSize
代码说明
Get-Member -MemberType NoteProperty:筛选出变量中所有存储端口信息的NoteProperty类型成员(即ha、modem、port1、port2)ForEach-Object { $yourResultVar.$($_.Name) }:遍历每个成员名称,取出对应的子对象Format-Table ... -AutoSize:将所有子对象按指定列名格式化为表格,并自动调整列宽适配内容
内容的提问来源于stack exchange,提问作者rga.cz
相关产品推荐
相关产品推荐

