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.
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With