Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function [Hashtable[]] parameter that can come from pipeline or argument

Here's a function which accepts an array of hashtables via argument:

function abc () {

    Param([Hashtable[]]$tables)

    $tables.count

}

Example use:

PS C:\> abc -tables @{ a = 10 }, @{ b = 20 }, @{ c = 30 }
3

Here's a function which accepts Hashtables via pipeline:

function bcd () {

    Param([parameter(ValueFromPipeline=$true)][Hashtable]$table)

    $input.count

}

Example use:

PS C:\> @{ a = 10 }, @{ b = 20 }, @{ c = 30 } | bcd
3

Is there a way to define function which can accept a hashtable array via argument or pipeline via the same parameter? I.e. a function which can be called in both of the ways shown above. Note that I'll need the entire array of hashtables in a single variable (hence the use of $input above in bcd).

like image 977
dharmatech Avatar asked Nov 20 '25 23:11

dharmatech


2 Answers

function bcd () {

    Param([parameter(ValueFromPipeline=$true)][Hashtable[]]$table)

    Begin {$tables= @()}
    Process {$tables += $table}
    End {$tables.count}

}

@{ a = 10 }, @{ b = 20 }, @{ c = 30 } | bcd
bcd -table @{ a = 10 }, @{ b = 20 }, @{ c = 30 }

3
3
like image 75
mjolinor Avatar answered Nov 23 '25 16:11

mjolinor


Here is my go-to structure for dual-mode (pipeline and cmd-line) parameters:

Function bcd () 
{
    Param(
       [parameter(ValueFromPipeline = $true)]
       [Hashtable[]]$table
    )

    Process 
    {
        ForEach ($tab in $table) 
        {  
          # do something with the table
        }
    }
}
like image 22
Mike Shepard Avatar answered Nov 23 '25 15:11

Mike Shepard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!