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

标签 powershell parameters powershell-7.2

我正在编写一个PowerShell模块,该模块内的函数有一些参数,这些参数将在所有函数中重复使用。我不想每次添加新函数时都复制粘贴函数定义,而是想像脚本变量一样在顶部定义它们,然后将它们插入到每个函数中,以便在需要更改它们时给我一个更新的地方.

看看动态参数是如何定义的,似乎我应该能够定义该类型的对象,然后在函数定义中引用它,但我在网上找不到任何可以为我提供执行此操作的正确语法的内容。

使用 PowerShell 版本 7.2

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


Function New-Command {
    Param ($ReUsedParameters)

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

最佳答案

为了便于回答,您可以将运行时参数定义存储在 script block 中。然后call it &在函数的 dynamicparam block 内.

我认为这不是一个好主意,也不建议使用它。如果需要,所有函数都应该有自己的重复 param block .

$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

关于powershell - 定义 PowerShell 模块中所有函数通用的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74892282/

相关文章:

powershell - 如何列出根目录下的 namespace ?

json - Powershell 7.2 : ConvertFrom-Json - Date Handling

wpf - 如何在Powershell的xaml中使用相对路径

powershell - 隐晦的第三种错误

powershell - 我想检查数组中是否存在元素

c - 函数参数中的 int * 与 int [] 与 int (*)[] 。我应该使用哪一个?

parameters - 为什么以及何时使用 Lua 中 os.exit() 函数的参数 "code"

java - 在java客户端中使用@POST请求发送参数

windows - 如何停止 powershell 形式将 bool 值的变量赋值转换为大写字母

Azure Powershell - 根据私有(private)IP查找NIC