Using New-Object -ArgumentList when the constructor takes one parameter that is an array

PowerShell is a great scripting language. One of its greatest features is that you have the full power of the .NET framework at your disposal when you use it. However, PowerShell is a dynamically language, and the .NET CLR was designed for static languages. Because of this, sometimes when you call CLR assemblies in Powershell, the types do not get resolved correctly.

I ran into this recently while calling New-Object to invoke the MemoryStream constructor that takes an array of bytes as a parameter. PowerShell did not automatically turn byte[] into object[] {byte[]}. Instead I got an error.

Windows PowerShell New-Object MemoryStream error

The same error appeared if I tried New-Object System.IO.MemoryStream @($bytes).

I initially solved my problem the hard way. I created a List<byte>, add the the array to the list and called List.ToArray(). Eventually, I figured out how to do it correctly thanks to this MSDN PowerShell Tip of the Week. To make an array of one item you precede it with a comma (I tried placing the comma afterwards during my initial experiments).  Since the argument list is not the first parameter of New-Object, I needed to wrap it in parenthesis. So I ended up with New-Object System.IO.MemoryStream (,$bytes) which worked as illustrated below.

Windows PowerShell New-Object MemoryStream success