How do I conditionally add a class with Add-Type -TypeDefinition if it isn't added already?

前端 未结 5 1272
我在风中等你
我在风中等你 2020-12-16 09:15

Consider the following PowerShell snippet:

$csharpString = @\"
using System;

public sealed class MyClass
{
    public MyClass() { }
    public override stri         


        
5条回答
  •  半阙折子戏
    2020-12-16 09:30

    This technique works well for me:

    if (-not ([System.Management.Automation.PSTypeName]'MyClass').Type)
    {
        Add-Type -TypeDefinition 'public class MyClass { }'
    }
    
    • The type name can be enclosed in quotes 'MyClass', square brackets [MyClass], or both '[MyClass]' (v3+ only).
    • The type name lookup is not case-sensitive.
    • You must use the full name of the type, unless it is part of the System namespace (e.g. [System.DateTime] can be looked up via 'DateTime', but [System.Reflection.Assembly] cannot be looked up via 'Assembly').
    • I've only tested this in Win8.1; PowerShell v2, v3, v4.

    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.

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

提交回复
热议问题