Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a .Net enum into a PowerShell script

Hopefully I can explain this in a clear question to avoid confusion (since I'm a bit confused myself).
I have a dll, I'll call MyCommonStuff. I have an enum object defined in a module in this assembly here:

MyCommonStuff\Enums\ImportEnum.cs

Like this:

namespace MyCommonStuff.ImportEnum
{
    public enum ImportType
    {
        Blah1 = 0,
        Blah2 = 1,
        Blah3 = 2
    }
}

I'd like to import this into a PowerShell script at run-time to avoid having to manually copy it over and have to sync it up in the event that it should change.
Could someone enlighten me on how I can go about this?

like image 391
Maniaque Avatar asked Oct 08 '15 17:10

Maniaque


2 Answers

I was trying to do something similar to this, but was defining my enum inside a custom cmdlet and it seems to work differently. Using the example provided (and assuming that the enum is tucked inside a class which extends PSCmdlet) you would need to do the following inside a powershell script/cmd window:

Import-Module "Path to dll"

$Blah1 = [MyCommonStuff.ImportEnum.ClassName+ImportType]::Blah1

For some reason you use "+" instead of "." to reference the enum value

like image 124
Zach Avatar answered Oct 01 '22 15:10

Zach


Here's one possible way I foresee solving your solution. You can create a module which is automatically loaded by powershell which adds the type for you.

To create the module, open the powershell ISE and enter the following code:

$Path = "path to dll"
Add-Type -Path $Path

Save the "module" as a .psm1 file, not a script, and name it something easy but informative. You'll then create a new directory in the "C:\Windows\System32\WindowsPowerShell\v1.0\Modules" with the EXACT SAME NAME as your psm1 file. Drop your psm1 file in there and then launch a new powershell window.

You should now be able to access your enum like so:

[MyCommonStuff.ImportEnum.ImportType]::Blah1

I'd recommend using this one module to contain all your custom types, objects, cmdlets, functions, etc so they're all in the same place. If you do, check out the Export-ModuleMember cmdlet as you'll likely need it.

like image 28
Colyn1337 Avatar answered Oct 01 '22 14:10

Colyn1337