powershelladd-type

How do I conditionally add a class with Add-Type -TypeDefinition if it isn't added already?


Consider the following PowerShell snippet:

$csharpString = @"
using System;

public sealed class MyClass
{
    public MyClass() { }
    public override string ToString() {
        return "This is my class. There are many others " +
            "like it, but this one is mine.";
    }
}
"@
Add-Type -TypeDefinition $csharpString;
$myObject = New-Object MyClass
Write-Host $myObject.ToString();

If I run it more than once in the same AppDomain (e.g. run the script twice in powershell.exe or powershell_ise.exe) I get the following error:

Add-Type : Cannot add type. The type name 'MyClass' already exists.
At line:13 char:1
+ Add-Type -TypeDefinition $csharpString;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (MyClass:String) [Add-Type],
 Exception
    + FullyQualifiedErrorId :
 TYPE_ALREADY_EXISTS,Microsoft.PowerShell.Commands.AddTypeCommand

How do I wrap the call to Add-Type -TypeDefinition so that its only called once?


Solution

  • This technique works well for me:

    if (-not ([System.Management.Automation.PSTypeName]'MyClass').Type)
    {
        Add-Type -TypeDefinition 'public class MyClass { }'
    }
    

    Internally, the PSTypeName class calls the LanguagePrimitives.ConvertStringToType() method which handles the heavy lifting. It caches the lookup string when successful, so additional lookups are faster.

    I have not confirmed whether or not any exceptions are thrown internally as mentioned by x0n and Justin D.