Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parenthesis Powershell functions

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?

like image 690
Ricardo Polo Jaramillo Avatar asked Jun 16 '12 04:06

Ricardo Polo Jaramillo


1 Answers

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.:

Greet Recardo 5
Greet -times 5 -name Ricardo

PowerShell uses () to allow you to specify expressions like so:

function Greet([string[]]$names, [int]$times=5) {
    foreach ($name in $names) {
        1..$times | Foreach {"Hi $name"}
    }
}

Greet Ricardo (1+4)

Great Ricardo    # Note that $times defaults to 5

You can also specify arrays simple by using a comma separated list e.g.:

Greet Ricardo,Lucy,Ethyl (6-1)

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" and 5. 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.:

"Hello World".Substring(6, 3)
like image 56
Keith Hill Avatar answered Sep 23 '22 04:09

Keith Hill