4

I am trying to create a function that return a a byte array ([Byte[]]).

However, when I use the function and assign the returned value to a variable, the type of the variable is an array of objects ([Object[]]).

function make-byteArray() {
  [OutputType([Byte[]])]

   [byte[]] $byteArray = new-object byte[] 2
   $byteArray[0] = 0
   $byteArray[1] = 1

   write-host "type of byteArray: $($byteArray.GetType().FullName)"

   return $byteArray
}

$x = make-byteArray
write-host "type of x: $($x.GetType().FullName)"

I am puzzled why that is and would like to know what I can do to force the function to return a byte array.

2 Answers 2

7

Just add the unary comma , before the returned $byteArray like this:

return ,$byteArray

Return:

type of byteArray: System.Byte[]
type of x: System.Byte[]

This will wrap the returned array inside another, one-element array. When an array is returned from a function, PowerShell 'unrolls' that and in this case, it unrolls the wrapper array, leaving the byte array inside.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use Write-Output Instead of return:

Write-Output $bytearray -NoEnumerate

Return statement always unpacks the return object so it gets a type of System.Object[]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.