【问题标题】:Use Enums across functions and classes in a PowerShell Module在 PowerShell 模块中跨函数和类使用枚举
【发布时间】:2020-07-10 04:26:42
【问题描述】:

我正在创建一个 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."
    }
}

第一类:

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

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

枚举1:

enum Enum1 {
    ValueOne
    ValueTwo
}

这是我的 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
}

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

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

Use-Module(在 Module1 文件夹之外):

Using module .\Module1

$class1 = [Class1]::new()

Deploy-MyResource -EnumParam ValueOne -ClassParam $class1

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

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

【问题讨论】:

  • 请将您的代码作为代码(文本)发布在问题本身中。请参阅How do I ask a good question?,其中写着“请勿发布代码、数据、错误消息等的图像。
  • 抱歉。我试图避免更长的帖子,这就是我包含回购的原因,但我确实添加了它们。

标签: powershell


【解决方案1】:

目前在纯 PowerShell 中没有很好的解决方案。如果您需要跨多个脚本和其他模块共享类定义,那么您可能需要构建一个 C# 类库并将 DLL 包含在您的 PowerShell 模块项目之一中。

【讨论】:

    【解决方案2】:

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

    从 PowerShell 模块加载类:

    using module <module-name>

    【讨论】:

    • 我想使用它的实际项目以这种方式维护会很糟糕。甚至在添加类之前,其中一个模块中就有超过 50 个功能。其中一些很长。必须有办法做到这一点,对吧?
    • “我正在创建一个 PowerShell 模块,我想在模块中的多个函数(将被导出,如果重要的话)和类中使用枚举。”将枚举放在一个文件中并保存为 enums.psm 或其他内容。将 using 放入需要枚举的每个文件中。
    • 如果你想在其他功能中使用命名空间,但又不希望它太大,只需为特定命名空间制作模块即可。这样您就不会导出其他功能,并且所有内容都包含在一个简单的文件中,以便在需要时进行维护。 @SPSamL
    【解决方案3】:

    我使用 pre-v5 语法(与 Core 一起使用),它将枚举创建到全局范围内。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-18
      • 2020-08-03
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多