pipeline works but parameter input does not

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 11 months ago.

  • Author
    Posts
  • #33743
    Profile photo of Tony Pagliaro
    Tony Pagliaro
    Participant

    I have a script I'm writing that works great when the data is piped in,

    gc .\Desktop\PCs.txt |Repair-WinAgent
    

    but when I run it with an array in the parameter, it attempts to process all values in the array as one big long string.

    Repair-WinAgent -ComputerName (gc .\Desktop\PCs.txt) 
    

    here's my param section.

        Param
        (
            # Hostname(s) or IP Address(es) of the system(s) with the agent issue.  Can be piped in as a [string[]] value. 
            [Parameter(ValueFromPipeline=$true)]
            [string[]]
            $ComputerName = 'localhost'
        )
    
  • #33749
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Depends on what's in your function's Process block. Since $ComputerName is an array, you'll likely need a loop of some sort to enumerate that array. When you pipe stuff in, the process block gets called multiple times with just one string each time, but when you pass in the array on the command line, the process block gets called only once, and $ComputerName will contain the whole list of names.

  • #33782
    Profile photo of Tony Pagliaro
    Tony Pagliaro
    Participant

    Thanks Dave,
    Process has a bunch of if statements and whatnots that all reference the variable as if it were a single value.
    So if I wrap the whole process block (contents) inside a foreach loop, i should be all set for both cases, right?

  • #33783
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Yep, exactly. Here's the basic skeleton I use for this type of function:

    function Do-Something
    {
        [CmdletBinding()]
        param (
            [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
            [ValidateNotNullOrEmpty()]
            [string[]] $ComputerName = 'localhost'
        )
    
        process
        {
            foreach ($name in $ComputerName)
            {
                # Do stuff with $name
            }
        }
    }
    

You must be logged in to reply to this topic.