Powershell function arguments and the array operator

If you are a C# developer that is new to Powershell, or at least new to writing Powershell functions with typed parameters you will likely come across the following error:

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "<type of first argument>"

The reason for this error is most likely because you are passing a comma separated list of arguments as you would in C#:

myfunction arg1, arg2, arg3 or perhaps even myfunction(arg1, arg2, arg3)

In both of these cases you are in fact passing an array of objects as the single and only parameter. Considering this, the error message makes perfect sense. In Powershell the comma is an array operator (see here) and arguments should be passed to a function delimited only by a space character. Like so:

myfunction arg1 arg2 arg3

This brings up another question though: “how come I wasn’t getting an error when I had untyped parameters (or string type parameters)?”

This is because under the covers the arguments list is just an object array and the parameters are positional – they retrieved by indexing into the arguments array. When you are passing a single parameter that is an object array you are passing in the arguments array itself. When the parameters are typed such that they can be auto-converted from an object type (eg string) then it will work as expected.

Published by

Paul Ryan

As a developer my professional interests are technical and tend to be SharePoint focused. I've been working with SharePoint since 2009 and hope my posts will give back a little to the community that's supported me over this time. I'm also a keen runner (half-marathon) and passionate Brompton bicycle owner.

2 thoughts on “Powershell function arguments and the array operator”

  1. Thanks for the tip. This was driving me Crazy as I converted some c# code to powershell. After losing the brackets and the commas everything worked as expected.

Leave a Reply

Your email address will not be published.