powershell - How do I conditionally add a class with Add-Type -TypeDefinition if it isn't added already? -
consider following powershell snippet:
$csharpstring = @" using system; public sealed class myclass { public myclass() { } public override string tostring() { return "this class. there many others " + "like it, 1 mine."; } } "@ add-type -typedefinition $csharpstring; $myobject = new-object myclass write-host $myobject.tostring();
if run more once in same appdomain (e.g. run script twice in powershell.exe or powershell_ise.exe) following error:
add-type : cannot add type. type name 'myclass' exists. @ line:13 char:1 + add-type -typedefinition $csharpstring; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + categoryinfo : invalidoperation: (myclass:string) [add-type], exception + fullyqualifiederrorid : type_already_exists,microsoft.powershell.commands.addtypecommand
how wrap call add-type -typedefinition called once?
this technique works me:
if (-not ([system.management.automation.pstypename]'myclass').type) { add-type -typedefinition 'public class myclass { }' }
- the type name can enclosed in quotes 'myclass', square brackets [myclass], or both '[myclass]' (v3+ only).
- the type name lookup not case-sensitive.
- you must use full name of type, unless part of system namespace (e.g. [system.datetime] can looked via 'datetime', [system.reflection.assembly] cannot looked via 'assembly').
- i've tested in win8.1; powershell v2, v3, v4.
internally, pstypename class calls languageprimitives.convertstringtotype() method handles heavy lifting. caches lookup string when successful, additional lookups faster.
i have not confirmed whether or not exceptions thrown internally mentioned x0n , justin d.
Comments
Post a Comment