Consider this:
Function Foo
{
param(
#????
)
}
I want to call Foo like this:
Foo -Bar "test"
Without it blowing up that I don’t have a $bar param specified. Is that possible? 🙂
Update:
I want this to work:
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"
This gives me:
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
I would suggest two alternatives.
First: you may want to consider passing whole function + it’s parameters as scriptblock parameter to your ifFunction…
OR: use ValueFromRemainingArguments:
In this case I use $MyArgs to store everything besides my mandatory parameter ‘First’. Than some simple if will tell me if it’s named parameter (-Next, -Last) or positional (Alfa, Beta, Gamma). This way you can have both advantages of advanced functions binding (whole [Parameter()] decoration) AND leave room for $args-style parameters too.