【问题标题】:Export Powershell 5 enum declaration from a Module从模块中导出 Powershell 5 枚举声明
【发布时间】:2019-01-11 00:37:54
【问题描述】:

我在模块中定义了一个枚举类型。加载模块后,如何将其导出为可从外部访问?

enum fruits {
 apple
 pie
}

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

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

更新: 将其分离为 ps1 并对其进行点源 (ScriptsToProcess) 是可行的,但我希望有一种更清洁的方法。

【问题讨论】:

标签: powershell enums powershell-5.0 powershell-cmdlet powershell-module


【解决方案1】:

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

改为使用Add-Type 使其正常工作:

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

你应该可以使用

[fruits]::apple

【讨论】:

  • +1 因为如果您依赖模块自动加载功能,这是最好的方法,否则我们必须手动执行using module ...
【解决方案2】:

您可以在加载模块后使用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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      我在 5.0.10105.0 上遇到了问题

      但是,这在 5.1.x 版本中运行良好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多