PowerShell Add-Type : Cannot add type. already exist

You can execute it as a job:

$cmd = {    

    $code = @'
        using System;

        namespace MyCode
        {
            public class Helper
            {
                public static string FormatText(string message)
                {
                    return "Version 1: " + message;
                }
            }
        }
'@

    Add-Type -TypeDefinition $code -PassThru | Out-Null

    Write-Output $( [MyCode.Helper]::FormatText("It Works!") )
}

$j = Start-Job -ScriptBlock $cmd

do 
{
    Receive-Job -Job $j

} while ( $j.State -eq "Running" )

To my knowledge there is no way to remove a type from a PowerShell session once it has been added.

The (annoying) workaround I would suggest is to write your code in one ISE session, and execute it in a completely different session (separate console window or separate ISE if you want to be able to debug).

This only matters if you're changing $Source though (actively developing the type definition). If that's not the part that's changing, then ignore the errors, or if it's a terminating error use -ErrorAction to change it.


For those who want to avoid the error or avoid loading the type if it's already been loaded use the following check:

if ("TrustAllCertsPolicy" -as [type]) {} else {
        Add-Type "using System.Net;using System.Security.Cryptography.X509Certificates;public class TrustAllCertsPolicy : ICertificatePolicy {public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) {return true;}}"
        [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
}

I post this because you get the error OP posted if you make even superficial (e.g. formatting) changes to the C# code.