Export Powershell 5 declaration of declaration from module

I have an enum type defined in a module. How can I export it for external access once the module has been loaded?

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

My extended function accepts an enumeration instead of a ValidateSet , which works if the enumeration is available, but fails if it is not.

Update: Splitting it into ps1 and dot-sourcing it (ScriptsToProcess) works, however I would like a cleaner way there.

+7
source share
4 answers

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

For instance:

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 

Mark:

 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 
+3
source

This seems like a problem somewhere in PowerShell version 5.0.x.

I had a problem on 5.0.10105.0

However, in version 5.1.x this works fine.

0
source

Faced the same problem while trying to use / export an enumeration from a nested module (.psm1) in 5.0.x.

Managed to get it working using Add-Type instead:

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

You should be able to use

 [fruits]::apple 
0
source

When you get classes, enum, or any type of .Net in the module and want to export them, you must use the using keyword in the script where you want to import it, otherwise only cmlet will be imported.

-one
source

Source: https://habr.com/ru/post/1011893/


All Articles