Reputation: 533
I have a function that looks somthing like this:
function plk(){
$cmd = $args -join ' '
plink user@myserver -i key.ppk $cmd
}
This function works great, however I wish to add a new argument that will enable me to change the server (but keep myserver
as default if I don't name my server). so I changed my code to this:
function plk($server = 'myserver'){
$cmd = $args -join ' '
plink user@$server -i key.ppk $cmd
}
However, PowerShell seems to think that my first argument is my $server
variable.
Meaning if I use my function like: plk ls /folder
, PowerShell would think that ls
is $server
.
I want to fix this that only if I do: plk -server 'server' ls /folder
, PowerShell would switch the server, and using plk ls /folder
would use my default.
Upvotes: 3
Views: 180
Reputation: 58971
I would define the parameters within a Param
block, add one parameter for $Server
and one for the remaining $Arguments
.
Then you could use the ValueFromRemainingArguments
property:
The ValueFromRemainingArguments argument indicates that the parameter accepts all of the parameters values in the command that are not assigned to other parameters of the function.
Source: about_Functions_Advanced_Parameters
Script:
function plk
{
Param
(
[Parameter(ValueFromRemainingArguments=$true)]
[string[]]$Arguments,
[Parameter(Mandatory=$false)]
[string]$Server = 'myServer'
)
$cmd = $Arguments -join ' '
plink user@$Server -i key.ppk $cmd
}
Upvotes: 1