add-type

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

主宰稳场 提交于 2019-11-30 10:43:08
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(); 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

Can you remove an Add-ed Type in PowerShell again?

喜欢而已 提交于 2019-11-28 05:37:57
I'm currently writing a library in C# and was using PowerShell to quickly test it on some occasions. However, this prevents me from re-building the project as PowerShell obviously still has the DLL open. Is there a way of unloading the DLL again after adding it with Add-Type ? The documentation doesn't seem to have clues on that and the obvious candidate would be Remove-Type (which doesn't exist – there is only one command anyway with Type as its noun). It gets cumbersome to close PowerShell and do all the stuff of navigating to the build directory and adding the type again each time I want to