views:

410

answers:

4

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 ## <---- This should be simpler?
    }
}

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

Can anyone remember what the method would be, and provide a link? I thought it might have been Jeffrey Snover, but I'm not sure.

Thanks!

+1  A: 

How about

called-func  $foo $bar
Scott Weinstein
Good answer.. I'll modify the question a bit to show the differences...
John Weldon
+2  A: 

Bart de Smet has a great explanation* of parameter splatting: http://bartdesmet.net/blogs/bart/archive/2008/03/24/windows-powershell-2-0-feature-focus-splat-split-and-join.aspx

*as usual -- if you're a Powershell geek you owe him a spot in your RSS

Richard Berg
nice. This seems specific to powershell v2 btw.
John Weldon
Correct. In v1 the -param:$value syntax is as good as it gets.
Richard Berg
A: 

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

or as I noticed in the blog post:

called-func -foo:$foo -bar:$bar
John Weldon
+1  A: 

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
Yes, I can't wait till v2 goes to production :)
John Weldon