如果尚未添加,如何有条件地添加具有 Add-Type -TypeDefinition 的类? [英] How do I conditionally add a class with Add-Type -TypeDefinition if it isn't added already?

查看:41
本文介绍了如果尚未添加,如何有条件地添加具有 Add-Type -TypeDefinition 的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 PowerShell 片段:

Consider the following PowerShell snippet:

$csharpString = @"
using System;

public sealed class MyClass
{
    public MyClass() { }
    public override string ToString() {
        return "This is my class. There are many others " +
            "like it, but this one is mine.";
    }
}
"@
Add-Type -TypeDefinition $csharpString;
$myObject = New-Object MyClass
Write-Host $myObject.ToString();

如果我在同一个 AppDomain 中多次运行它(例如在 powershell.exe 或 powershell_ise.exe 中运行脚本两次),我会收到以下错误:

If I run it more than once in the same AppDomain (e.g. run the script twice in powershell.exe or powershell_ise.exe) I get the following error:

Add-Type : Cannot add type. The type name 'MyClass' already exists.
At line:13 char:1
+ Add-Type -TypeDefinition $csharpString;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (MyClass:String) [Add-Type],
 Exception
    + FullyQualifiedErrorId :
 TYPE_ALREADY_EXISTS,Microsoft.PowerShell.Commands.AddTypeCommand

如何包装对 Add-Type -TypeDefinition 的调用,使其只调用一次?

How do I wrap the call to Add-Type -TypeDefinition so that its only called once?

推荐答案

这个技巧很适合我:

if (-not ([System.Management.Automation.PSTypeName]'MyClass').Type)
{
    Add-Type -TypeDefinition 'public class MyClass { }'
}

  • 类型名称可以用引号MyClass"、方括号 [MyClass] 或两者括起来[MyClass]"(仅限 v3+).
  • 类型名称查找不区分大小写.
  • 您必须使用类型的全名,除非它是 System 命名空间的一部分(例如,[System.DateTime] 可以通过 'DateTime' 查找,但 [System.Reflection.Assembly] 不能通过以下方式查找组装").
  • 我只在 Win8.1 中测试过;PowerShell v2、v3、v4.
  • 在内部,PSTypeName 类调用 LanguagePrimitives.ConvertStringToType() 方法来处理繁重的工作.它在成功时缓存查找字符串,因此其他查找速度更快.

    Internally, the PSTypeName class calls the LanguagePrimitives.ConvertStringToType() method which handles the heavy lifting. It caches the lookup string when successful, so additional lookups are faster.

    我还没有确认是否有 x0n 和 Justin D 提到的内部抛出任何异常.

    I have not confirmed whether or not any exceptions are thrown internally as mentioned by x0n and Justin D.

    这篇关于如果尚未添加,如何有条件地添加具有 Add-Type -TypeDefinition 的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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