title: How do I conditionally add a class with Add-Type -TypeDefinition if it isn't added already?
body: <p>Consider the following PowerShell snippet:</p>
  
  <pre><code>$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();
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>How do I wrap the call to <a href="http://ss64.com/ps/add-type.html">Add-Type</a> -TypeDefinition so that its only called once? </p>