【发布时间】:2021-10-02 13:33:31
【问题描述】:
谁能解释使用 Add-Member 向 PSCustomObject 对象添加属性时出现的奇怪行为?出于某种原因,一旦您添加了成员,该对象在显示时就会像 hashtable 一样表示,即使它仍然是 PSCustomObject,例如:
创建一个简单的对象:
[PSCustomObject] $test = New-Object -TypeName PSCustomObject -Property @{ a = 1; b = 2; c = 3; }
检查它的类型:
$test.GetType();
...返回:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object
然后获取它的内容:
$test;
...返回:
c b a
- - -
3 2 1
添加属性:
Add-Member -InputObject $test -MemberType NoteProperty -Name d -Value 4 -TypeName Int32;
确认其类型没有改变:
$test.GetType();
...返回:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object
最后,再次获取它的内容:
$test;
...返回:
@{c=3; b=2; a=1; d=4}
而我希望得到:
c d b a
- - - -
3 4 2 1
欢迎任何想法,因为我多年来一直在挑选。
非常感谢
【问题讨论】:
-
在构造函数的哈希表中有一个分号。应该是:
@{ a = 1; b = 2; c = 3 }
标签: powershell pscustomobject add-member