Powershell argument passing to function seemingly not working

28,506

Solution 1

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.

Solution 2

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

Share:
28,506
soandos
Author by

soandos

Student. Third to earn the marshal badge on SuperUser profile for soandos on Stack Exchange, a network of free, community-driven Q&A sites http://stackexchange.com/users/flair/375094.png profile for soandos on Project Euler, which exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics. http://projecteuler.net/profile/soandos.png

Updated on February 24, 2020

Comments

  • soandos
    soandos about 4 years

    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.