Powershell,在哈希表中丢失自定义对象属性

时间:2013-08-14 18:38:44

标签: powershell

我正在尝试在PowerShell中创建自定义对象的集合,并将它们存储在哈希表中。问题是当我将对象放入哈希表时,自定义属性会消失。

$customObject = New-Object object

$customObject | Add-member -membertype noteproperty -name customValue -value "test"

Write-Host $customObject.customValue

$hashTable = @{}

$hashTable.add("custom", $customObject)

$object = $hashTable["custom"]

$object.customValue = 7

当我执行此代码时,我得到以下输出。

test
Property 'customValue' cannot be found on this object; make sure it exists and is settable.
At C:\temp\test2.ps1:15 char:9
+ $object. <<<< customValue = 7
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

在我将自定义属性放入集合后,有什么方法可以使用自定义属性吗?

1 个答案:

答案 0 :(得分:4)

我在64位Windows 7上使用PowerShell 3.0。在3.0中,您的代码按预期运行,但在2.0(powershell.exe -Version 2.0)中,我得到的错误与您相同。这个输出在2.0下真的很奇怪:

PS> [Object]::ReferenceEquals($customObject, $object)
True
PS> $customObject | Get-Member


   TypeName: System.Object

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
customValue NoteProperty System.String customValue=test


PS> $object | Get-Member


   TypeName: System.Object

Name        MemberType Definition
----        ---------- ----------
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
ToString    Method     string ToString()

因此,PowerShell同意它们是同一个对象,但只有一个具有customValue属性。我还注意到,如果我改变了将$customObject添加到$hashTable的方式......

$hashTable.add("custom", $customObject)

......对此...

$hashTable["custom"] = $customObject

...然后您的代码在PowerShell 2.0下按预期工作。因此,在调用Add()时似乎出现了问题,并且该行为必须已在3.0中修复。

另一种解决方法是更改​​第一行......

$customObject = New-Object object

......对此...

$customObject = New-Object PSObject

...并且您的代码在两个版本的PowerShell中都可以正常运行。然后,您可以将前两行缩短为此...

$customObject = New-Object PSObject -Property @{ customValue = "test" }