PowerShell – Passing Arguments to a Function – Don’t Use Commas!

Recently picked up PowerShell for some automated deployment scripts – when passing more than one argument to a function I seemed to end up with one strange object, and any subsequent arguments were simply missing.
The problem was that within PowerShell you must separate arguments to a function by spaces rather than commas – if you use commas you are actually creating a list (of objects) and passing that as the first argument.

So say you have a function myFunction defined somewhere – the below call will dynamically create a list (the parentheses are simply ignored) and pass that to myFunction:

    myFunction($arg1, $arg2, $arg3);
    #myFunction will receive ONE argument from this call, a list with three elements
    #The second and third parameter will be null.

The correct way to pass three separate arguments is with spaces:

    myFunction $arg1 $arg2 $arg3;
    # my function will receive THREE separate arguments from this call. 

I mainly code in C# – and I think the main reason this caught me out, is that PowerShell scripting language is otherwise very similar to C#, especially when you code in a nice IDE like Power GUI.
At the time I calling a function inside a foreach loop with a XmlElement, and it’s just odd that you then have to “switch back” to this kind of classic command line passing of params.. but there you go – it’s a shell, albeit a powerful one!

This is also covered along with some other great PowerShell gotchas in the excellent article here http://www.johndcook.com/powershell_gotchas.html.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: