gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:14:41 24 4
gpt4 key购买 nike

我正在尝试在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

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

最佳答案

我在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" }

关于powershell - Powershell,在哈希表中丢失自定义对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18239673/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com