How to call function using parameters in powershell with parenthesis.
I have as example this function
function Greet([string]$name , [int]$times)
{
for ([int]$i = 1; $i -le $times;$i++)
{
Write-Host Hiiii $name
}
}
If I call the functions using
Greet Ricardo 5
or Greet "Ricardo" 5
works.
But when I use Greet ("Ricardo",5)
or Greet("Ricardo" ; 5)
It fails.
What is wrong?
Functions behaves like cmdlets. That is, you don't type dir(c:\temp). Functions likewise take parameters as space separated and like cmdlets, support positional, named and optional parameters e.g.:
PowerShell uses () to allow you to specify expressions like so:
You can also specify arrays simple by using a comma separated list e.g.:
So when you pass in something like
("Ricardo",5)
that is evaluated as a single parameter value that is an array containing two elements"Ricardo"
and5
. That would be passed to the$name
parameter but then there would be no value for the$times
parameter.The only time you use a parenthesized parameter list is when calling .NET methods e.g.: