Parenthesis Powershell functions

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)

Leave a Comment