gpt4 book ai didi

powershell - 从 powershell 对象中选择元素

转载 作者:行者123 更新时间:2023-12-05 03:22:49 25 4
gpt4 key购买 nike

大家好!

小问题:

为什么这样做:

(Get-CimClass Win32_Share).CimClassMethods['Create'].Parameters

但这不是:

(Get-CimClass Win32_Share).CimClassMethods.Create.Parameters

可以通过以下方式实现相同的结果:

   ((Get-CimClass Win32_Share).CimClassMethods|where-object {$_.name -match 'create'}).parameters

根据相同的逻辑,我希望同样适用于:

(Get-command *help*)['get-help']
Or
(Get-command *help*)['cmdlet']
Or
(Get-childitem)['test.txt']

但事实并非如此。此处只能使用带有 where-object 的方法

其他注意事项:

我知道这应该是从哈希表而不是 pscustomobject 中检索项目的默认方法,但我也想更好地了解我还可以在哪些地方使用此方法。我在谷歌上搜索了一整天,但没有找到任何东西。

提前致谢佛朗哥

最佳答案

基于字符串的索引(['Create']) 有效,因为 Microsoft.Management.Infrastructure.Internal .Data.CimMethodDeclarationCollection 类型,它适用于实现具有 [string]参数化 Item 属性 -输入的参数(抽象化;使用 Get-Member Item -InputObject Get-CimClass Win32_Share).CimClassMethods 验证:

# {get;} indicates that the property is read-only.
Item ParameterizedProperty <T> Item(string key) {get;}

注意:严格来说,要接受像['Create']这样的东西,Item属性参数是就足够了[object] 类型,例如,非泛型 [hashtable] 类型就是这种情况。

对于具有此类方法的类型,PowerShell 与 C# 一样,支持语法 ['Create'] 作为 .Item('Create') 的语法糖 暗示是执行基于键的项目查找

通常,此类类型还实现了 IDictionary 接口(interface)(例如,[hasthable]),但此处并非如此。

CimMethodDeclarationCollection行为类似于 [ordered] hashtable ,因为它同时支持位置(例如,[0])和基于的索引(例如,['Create' ]),[1] 但有一个关键区别:

  • PowerShell 枚举管道中的 IDictionary 实现类型(您必须调用 .GetEnumerator() 来实现) ,而 CimMethodDeclarationCollection - 由于未实现 IDictionary - 枚举,就像数组等其他集合一样;也就是说,它的元素/条目通过管道一个一个地发送。

至于为什么像下面这样的东西不起作用:

(Get-command help)['get-help']

Get-command *help* 输出 多个 对象,(...) 自动收集在 常规 PowerShell 数组中,类型为 [object[]]

[object[]](基于 System.Array ),是否具有支持 ['get-help'] 的必要参数化属性 语法 - 数组仅支持 位置 索引(例如 [0] 引用第一个元素),基于 >参数化的 Item 属性,其参数为 [int]-typed,作为 IList 的一部分实现接口(interface)(抽象化;使用 Get-Member Item -InputObject @() 验证):

# Note: IList.Item indicates that the property is implemented
# as part of the IList interface.
# {get;set;} indicates that the property is read-write.
Item ParameterizedProperty <T> IList.Item(int index) {get;set;}

但是,鉴于 PowerShell 的 member-access enumeration feature可以合理地期望 ['get-help'] 应用于数组的单个元素,因为它是如何与 一起工作的。member-access operator (例如,(Get-Command *help*).Name)。
但是,从 PowerShell 7.2.4 开始,只有 . 而不是 ["someKey"] 执行此枚举;这种令人惊讶的不对称性是 GitHub issue #17514 的主题.


[1] [int] 类型的键不一定暗示位置语义,但在上下文中实现 IListICollection 接口(interface)(或其通用等效项)。

关于powershell - 从 powershell 对象中选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72618838/

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