我有一个通过普通 Get-ChildItem 获得的非常大的对象数组,我需要能够通过各种不同的属性对它们进行索引。我有一组哈希表,我已经制作了这些哈希表,可以通过这些属性对它们进行索引,但现在它只是一堆必须单独构建和管理的集合。有一次我想到,将哈希表作为“ByPath”“ByGuid”等属性添加到基础集合中会很好。构建它的代码只是将我已经拥有的各个语句组合在一起:
$items = Get-ChildItem -recurse blahblah
$items | Add-Member -membertype NoteProperty -name "ByGuid" -value (Get-ItemsByGuid)
$items | Add-Member -memberType NoteProperty -name "ByPath" -value (Get-ItemsByPath)
$items
不幸的是,虽然这不会导致执行,但它什么也没做。这些属性存在并且可以通过 Get-Member 看到,但它们在询问时始终为 null,并在之后设置时抛出。
Property 'ByGuid' cannot be found on this object; make sure it exists and is settable.
At line:1 char:14
+ $items. <<<< ByGuid = $itemsByGuid
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
谎言!
根据我正在尝试做的事情,是否有任何理由认为这不可能?还是有什么原因导致我收到奇怪的混合消息?
最佳答案
是的,这是可能的,而且您走在正确的轨道上。请记住,管道会枚举集合(包括数组)。您需要考虑该枚举,否则您最终会将属性添加到数组中的每个项目而不是数组本身。您可以像这样使用逗号运算符来解决此枚举:
$items = ,$items | Add-Member NoteProperty ByGuid (Get-ItemsByGuid) -PassThru
$items = ,$items | Add-Member NoteProperty ByPath (Get-ItemsByPath) -PassThru
请注意,如果您想使用 Get-Member
检查 $items 数组中的成员,您需要使用相同的技巧:
,$items | Get-Member
,
运算符只是将目标包装在另一个数组中,其中目标是唯一的元素。当管道枚举这个新数组时,我们将原始数组作为管道的唯一输出。
关于collections - 是否可以在 powershell 中向集合添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5213218/