PowerShell 添加类型:无法添加类型.已经存在 [英] PowerShell Add-Type : Cannot add type. already exist

查看:77
本文介绍了PowerShell 添加类型:无法添加类型.已经存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using PowerShell script to run C# code directly in the script. I've run in to an error a particular error a few times. If I make any changes to the C# code in the 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

我解决此错误的方法是更改​​命名空间和调用 C# 方法 [AlertsOnOff10.onOff]::Main("off") 的命令.我有什么方法可以防止这个错误发生而不必更改命名空间和方法调用?

The way I have been resolving this error is by changing the namespace and the command to call the C# method [AlertsOnOff10.onOff]::Main("off"). I there a way I can prevent this error from happening without having to change namespace and method call?

推荐答案

据我所知,一旦添加了类型,就无法从 PowerShell 会话中删除它.

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

我建议的(烦人的)解决方法是在一个 ISE 会话中编写您的代码,然后在一个完全不同的会话中执行它(单独的控制台窗口或单独的 ISE,如果您希望能够进行调试).

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).

这仅在您更改 $Source 时才重要(积极开发类型定义).如果那不是正在更改的部分,则忽略错误,如果是终止错误,请使用 -ErrorAction 更改它.

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, of if it's a terminating error use -ErrorAction to change it.

这篇关于PowerShell 添加类型:无法添加类型.已经存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆