在 PowerShell 模块中跨函数和类使用枚举

SPS*_*amL 6 powershell

我正在创建一个 PowerShell 模块,我想在模块中的多个函数(如果重要的话,将导出该函数)和类中使用枚举。我认为做到这一点的唯一方法是将所有代码放在一个文件中。然而,这并不是一个容易维护的故事。我想要一个类似于以下内容的模块文件结构:

样本结构

正如您在代码中看到的,Class1 的 Enum1 属性被标记为“无法找到类型 [Enum1]”。

代码示例

部署我的资源:

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."
    }
}
Run Code Online (Sandbox Code Playgroud)

第1类:

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

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

枚举1:

enum Enum1 {
    ValueOne
    ValueTwo
}
Run Code Online (Sandbox Code Playgroud)

这是我的 PSD1 和 PSM1:

在此输入图像描述

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
}
Run Code Online (Sandbox Code Playgroud)

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): $_"
    }
}

Run Code Online (Sandbox Code Playgroud)

这是我尝试使用该模块时得到的结果:

在此输入图像描述

使用模块(在 Module1 文件夹之外):

Using module .\Module1

$class1 = [Class1]::new()

Deploy-MyResource -EnumParam ValueOne -ClassParam $class1
Run Code Online (Sandbox Code Playgroud)

我缺少什么?我找到的有关模块和类的所有示例都在一个文件中。

我在 GitHub 上创建了一个存储库,代码如下:https://github.com/SPSamL/PowerShell-Module-With-Classes

Ril*_*ney 0

无论您想在多个函数或模块中使用哪个类,请将其放入单个模块文件中。之后,您可以使用using命令:https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_using ?view=powershell-7 导入命名空间。

要从 PowerShell 模块加载类:

using module <module-name>