定义PowerShell模块中所有函数的公共参数



我正在写一个PowerShell模块,这个模块内的函数有一些参数,这些参数将在所有函数中重用。与其每次添加新函数时都复制粘贴函数定义,不如在顶部像脚本变量一样定义它们,然后将它们插入到每个函数中,如果需要更改它们,给我一个单独的地方来更新。

看看动态参数是如何定义的,似乎我应该能够定义该类型的对象,然后在函数定义中引用它,但我在网上找不到任何能给我正确语法的东西。

使用PowerShell version 7.2

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

Function New-Command {
Param ($ReUsedParameters)
Write-Output "Name: $Name, ID: $ID"
}

为了回答这个问题,您可以将运行时参数定义存储在脚本块中,然后在函数的dynamicparam块中将其称为&

我不认为这是一个好主意,我也不建议这样做。如果需要,所有函数都应该有自己的重复的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

作为声明性方法,您可以将公共参数转换为类属性,并具有类类型的单个函数参数。

class MyReUsedParameters {
[String] $Name
[Int] $Id = 23
}
Function New-Command {
Param (
[MyReUsedParameters] $ReUsedParameters,
$AnotherParam
)
Write-Output "Name: $($ReUsedParameters.Name), ID: $($ReUsedParameters.ID)"
}
# Pass the common parameters as a hashtable which gets converted to
# MyReUsedParameters automatically.
New-Command -ReUsedParameters @{ Name = 'foo'; Id = 42 } -AnotherParam bar
# Alternatively pass the common parameters as a (typed) variable.
# PowerShell is able to deduce the argument name from the type.
$commonArgs = [MyReUsedParameters] @{ Name = 'Foo'; Id = 42 }
New-Command $commonArgs -AnotherParam bar

当传递具有匹配属性的hashtablePSCustomObject时,将自动转换为类类型。

您甚至可以验证类属性类似于常规参数。大多数参数验证属性也可以为类属性指定。

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 }

最新更新