powershellargumentsnew-object

Passing an Array Parameter Value


I have some code in PowerShell (below) to call the System.Guid constructor with a byte array (byte[]) as the only parameter.

The C# equivalent of this code is:

byte[] binaryData = userObj["ADGuid"].Value;
Guid adid = new System.Guid(binaryData);

This is my PowerShell code. It interprets the items array as individual parameters. How do I need to adjust this code?

[byte[]]$binaryData = $uo["ADGuid"].Value                 
$adid = new-object System.Guid -ArgumentList $binaryData

Here is a screenshot of the error message:

PowerShell Error Message


Solution

  • PowerShell is treating the array of bytes as a list of 16 individual parameters and trying to find a constructor for System.Guid that accepts that many, which it can't do because there isn't one.

    If you want to pass a single parameter which just happens to be an array of 16 bytes you need to wrap it in a "sacrificial array" so PowerShell only sees one parameter for the constructor...

    $adid = new-object System.Guid -ArgumentList @(, $binaryData)
    

    In this case, the single parameter is an array of bytes, which it can find a constructor overload for (i.e. public Guid (byte[] b);).