There are 2 primary options for resolving a given type by name, each with slightly different behavior:
- Using a cast to
[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
- Using the
-as
type conversion operator (introduced in PowerShell version 3.0):
$myType = 'MyCustomClass' -as [type]
Unlike casting, the -as
operator never throws - it simply returns $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]
:
$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:
class MyClass
{
static [string] $StaticValue = 'Static string value'
}
PS ~> $instance = [MyClass]::new()
PS ~> $instance::StaticValue
Static string value