c# - PowerShell 添加类型 : Cannot add type. 已存在

标签 c# powershell runtime-error

我正在使用 PowerShell 脚本直接在脚本中运行 C# 代码。我遇到了几次特定错误的错误。如果我在 PowerShell ISE 中对 C# 代码进行任何更改并尝试再次运行它,我会收到以下错误。

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

我解决此错误的方法是更改​​命名空间和调用 C# 方法的命令 [AlertsOnOff10.onOff]::Main("off")。有没有一种方法可以在不更改 namespace 和方法调用的情况下防止此错误发生?

最佳答案

对于那些想要避免错误或避免加载已经加载的类型的人,请使用以下检查:

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
}

我发布这个是因为如果您对 C# 代码进行哪怕是表面的(例如格式化)更改,您都会收到错误 OP。

关于c# - PowerShell 添加类型 : Cannot add type. 已存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25730978/

相关文章:

python - 洛伦兹方程的运行时警告

image - 如何解决VB6中的运行时错误 '429 : Activex component can' t创建对象?

java - 使用google fit android api读取数据时获取 "Task is not yet complete error"

c# - Windows Phone 7 按钮

bash - 如何更改目录中多个文件的扩展名?

powershell - 方法调用失败,因为 [System.String] 不包含名为 'SelectNodes' 的方法

powershell - 在任务计划程序上运行PowerShell脚本

c# - 如何在ASP.NET C#的Gridview中获取并显示特定的值

c# - 在 UpdatePanel 中使用 GridView

c# - 如何以编程方式从数据库生成 Entity Framework 类?