Powershell - How to use an 'enum' imported from a module as script parameter

Viewed 280

in a script I try to use an enum that is defined in a module. Here's the script Sample.ps1:

 using module SampleModule
 param(
  [SampleEnum] $MyEnum
 )
 $MyEnum

and here's SampleModule.psm1:

  enum SampleEnum {
    A
    B
    C
  }

Starting Sample.ps1 from a fresh Powershell gives me the following error:

  PS C:\test> .\Sample.ps1
  Unable to find type [SampleEnum].
  At C:\test\Sample.ps1:3 char:2
  +  [SampleEnum] $MyEnum
  +  ~~~~~~~~~~~~
      + CategoryInfo          : InvalidOperation: (SampleEnum:TypeName) [], RuntimeException
      + FullyQualifiedErrorId : TypeNotFound

I can explicitly import the module from the shell like this:

  PS C:\test> using module SampleModule
  PS C:\test> .\Sample.ps1
  PS C:\test> .\Sample.ps1 A
  A

...but of course I want the script to be self-contained. Why does the error occur and how to work-around it?

Update to be more specific: Using the enum in the script body - not in the param declaration - does work, like here:

using module SampleModule
$MyEnum = [SampleEnum]::A
$MyEnum

Using Import-Module does not work in either scripts, it simply does not make the enum visible (see e.g. enter link description here).

So my problem is to use the enum in the param of the script.

1 Answers

I ran into this, too (with PS v5.1.17763.2090).

As far as I can tell (I haven't disassembled to verify, but this is what it looks like based on a simple script's behavior), a PSM's param() clause is evaluated first, therefore any types that should be imported by the using statement are unknown at that point.

Best workaround I could find would be to use basic types, then convert them, as follows:

 using module SampleModule
 param(
  [UInt64] $MyEnum
 )
 $MyEnum = [Enum]::ToObject([SampleEnum],$MyEnum)
Related