Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export Powershell 5 enum declaration from a Module

I have an enum type defined within a module. How do I export it to be accessible from outside once the module has been loaded?

enum fruits {
 apple
 pie
}

function new-fruit {
    Param(
        [fruits]$myfruit
    )
    write-host $myfruit
}

My advanced function takes the enum instead of the ValidateSet which works if the enum is available, but fails if it isn't.

Update: Separating it into a ps1 and dot-sourcing it (ScriptsToProcess) works, however I would wish that there's a cleaner way.

like image 484
Joel Avatar asked Oct 31 '16 18:10

Joel


3 Answers

Ran into the same issue trying to use/export an enumeration from a nested module (.psm1) on 5.0.x.

Managed to get it working by using Add-Type instead:

Add-Type @'
public enum fruits {
    apple,
    pie
}
'@

You should then be able to use

[fruits]::apple
like image 154
Will Avatar answered Nov 19 '22 06:11

Will


You can access the enums after loading the module using the using module ... command.

For example:

MyModule.psm1

enum MyPriority {
    Low = 0
    Medium = 1
    high = 2
}
function Set-Priority {
  param(
    [Parameter(HelpMessage = 'Priority')] [MyPriority] $priority
  )
  Write-Host $Priority
}  
Export-ModuleMember -function Set-Priority

Make:

New-ModuleManifest MyModule.psd1 -RootModule 'MyModule.psm1' -FunctionsToExport '*' 

Then in Powershell...

Import-Module .\MyModule\MyModule.psd1
PS C:\Scripts\MyModule> [MyPriority] $p = [MyPriority ]::High
Unable to find type [MyPriority].
At line:1 char:1
+ [MyPriority] $p = [MyPriority ]::High
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (MyPriority:TypeName) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

PS C:\Scripts\MyModule> using module .\MyModule.psd1
PS C:\Scripts\MyModule> [MyPriority] $p = [MyPriority ]::High
PS C:\Scripts\MyModule> $p
high
like image 29
Christopher G. Lewis Avatar answered Nov 19 '22 05:11

Christopher G. Lewis


When you get classes, enum or any .Net type in a module and you want to export them you have to use the using key word in the script where you want to import it, otherwise only cmlet are going to be imported.

like image 2
Aquiles Toruño Avatar answered Nov 19 '22 06:11

Aquiles Toruño