views:

442

answers:

1

The $args variable should, by definition, contain all arguments passed to a script function. However if I construct a pipeline inside my function, the $args variable evaluates to null. Anyone knows why?

See this example:

function test { 1..3 | % { echo "args inside pipeline: $args" } ; echo "args outside pipeline: $args" }

This is the output, when passing parameter "hello":

PS> test hello
args inside pipeline:
args inside pipeline:
args inside pipeline:
args outside pipeline: hello

Is there a specific reason for this? I know how to work around this, however I wonder if anonye out there can explain the reason for this.

+5  A: 

Pipes use $input. Try this:

function test { 1..3 | % { echo "args inside pipeline: $input" } ; echo "args outside pipeline: $args" }
EBGreen
Ok thanks. However I'd still say that this behavior is very strange. And according to the dev's they tried hard to design it using the Principle Of Least Surprise ;)
driAn
To explain what is going on here, $args contains every uncaptured (for lack of a better term) argument to a command. In your pipeline example, you are asking for left over $args from the ForEach-Object (%) command, because that is the context that the script block will be evaluated in.
JasonMArcher
This kind of thing also happens with the $_ automatic variable. You need to watch what context it is in.
JasonMArcher