考慮兩個 powershell 函式:
function A {
params(
[Parameter()]$x,
[Parameter()]$y
)
Write-Host $x $y
}
function B {
params(
[Parameter()]$x,
[Parameter()]$z
)
Write-Host $x $z
}
我想定義一個引數$x一次(它可能具有相當復雜的屬性,兩個函式必須保持相同)并在兩個函式中重新使用它,例如:
$x = {[Parameter()]$x}
function A {
params(
$x,
[Parameter()]$y
)
Write-Host $x $y
}
function B {
params(
$x,
[Parameter()]$z
)
Write-Host $x $z
}
(這怎么可能?
uj5u.com熱心網友回復:
要跨函式重用引數宣告- 如您的問題所要求 - 請參閱以下部分。
要通過預設(默認值)跨函式重用引數值(引數) ,請參閱底部部分。
為了重用引數宣告——不使用設計時模板來生成源代碼——你需要定義一個腳本塊來創建一個動態引數,該引數可以傳遞給dynamicparam多個高級函式的塊:
using namespace System.Management.Automation
# The script block that declares the dynamic parameter to be shared
# across functions.
$sharedDynParam = {
# Define the -x parameter dynamically.
$paramName = 'x'
$dict = [RuntimeDefinedParameterDictionary]::new()
$dict.Add(
$paramName,
[RuntimeDefinedParameter]::new(
$paramName,
[datetime], # Type the parameter [datetime]. for instance.
[ParameterAttribute] @{
Mandatory = $true # Make the parameter mandatory, for instance.
# ParameterSetName = 'default' # Assign it to a parameter set, if neeeded.
}
)
)
# Return the dictionary
return $dict
}
function A {
[CmdletBinding()]
param(
$y
)
# Assign the shared dynamic parameter.
dynamicparam { & $sharedDynParam }
# The use of `dynamicparam { ... }` requires use of an explicit
# `process { ... }` block (and optionally `begin { ... }` and
# `end { ... }`, as needed).
process {
# Note: A dynamic -x parameter cannot be accessed as $x
# Instead, it must be accessed via the $PSBoundParameters dictionary.
"[$($PSBoundParameters['x'])] - [$y]"
}
}
function B {
[CmdletBinding()]
param(
$z
)
# Assign the shared dynamic parameter.
dynamicparam { & $sharedDynParam }
process {
"[$($PSBoundParameters['x'])] - [$z]"
}
}
# Sample calls,
A -x '1970-01-01' -y yval
B -x '1970-01-02' -z zval
輸出:
[01/01/1970 00:00:00] - [yval]
[01/02/1970 00:00:00] - [zval]
要通過給定名稱跨命令預設引數值,請使用$PSDefaultParameterValues首選項變數:
# Preset a parameter value for all commands ('*') that have
# an -x ('x') parameter.
$PSDefaultParameterValues = @{ '*:x' = [pscustomobject] @{ foo = 1; bar = 2 } }
function A {
[CmdletBinding()] # This makes the function an *advanced* one, which respects
# $PSDefaultParameterValues; similarly, at least one
# parameter-individual [Parameter()] attribute does the same.
param(
$x,
$y
)
"[$x] - [$y]"
}
function B {
[CmdletBinding()]
param(
$x,
$z
)
"[$x] - [$z]"
}
# Sample calls, without an -x argument, relying on
# $PSDefaultParameterValues to provide it automatically.
A -y yval
B -z zval
輸出,顯示引數-x是通過自動系結的$PSDefaultParameterValues:
[@{foo=1; bar=2}] - [yval]
[@{foo=1; bar=2}] - [zval]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/412537.html
標籤:
