10

I am sure I read somewhere that there is an easy way to pass named parameters from a calling function to a called function without explicitly naming and specifying each parameter.

This is more than just reusing the position; I'm interested in the case where the name of the passed parameters is the same in some cases, but not in others.

I also think there is a way that is not dependent on position.

function called-func {
    param([string]$foo, [string]$baz, [string]$bar)
    write-debug $baz
    write-host $foo,$bar
}

function calling-func {
    param([int]$rep = 1, [string]$foo, [string]$bar)
    1..$rep | %{
        called-func -foo $foo -bar $bar -baz $rep ## <---- Should this be simpler?
    }
}

calling-func -rep 10 -foo "Hello" -bar "World"

What would the method be, and is there a link?

I thought it might have been Jeffrey Snover, but I'm not sure.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John Weldon
  • 39,849
  • 11
  • 94
  • 127
  • I did do *some* googling first, but since I didn't see the answer already here on SO, I wanted to get it here too anyway. – John Weldon Aug 05 '09 at 15:54
  • So after some googling, I think the feature I was thinking of had to do with 'splatting' and passing switch parameters. I'll post an answer after I get all the details. – John Weldon Aug 05 '09 at 16:53

3 Answers3

3

In PowerShell v2 (which admittedly you may not be ready to move to yet) allows you to pass along parameters without knowing about them ahead of time:

called-func $PSBoundParameters

PSBoundParameters is a dictionary of all the parameters that were actually provided to your function. You can remove parameters you don't want (or add I suppose).

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
2

Well, I think I was confusing a blog post I read about switch parameters. As far as I can tell the best way is to just reuse the parameters like so:

called-func -foo:$foo -bar:$bar
John Weldon
  • 39,849
  • 11
  • 94
  • 127
  • 1
    The colon syntax is required when `foo` is a switch parameter. If you pass `-foo $foo` then `called-func` will think it's receiving two arguments (the switch `foo` and a value `$foo`). – sourcenouveau Dec 28 '11 at 16:34
1

How about

called-func  $foo $bar
Scott Weinstein
  • 18,890
  • 14
  • 78
  • 115