Can you remove an Add-ed Type in PowerShell again? Can you remove an Add-ed Type in PowerShell again? powershell powershell

Can you remove an Add-ed Type in PowerShell again?


Like the others say, this is a .NET behavior. Assemblies loaded into an AppDomain cannot be unloaded. Only the AppDomain can be unloaded, and powershell uses a single appdomain. I blogged a bit about this some years ago:

https://web.archive.org/web/20170707034334/http://www.nivot.org/blog/post/2007/12/07/WhyAppDomainsAreNotAMagicBullet

When I test like this, I usually keep a shell open and use a nested shell to do tests. start powershell, cd to bin location then run "powershell" to start nested shell (new process.) "exit" to start over, and run "powershell" again.


I find the simplest way to get around this problem is to wrap the Add-Type and the test code inside of a Start-Job. Start-Job will create a background process, and the type will be loaded there. Once you are done, the process goes away and you're free to retry.

Here's an example of how it looks:

$job = Start-Job -ScriptBlock {    Add-Type -path 'my.dll'    $myObj = new-object My.MyTestClassName    $result = $myObj.TestMethod    $result}Wait-Job $jobReceive-Job $job

The output from the test method will be echoed to the console.


If your assembly doesn't require a binding context you can do this:

$bytes = [System.IO.File]::ReadAllBytes("Path_To_Your_Dll.dll")[System.Reflection.Assembly]::Load($bytes)