Parenthesis Powershell functions

后端 未结 1 886
孤独总比滥情好
孤独总比滥情好 2020-11-29 13:44

How to call function using parameters in powershell with parenthesis.

I have as example this function

function Greet([string]$name , [int]$times)
{
          


        
相关标签:
1条回答
  • 2020-11-29 13:53

    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)
    
    0 讨论(0)
提交回复
热议问题