How to pass parameters to a function?

Solution 1:

The $arg[] array appears to lose scope inside the ForEach-Object.

function foo($arg1, $arg2)
{
  echo $arg1
  echo $arg2.FullName
}

echo "0: $($args[0])"
echo "1: $($args[1])"
$zero = $args[0]
$one = $args[1]
$items = get-childitem $args[1] 
$items | foreach-object {
    echo "inner 0: $($zero)"
    echo "inner 1: $($one)"
}

Solution 2:

The reason that $args[0] is not returning anything in the foreach-object is that $args is an automatic variable that takes unnamed, unmatched parameters to a command and the foreach-object is a new command. There aren't any unmatched parameters for the process block, so $args[0] is null.

One thing that can help is that your scripts can have parameters, just like functions.

param ($SomeText, $SomePath)
function foo($arg1, $arg2)
{
  echo $arg1
  echo $arg2.FullName
}

echo "0: $SomeText"
echo "1: $SomePath"
$items = get-childitem $SomePath
$items | foreach-object -process {foo $SomeText $_}

As you start to want more functionality from your parameters, you might want to check out a blog post I wrote on the progression of parameters from $args to the current advanced parameters we can use now.