Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell argument passing to function seemingly not working

I sense that I am doing something silly, but here is the issue:

Function getPropertyOfFile($a, $b, $c)
{
    $a.GetDetailsOf($b, $c)
}

If I pass $a, $b, $c variables that are appropriate to the function, it fails saying that

"Method invocation failed because [System.Object[]] doesn't contain a method named 'GetDetailsOf'."

However, if I directly replace $a, $b, $c with the arguments that I was passing, and then try to run that, it works fine.

What the heck is going on?

Note: I am using powershell ISE, and am inputting the function to powershell by copy/pasting it into the console. I have also been working under the assumption that if I input a new function with the same name, it would overwrite. Is there a better way to just have PS read from the .ps1?

Edit: I am trying to wrap the answer to this question into functions.

Edit 2:

Function getPropertyOfFile $a $b $c
{
    $a.GetDetailsOf($b, $c)
}

Gives an Missing function body in function declaration. At line:1 char:28 error.

like image 544
soandos Avatar asked Feb 23 '12 20:02

soandos


2 Answers

Functions in PowerShell are called similar to cmdlets, so you don't need to separate arguments with commas.

Your invocation likely looks like this:

getPropertyOfFile($foo, $bar, $baz)

which results in $a having the value $foo, $bar, $baz (an array) while $b and $c are $null.

You need to call it like this:

getPropertyOfFile $foo $bar $baz

which, as noted, is identical to how you call cmdlets. You could even do

getPropertyOfFile -a $foo -c $baz -b $bar

at which point you probably notice that your function arguments aren't named very well ;-)

EDIT: As noted before your declaration of the function is fine. The problem is in the code you didn't post but is easily inferrable for people with PowerShell experience. Namely, the invocation of your function.

like image 145
Joey Avatar answered Oct 19 '22 07:10

Joey


You need to separate your arguments when calling the function with spaces rather than commas i.e.

getPropertyOfFile $arg1 $arg2 $arg3

instead of

getPropertyOfFile $arg1, $arg2, $arg3

The second form will pass a single array containing $arg1, $arg2 and $arg3 as the parameter $a

like image 27
Lee Avatar answered Oct 19 '22 06:10

Lee