Function parameters

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Mark Brown Mark Brown 1 year, 6 months ago.

  • Author
    Posts
  • #31594
    Profile photo of Mark Brown
    Mark Brown
    Participant

    I have created a function that has a parameter ComputerName. I use ValueFromPipline=$true, and everything works OK. So I can use the function with a single value or a series of values from the pipeline.
    How can I also use a list of values, similar to most CmdLets that have a ComputerName parameter.
    I what the function to accept a single value, a list of values or accept values from the pipeline.
    I just can't workout the list of values part.

    Thanks

  • #31596
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    This is the usual setup for parameters that fit your description:

    function Test-Something
    {
        param (
            [Parameter(ValueFromPipeline)]
            [string[]] $ComputerName = '.'
        )
    
        process
        {
            foreach ($computer in $ComputerName)
            {
                "Processing $computer"
            }
        }
    }
    

    By declaring the parameter as an array (in this case, [string[]]), callers can then use any of these conventions:

    Test-Something -ComputerName 'Single'
    Test-Something -ComputerName 'Multiple 1', 'Multiple 2'
    'Multiple 1', 'Multiple 2' | Test-Something
    
  • #31598
    Profile photo of Mark Brown
    Mark Brown
    Participant

    Brilliant! Thank You.

You must be logged in to reply to this topic.