11

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?

3
  • What is wrong with no parenthesis? Commented Jun 16, 2012 at 4:36
  • 1
    Nothing. I am wondering how they create functions (cmd-lets) that use parenthesis Commented Jun 16, 2012 at 4:39
  • For eexample $ACL.SetAccessRule $Rule doesn't work without parenthesis. Commented Jan 7, 2021 at 14:18

1 Answer 1

23

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.