Sna*_*ake 5 powershell arguments function
考虑一下:
Function Foo
{
param(
#????
)
}
Run Code Online (Sandbox Code Playgroud)
我想像这样打电话给Foo:
Foo -Bar "test"
Run Code Online (Sandbox Code Playgroud)
没有它爆炸,我没有指定$ bar param.那可能吗?:)
更新:
我希望这个工作:
Function IfFunctionExistsExecute
{
param ([parameter(Mandatory=$true)][string]$func, [parameter(Mandatory=$false)][string]$args)
begin
{
# ...
}
process
{
if(Get-Command $func -ea SilentlyContinue)
{
& $func $args # the amperersand invokes the function instead of just printing the variable
}
else
{
# ignore
}
}
end
{
# ...
}
}
Function Foo
{
param([string]$anotherParam)
process
{
$anotherParam
}
}
IfFunctionExistsExecute Foo -Test "bar"
Run Code Online (Sandbox Code Playgroud)
这给了我:
IfFunctionExistsExecute : A parameter cannot be found that matches parameter name 'Test'.
At C:\PSTests\Test.ps1:35 char:34
+ IfFunctionExistsExecute Foo -Test <<<< "bar"
+ CategoryInfo : InvalidArgument: (:) [IfFunctionExistsExecute], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,IfFunctionExistsExecute
Run Code Online (Sandbox Code Playgroud)
我建议两种选择.
首先:您可能需要考虑将整个函数+它的参数作为scriptblock参数传递给ifFunction ...
或者:使用ValueFromRemainingArguments:
function Test-SelfBound {
param (
[Parameter(
Mandatory = $true,
HelpMessage = 'Help!'
)]
[string]$First,
[Parameter(
ValueFromRemainingArguments = $true
)]
[Object[]]$MyArgs
)
$Arguments = foreach ($Argument in $MyArgs) {
if ($Argument -match '^-([a-z]+)$') {
$Name = $Matches[1]
$foreach.MoveNext() | Out-Null
$Value = $foreach.Current
New-Variable -Name $Name -Value $Value
$PSBoundParameters.Add($Name,$Value) | Out-Null
} else {
$Argument
}
}
$PSBoundParameters | Out-Default
"Positional"
$Arguments
}
Test-SelfBound -First Test -Next Foo -Last Bar Alfa Beta Gamma
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我使用$ MyArgs存储除强制参数'First'之外的所有内容.比起一些简单的if会告诉我它是否是命名参数(-Next,-Last)或位置(Alfa,Beta,Gamma).这样你就可以同时拥有高级函数绑定的优点(整个[Parameter()]装饰)并为$ args-style参数留出空间.