4
votes

I'm creating a PowerShell module that I would like to use enums across several functions (that will be exported, if that matters) and classes in the module. The only way I can see to do this is to put all of the code in a single file. That's not an easy maintenance story, however. I want a module file structure similar to the following:

Sample Structure

As you can see in the code, Class1 has the Enum1 property flagged as "Unable to find type [Enum1]."

Code examples

Deploy-MyResource:

function Deploy-MyResource {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [Enum1] $EnumParam,

        [Parameter(Mandatory=$true)]
        [Class1] $ClassParam
    )

    $class2 = [Class2]::new()

    if($class2.Prop1 -eq $ClassParam.Prop1) {
        Write-Output "Matches"
    }
    else {
        Write-Output "No match."
    }
}

Class1:

Class Class1 {
    [string] $Prop1
    [int] $Prop2
    [Enum1] $EnumProp

    DoSomething() {
        Write-Output "Did something using $($this.Prop1), $($this.Prop2), & $($this.EnumProp)"
    }
}

Enum1:

enum Enum1 {
    ValueOne
    ValueTwo
}

Here are my PSD1 and PSM1:

enter image description here

PSD1:


@{

    # Script module or binary module file associated with this manifest.
    RootModule         = 'Module1.psm1'

    # Version number of this module.
    # NOTE keep version in sync with Module1.nuspec
    ModuleVersion      = '2.7.2'

    # ID used to uniquely identify this module
    GUID               = '24EC97AC-42B1-4719-9EF2-F49C14F8D148'

    # Author of this module
    Author             = 'Me'

    # Company or vendor of this module
    CompanyName        = 'Me'

    # Description of the functionality provided by this module
    Description        = 'Example module for Stack post'

    # Minimum version of the Windows PowerShell engine required by this module
    PowerShellVersion  = '5.1'

    # Modules that must be imported into the global environment prior to importing this module
    RequiredModules    = @()

    # Assemblies that must be loaded prior to importing this module
    RequiredAssemblies = @('System.Web')

    # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
    FunctionsToExport  = @('Deploy-MyResource')

    # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
    CmdletsToExport    = @()

    # Variables to export from this module
    VariablesToExport  = @()

    # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
    AliasesToExport    = @()

    # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
    PrivateData        = @{

        PSData = @{
            #region Unused PSData

            # Tags applied to this module. These help with module discovery in online galleries.
            # Tags = @()

            # A URL to the license for this module.
            # LicenseUri = ''

            # A URL to the main website for this project.
            # ProjectUri = ''

            # A URL to an icon representing this module.
            # IconUri = ''

            # ReleaseNotes of this module
            # ReleaseNotes = ''

            #endregion Unused PSData
        } # End of PSData hashtable

    } # End of PrivateData hashtable

    #region Unused Props

    # Copyright statement for this module
    # Copyright = '(c) 2019 appliedis.com. All rights reserved.'

    # Supported PSEditions
    # CompatiblePSEditions = @()

    # Name of the Windows PowerShell host required by this module
    # PowerShellHostName = ''

    # Minimum version of the Windows PowerShell host required by this module
    # PowerShellHostVersion = ''

    # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
    # DotNetFrameworkVersion = ''

    # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
    # CLRVersion = ''

    # Processor architecture (None, X86, Amd64) required by this module
    # ProcessorArchitecture = ''

    # Script files (.ps1) that are run in the caller's environment prior to importing this module.
    # ScriptsToProcess = @()

    # Type files (.ps1xml) to be loaded when importing this module
    # TypesToProcess = @()

    # Format files (.ps1xml) to be loaded when importing this module
    # FormatsToProcess = 'Module1.Format.ps1xml'

    # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
    # NestedModules = @()

    # DSC resources to export from this module
    # DscResourcesToExport = @()

    # List of all modules packaged with this module
    # ModuleList = @()

    # List of all files packaged with this module
    # FileList = @()

    # HelpInfo URI of this module
    # HelpInfoURI = ''

    # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
    # DefaultCommandPrefix = ''

    #endregion Unused Props
}

PSM1:

# Get public and private function definition files.
$Private = @( Get-ChildItem -Path $PSScriptRoot\Function\private\*.ps1 -Recurse -ErrorAction SilentlyContinue )
$Public  = @( Get-ChildItem -Path $PSScriptRoot\Functions\public\*.ps1 -Recurse -ErrorAction SilentlyContinue )

# Dot source the files
Foreach($import in @($Private + $Public))
{
    Try
    {
        Set-StrictMode -Version Latest
        . $import.fullname
    }
    Catch
    {
        Write-Error -Message "Failed to import function $($import.fullname): $_"
    }
}

# Export the public functions
Foreach($import in $Public)
{
    Try
    {
        Export-ModuleMember -Function $import.BaseName
    }
    Catch
    {
        Write-Error -Message "Failed to import function $($import.fullname): $_"
    }
}

This is what I get when I try to use the module:

enter image description here

Use-Module (outside of the Module1 folder):

Using module .\Module1

$class1 = [Class1]::new()

Deploy-MyResource -EnumParam ValueOne -ClassParam $class1

What am I missing? All of the examples about modules and classes I'm finding are all in a single file.

I've created a repo on GitHub with the code here: https://github.com/SPSamL/PowerShell-Module-With-Classes

3
Please post your code as code (text) in the question itself. See How do I ask a good question? where it says "DO NOT post images of code, data, error messages, etc." - Lance U. Matthews
Apologies. I was trying to avoid a longer post which is why I included the repo, but I did add them. - SPSamL

3 Answers

1
votes

There's no good solution to this in pure PowerShell right now. If you need class definitions shared across multiple scripts and other modules, then you'll probably want to build a C# class library and include the DLL with one of your PowerShell module projects.

0
votes

Whichever classes you would like to use across multiple functions or modules, put inside a single module file. Afterward, you can utilize the using command: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_using?view=powershell-7 to import the namespace.

To load classes from a PowerShell module:

using module <module-name>

0
votes

I use pre-v5 syntax (works with Core), which creates the enum into a global scope.

Add-Type -TypeDefinition @"
    public enum Enum1 {
        ValueOne,
        ValueTwo
    }
"@