简体   繁体   English

定义 PowerShell 模块中所有函数通用的参数

[英]Defining parameters common to all functions within a PowerShell module

I am writing a PowerShell module, the functions inside this module have some parameters which will be re-used across all functions.我正在编写一个 PowerShell 模块,该模块中的函数有一些参数将在所有函数中重复使用。 Rather than copy-pasting the function definition each time I add a new function, I would like to define them at the top like a script variable and then insert them into each function, giving me a single place to update if they need to be changed.我不想在每次添加新函数时都复制粘贴函数定义,而是想像脚本变量一样在顶部定义它们,然后将它们插入到每个函数中,以便在需要更改时给我一个更新位置.

Looking at how dynamic parameters are defined it seems like I should be able to define an object of that type and then reference it in the function definitions, but I can't find anything online giving me the correct syntax to do this.查看动态参数的定义方式,似乎我应该能够定义该类型的对象,然后在函数定义中引用它,但我无法在网上找到任何给我正确语法的信息。

Using PowerShell version 7.2使用 PowerShell 版本 7.2

$Script:ReUsedParameters = param(
    [Parameter()]
    [String]$Name,
    [Parameter()]
    [Int]$Id
)


Function New-Command {
    Param ($ReUsedParameters)

    Write-Output "Name: $Name, ID: $ID"
}

For the sake of answering, you can store the runtime parameters definitions in a script block and then call it & inside the function's dynamicparam block .为了回答,您可以将运行时参数定义存储在脚本块中,然后在函数的dynamicparam调用它&

I do not think this is a good idea nor I recommend using this.我认为这不是一个好主意,也不推荐使用它。 All functions should have their own repeated param blocks if needed.如果需要,所有函数都应该有自己的重复param块。

$reusedParameters = {
    $paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()

    # Since both parameters don't have any arguments (Mandatory, Position, ValueFromPipeline, etc..)
    # you can use this one for both, otherwise, each dynamic parameter should have their own
    # Parameter Declaration
    [Parameter[]] $paramAttribute = [Parameter]::new()

    $paramDictionary['Name'] = [System.Management.Automation.RuntimeDefinedParameter]::new('Name', [string], $paramAttribute)
    $paramDictionary['Id'] = [System.Management.Automation.RuntimeDefinedParameter]::new('Id', [int], $paramAttribute)

    return $paramDictionary
}

Function New-Command {
    [CmdletBinding()] # `CmdletBinding` is Mandataroy here
    param()           # if the `param` block is empty

    dynamicparam {
        & $reusedParameters
    }

    end {
        # Caveat: you can reference these parameters via $PSBoundParameters
        #         $Name and $Id are not part of the `param` block
        #         hence that wouldn't work here
        "Name: {0}, ID: {1}" -f $PSBoundParameters['Name'], $PSBoundParameters['ID']
    }
}

New-Command -Name asd -Id 123

As a declarative approach, you may turn the common parameters into class properties and have a single function parameter of the class type.作为一种声明式方法,您可以将公共参数转换为属性,并拥有一个类类型的函数参数。

class MyReUsedParameters {
    [String] $Name
    [Int] $Id = 23
}

Function New-Command {
    Param (
        [MyReUsedParameters] $ReUsedParameters,
        $AnotherParam
    )

    Write-Output "Name: $($ReUsedParameters.Name), ID: $($ReUsedParameters.ID)"
}

New-Command -ReUsedParameters @{ Name = 'foo'; Id = 42 } -AnotherParam bar

When passing a hashtable or PSCustomObject that has matching properties, it will automatically be converted to the class type.传递具有匹配属性的hashtablePSCustomObject时,它将自动转换为类类型。

You may even validate class properties similar to regular parameters.您甚至可以验证类似于常规参数的类属性。 Most parameter validation attributes can be specified for class properties as well.大多数参数验证属性也可以为类属性指定。

class MyReUsedParameters {
    [ValidateNotNullOrEmpty()] [String] $Name
    [Int] $Id = 23

    # Constructor - required to apply validation
    MyReUsedParameters( [Hashtable] $ht ) {
        $this.Name = $ht.Name
        $this.Id = $ht.Id
    }
}

Function New-Command {
    Param (
        [Parameter(Mandatory)] 
        [MyReUsedParameters] $ReUsedParameters
    )

    Write-Output "Name: $($ReUsedParameters.Name), ID: $($ReUsedParameters.ID)"
}

# Causes an error (as expected), because Name property is missing
New-Command -ReUsedParameters @{ Id = 42 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM