bwe*_*rks 2 collections powershell properties
我有一个非常大的对象数组,由正常的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
Run Code Online (Sandbox Code Playgroud)
不幸的是,虽然这不会执行,但它没有做任何事情.这些属性存在并且可以通过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
Run Code Online (Sandbox Code Playgroud)
请注意,如果要使用$ items数组检查成员,则Get-Member需要使用相同的技巧:
,$items | Get-Member
Run Code Online (Sandbox Code Playgroud)
的,操作者只需包装了目标在另一阵列,其中所述目标是唯一的元件.当管道枚举这个新数组时,我们将原始数组作为管道的唯一输出.
| 归档时间: |
|
| 查看次数: |
4107 次 |
| 最近记录: |