0

I have a simple PowerShell function

function Foo($a, $b){
  '$a = ' + $a
  '$b = ' + $b
}

I invoke it by calling

Foo("dogs", "cat");

Everything I've read so far says the expected output is

$a = dogs
$b = cats

What I'm actually seeing is:

$a = dogs cat
$b =

If I rewrite my function as:

function Foo($a, $b){
  '$a is ' + $a.GetType().Name;
  '$b = ' + $b.GetType().Name;
}

The output is:

$a is Object[]
You cannot call a method on a null-valued expression.
At C:\WCMTeam\Percussion\Notifier\foo.ps1:4 char:7
+       '$b = ' + $b.GetType().Name;
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Apparently $a and $b are being combined into a single array. What am I doing to cause this and how should I change it to get my expected result?

ThatBlairGuy
  • 2,426
  • 1
  • 19
  • 33

1 Answers1

5

You should call your function using

Foo "dogs" "cats"

, is used to separate array elements in Powershell, so

Foo "dogs", "cats"

calls Foo with a single array argument, which is assigned to $a.

Lee
  • 142,018
  • 20
  • 234
  • 287
  • Calling it as `Foo("dogs" "cats")` causes it to fail with the error "Unexpected token '"cats"' in expression or statement." But changing it to just `Foo "dogs" "cats"` does indeed solve the problem. Thank you; this is as maddening as the parentheses rules in VBScript. – ThatBlairGuy Apr 04 '13 at 19:47
  • 1
    Listen to the man (Lee). You shouldn't be using `(` and `)` at all in your function calls. PowerShell is not equal to c#, PS has it's own language (although much .Net / C# code work). – Frode F. Apr 04 '13 at 20:36
  • Oh, I'm listening all right. Just finding the transition a bit disorienting. :-/ – ThatBlairGuy Apr 04 '13 at 21:51