Powershell gotchas: calling a function

June 12, 2012

...

Consider the following code:

function f($a, $b, $c) {
	"f: `$a=$a, `$a.GetType()=$($a.GetType())"
	"f: `$b=$b, `$b.GetType()=$($b.GetType())"
	"f: `$c=$c, `$c.GetType()=$($c.GetType())"
}
f 1 2 3   # call f with three integers as parameters
f 1,2,3   # call f with an array of three integers
f (1,2,3) # as above

The gotcha here is not to fall into the trap to use a C#-like or Java(Script)-like syntax where parameters are separated by commas. The comma in Powershell is always an array constructor operator, and takes precedence over function application. (Which also means that adding paranthesis will yield the same result). The code above will result in:

f: $a=1, $a.GetType()=int
f: $b=2, $b.GetType()=int
f: $c=3, $c.GetType()=int
f: $a=1 2 3, $a.GetType()=System.Object[]
You cannot call a method on a null-valued expression.
At ...function-application.ps1:4 char:11
+ $b.GetType <<<< ()
    + CategoryInfo          : InvalidOperation: (GetType:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
f: $b=, $b.GetType()=
You cannot call a method on a null-valued expression.
At ...function-application.ps1:5 char:11
+ $c.GetType <<<< ()
    + CategoryInfo          : InvalidOperation: (GetType:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
f: $c=, $c.GetType()=
f: $a=1 2 3, $a.GetType()=System.Object[]
You cannot call a method on a null-valued expression.
At ...function-application.ps1:4 char:11
+ $b.GetType <<<< ()
    + CategoryInfo          : InvalidOperation: (GetType:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
f: $b=, $b.GetType()=
You cannot call a method on a null-valued expression.
At ...function-application.ps1:5 char:11
+ $c.GetType <<<< ()
    + CategoryInfo          : InvalidOperation: (GetType:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
f: $c=, $c.GetType()=

Profile picture

Written by Vidar Kongsli who is a software professional living in Oslo, Norway. Works as a consultant, system architect and developer at Bredvid. You should follow him on Twitter