Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Byte[] in PowerShell

I have some PowerShell code that is using a COM API. I am getting a Type Mismatch error when I pass in a byte array. Here is how I am creating the array, as well as some type information

PS C:\> $bytes = Get-Content $file -Encoding byte PS C:\> $bytes.GetType()  IsPublic IsSerial Name                                     BaseType -------- -------- ----                                     -------- True     True     Object[]                                 System.Array   PS C:\> $bytes[0].GetType()  IsPublic IsSerial Name                                     BaseType -------- -------- ----                                     -------- True     True     Byte                                     System.ValueType 

Poking around with the API, I have found that it is looking for a Byte[] with a base type of System.Array.

PS C:\> $r.data.GetType()  IsPublic IsSerial Name                                     BaseType -------- -------- ----                                     -------- True     True     Byte[]                                   System.Array  PS C:\> $r.data[0].gettype()  IsPublic IsSerial Name                                     BaseType -------- -------- ----                                     -------- True     True     Byte                                     System.ValueType 

What I am trying to do is convert $bytes into the same type as $r.data. For some reason, $bytes is getting created as an Object[]. How can I cast it to a Byte[]?

like image 493
Andy Schneider Avatar asked Jul 04 '13 15:07

Andy Schneider


People also ask

How do you write bytes in PowerShell?

[IO. File]::WriteAllBytes() is the correct way of writing bytes to a file in PowerShell.

What is byte in PowerShell?

All variables in PowerShell are .NET objects, including 8-bit unsigned integer bytes. A byte object is an object of type System.Byte in the .NET class library, hence, it has properties and methods accessible to PowerShell (you can pipe them into get-member).

How do you create an array in PowerShell?

To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator ( = ). The comma can also be used to initialize a single item array by placing the comma before the single item.

What are byte arrays?

A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..


1 Answers

This answer is for the question with no context. I'm adding it because of search results.

[System.Byte[]]::CreateInstance([System.Byte],<Length>) 
like image 91
Slogmeister Extraordinaire Avatar answered Sep 22 '22 19:09

Slogmeister Extraordinaire