从一个模块中导出 Powershell 5 枚举声明

20

我在一个模块内定义了一个枚举类型。在模块被加载后,如何导出它以便从外部访问?

enum fruits {
 apple
 pie
}

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

我的高级函数采用枚举而不是ValidateSet,如果枚举可用,则正常工作,但如果不可用则会失败。

更新: 将其分离为ps1文件并进行点源(ScriptsToProcess)处理可以解决问题,但我希望有更简洁的方法。


2
请参考以下内容,了解如何在 PowerShell v5 模块中导出类:在导入后添加 using module moduleName 即可。具体内容请参见此处://stackoverflow.com/a/38701492 - wOxxOm
1
@wOxxOm “使用 using module 命令导入模块,并加载类定义。” https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_using?view=powershell-7.1#example-2---load-classes-from-a-script-module - metablaster
5个回答

15

尝试在5.0.x中使用/导出嵌套模块(.psm1)中的枚举时遇到相同的问题。

通过使用Add-Type,设法使其工作:

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

然后,您应该能够使用

[fruits]::apple

1
如果您依赖于模块自动加载功能,那么使用 "+1" 是最好的方法,否则我们将不得不手动执行 "using module ..."。 - metablaster

11

使用using module ...命令加载模块后,您可以访问枚举。

例如:

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

制造:

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

然后在 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

简而言之:在PowerShell模块中定义的enumclass只有在使用using module而不是Import-Module导入模块时,才对导入该模块的用户可见。 - mklement0
明白了,谢谢! - aksarben

2

当您在模块中获取类、枚举或任何 .Net 类型并希望将它们导出时,您必须在想要导入它的脚本中使用 using 关键字,否则只有 cmlet 将被导入。


1

我看到你的问题中提到你正在寻找比点操作脚本或使用ScriptsToProcess更干净的方法,但这对我有效。

步骤1:

  • 在你的模块中创建一个 .PS1 文件。我把我的文件命名为 Enumerations.ps1,并将文件放在模块的根文件夹中。

  • 在这个新文件中放置你的枚举语句

     ENUM DeathStarPlans {
         Reactor = 0
         Trench  = 1
         SuperSecretExhaustPort = 2
         }
    

步骤2

  • 更新您的 .PSD1 清单文件,以包括 ScriptsToProcess 选项

  • 参考枚举文件的路径。此路径相对于您的 .psd1 文件所在位置。

     ScriptsToProcess = @(".\Enumerations.ps1")
    

步骤三

  • 导入你的模块,如果你有类或其他类型创建,则可能需要关闭 PowerShell 并重新打开。

    Import-Module "模块名称" -force
    

步骤 4

  • 使用枚举

     [DeathStarPlans] :: SuperSecretExhaustPort
    

-3

这似乎是PowerShell 5.0.x版本中的某个问题。

我在5.0.10105.0上遇到了这个问题。

然而,在5.1.x版本中,这个问题已经得到了解决。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接