Export Powershell 5 enum declaration from a Module

断了今生、忘了曾经 提交于 2020-01-02 02:40:30

问题


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.


回答1:


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



回答2:


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



回答3:


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.




回答4:


This looks to be an issue somewhere in the 5.0.x release of PowerShell.

I had the issue on 5.0.10105.0

However, this is working fine in the 5.1.x release.



来源:https://stackoverflow.com/questions/40348069/export-powershell-5-enum-declaration-from-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!