【问题标题】:Dynamically retrieve class information in Powershell在 Powershell 中动态检索类信息
【发布时间】:2021-06-17 19:40:17
【问题描述】:

所以这个问题很简单,但我不知道如何措辞才能找到答案。

我正在尝试访问一个类,即[MyCustomClass] 以检查静态属性,但我需要动态地进行。如何注入[$className]之类的类名?

或者是否有任何 cmdlet 或 .NET 类函数可以用于此目的?我尝试搜索Get-Command *Class* 和一些类似的命令,但没有找到任何东西。

【问题讨论】:

    标签: .net powershell class static


    【解决方案1】:

    有 2 个主要选项可用于按名称解析给定类型,每个选项的行为略有不同:

    1. 使用转换为[type]:
    $className = 'MyCustomClass'
    $myType = [type]$className
    

    尝试强制转换不存在的类型名称将引发异常:

    PS ~> [type]'Not actually a type'
    Cannot convert the "Not actually a type" value of type "System.String" to type "System.Type".
    At line:1 char:1
    + [type]'Not actually a type'
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvalidCastFromStringToType
    
    1. 使用 -as 类型转换运算符(在 PowerShell 版本 3.0 中引入):
    $myType = 'MyCustomClass' -as [type]
    

    与强制转换不同,-as 运算符 从不 抛出 - 它只是返回 $null:

    PS ~> $myType = 'this does not exist' -as [type]
    PS ~> $null -eq $myType
    True
    

    这两者的共同点是您现在可以解析[MyCucstomClass] 的静态成员:

    $myType::MyProperty
    

    静态成员运算符:: 也适用于instance 引用,因此如果您有[MyCustomClass] 类型的对象,请使用它来代替类型文字:

    class MyClass
    {
      static [string] $StaticValue = 'Static string value'
    }
    
    PS ~> $instance = [MyClass]::new()
    PS ~> $instance::StaticValue
    Static string value
    

    【讨论】:

      【解决方案2】:

      您可以使用Invoke-Expression 来运行您仍然需要构建的东西:

      $class = 'DateTime'
      Invoke-Expression "[$class]::Now"
      

      【讨论】:

      • 义务人警告;这是一个可以使用更好替代方案的经典示例:Invoke-Expression (iex) 通常应该避免并且仅作为最后手段使用,因为它具有固有的安全性风险。简而言之:如果可能的话,避免它,因为通常有更好的替代品。如果真的别无选择,请仅在您自己提供或完全信任的输入中使用它 - 请参阅this answer。
      • 这可能会附带一个关于将不受信任的输入传递给 Invoke-Expression 的警告 :-)
      • 这两个 cmets 都是绝对正确的 - 使用先生。 Jenssen 在任何实际用例中的回答。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      相关资源
      最近更新 更多