user189198
user189198

Reputation:

PowerShell type cast using type stored in variable

I'd like to cast a .NET object to another .NET type, but:

How would you achieve this?

For example, this is the "PowerShell" way to do it, but I don't want to use -as:

$TargetType = [System.String]; # The type I want to cast to
1 -as $TargetType;             # Cast object as $TargetType

Unfortunately, this does not work:

$TargetType = [System.String];
[$TargetType]1;

.. because PowerShell does not allow the use of variables inside the square brackets, in this scenario.

I am imagining something like:

$TargetType = [System.String];
$TargetType.Cast(1); # Does something like this exist in the .NET framework?

Can it be done with .NET method syntax? Is there a static method that does this?

Upvotes: 4

Views: 4039

Answers (1)

Jason Shirk
Jason Shirk

Reputation: 8019

You can roughly emulate a cast using the following method:

[System.Management.Automation.LanguagePrimitives]::ConvertTo($Value, $TargetType)

A true cast may behave differently than the above method for dynamic objects that provide their own conversions. Otherwise, the only other difference I can think of is performance - a true cast may perform better because of optimizations not available in the ConvertTo static method.

To precisely emulate a cast, you'll need to generate a script block with something like:

function GenerateCastScriptBlock
{
    param([type]$Type)

    [scriptblock]::Create('param($Value) [{0}]$Value' -f
        [Microsoft.PowerShell.ToStringCodeMethods]::Type($Type))
}

You can then assign this script block to a function or invoke it directly, e.g.:

(& (GenerateCastScriptBlock ([int])) "42").GetType()

Upvotes: 7

Related Questions