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

PowerShell两种创建PSCustomObject方式的显示差异原因咨询

为什么两种PowerShell自定义对象创建方式的输出格式不同?

先看你遇到的两种场景:

方式一:输出Name/Value列

[pscustomobject]$obj = @{"Colour" = "Blue"; "Car" = "Volkswagen"}
$obj

输出:

Name                           Value
----                           -----
Car                            Volkswagen
Colour                         Blue

方式二:直接显示对象属性

$obj = [pscustomobject]@{"Colour" = "Blue"; "Car" = "Volkswagen"}
$obj

输出:

Colour Car       
------ ---       
Blue   Volkswagen

核心原因:类型转换的逻辑差异

  • 方式一:你先创建了一个标准的[hashtable](哈希表),然后试图通过类型标注[pscustomobject]强制转换。但PowerShell的赋值逻辑里,这种写法并不会把哈希表转换成PSCustomObject——最终$obj还是哈希表类型。而哈希表在PowerShell中的默认输出格式就是以Name/Value列展示键值对。
  • 方式二:这里是直接调用[pscustomobject]的类型构造函数,把哈希表作为参数传入,直接生成真正的PSCustomObject实例。这种对象的属性对应哈希表的键,值对应哈希表的值,所以输出时会直接展示属性列和对应内容。

验证方式

你可以用GetType()查看两种方式下变量的实际类型:

# 方式一的类型
[pscustomobject]$obj1 = @{"Colour" = "Blue"; "Car" = "Volkswagen"}
$obj1.GetType().FullName  # 输出:System.Collections.Hashtable

# 方式二的类型
$obj2 = [pscustomobject]@{"Colour" = "Blue"; "Car" = "Volkswagen"}
$obj2.GetType().FullName  # 输出:System.Management.Automation.PSCustomObject

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:05:26