简体   繁体   English

动态获取Powershell中的class信息

[英]Dynamically retrieve class information in Powershell

So the question is fairly simple but I'm not sure how to word it in order to find the answer.所以这个问题相当简单,但我不确定如何表达才能找到答案。

I'm trying to access a class ie [MyCustomClass] in order to check static properties but I need to do it dynamically.我正在尝试访问 class 即[MyCustomClass]以检查 static 属性,但我需要动态执行。 How do I inject the class name like [$className] ?如何注入[$className]之类的 class 名称?

Or are there any cmdlets or .NET class functions I can use for this purpose?或者是否有任何 cmdlet 或 .NET class 函数可以用于此目的? I tried searching Get-Command *Class* and some similar commands but am not coming up with anything.我尝试搜索Get-Command *Class*和一些类似的命令,但没有找到任何结果。

There are 2 primary options for resolving a given type by name, each with slightly different behavior:有 2 个主要选项可用于按名称解析给定类型,每个选项的行为略有不同:

  1. Using a cast to [type] :使用强制转换为[type]
$className = 'MyCustomClass'
$myType = [type]$className

Attempting to cast a non-existing type name will throw an exception:尝试转换不存在的类型名称将引发异常:

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. Using the -as type conversion operator (introduced in PowerShell version 3.0):使用-as类型转换运算符(在 PowerShell 3.0 版本中引入):
$myType = 'MyCustomClass' -as [type]

Unlike casting, the -as operator never throws - it simply returns $null :与强制转换不同, -as运算符从不抛出 - 它只是返回$null

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

Common for both of these is that you can now resolve the static members of [MyCucstomClass] :这两者的共同点是您现在可以解析[MyCucstomClass]的 static 成员:

$myType::MyProperty

The static member operator :: also works on instance references, so if you have an object of type [MyCustomClass] , use that in place of a type literal: static 成员运算符::也适用于实例引用,因此如果您有类型为[MyCustomClass]的 object,请使用它代替类型文字:

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

You can use Invoke-Expression to run something you still have to build:您可以使用Invoke-Expression来运行您仍然需要构建的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM