PowerShell Add-Type: Unable to add type. already exists

I am using a PowerShell script to run C # code directly in a script. I encountered an error several times. If I make any changes to the C # code in PowerShell ISE and try to run it again, I get the following error.

Add-Type : Cannot add type. The type name 'AlertsOnOff10.onOff' already exists. At C:\Users\testUser\Desktop\test.ps1:80 char:1 + Add-Type -TypeDefinition $Source -ReferencedAssemblies $Assem + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (AlertsOnOff10.onOff:String) [Add-Type], Exception + FullyQualifiedErrorId : TYPE_ALREADY_EXISTS,Microsoft.PowerShell.Commands.AddTypeCommand 

The way I solved this error is to change the namespace and command to call the C # method [AlertsOnOff10.onOff]::Main("off") . Can I prevent this error without changing the namespace and method call?

+8
c # powershell runtime-error
source share
2 answers

As far as I know, there is no way to remove a type from a PowerShell session after adding it.

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

This only matters if you change $Source though (actively developing a type definition). If this is not the part that changes, and then ignores errors, if it ends with an error, use -ErrorAction to change it.

+8
source share

You can complete it as a task:

 $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" ) 
0
source share

All Articles