stewenson
stewenson

Reputation: 1322

Windows PowerShell - Array to function

I have this problem which makes me crazy:

i have a function like

function xyz
{
    foreach($x in $input)
    {
    }
}

1..10 | xyz

this is saved in a file test.ps1. When I execute it like ".\test.ps1" every time it writes that

cmdlet Write-Output at command pipeline position 1
Supply values for the following parameters:
InputObject[0]:

Why it is so? It does not work if I do like

$myArray = @("a","b","c")
xyz -arr $myArray

and doing a function like

function xyz
{
    param(
        [string[]]$arr
    )

    foreach($x in $arr)
    {
    }
}

Why?

Upvotes: 3

Views: 2490

Answers (1)

Keith Hill
Keith Hill

Reputation: 201602

I can't duplicate the error you're seeing but in general, when you want to process pipeline input the easiest way is like this:

function xyz
{
    process {
        $_
    }
}

1..10 | xyz

The process block will get called for every object in the pipeline. In fact, this is a common enough pattern that PowerShell has an even more convenient shortcut called a filter e.g.:

filter xyz
{
    $_
}

1..10 | xyz

Now if you need to handle regular parameters as well as pipeline input, then you need to add a param declaration and used advanced function parameter functionality e.g.:

function xyz
{
    param(
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [object[]]
        $myparam
    )
    process {
       foreach ($elem in $myparam)
       {
           $elem
       }
    }
}

xyz (1..10)
'a','b','c' | xyz

This works for both pipeline input and simple parameter (non-pipeline) usage. This most closely emulates how binary cmdlets actually work.

Upvotes: 5

Related Questions