Creating Byte[] in PowerShell
Solution 1
Cast it to a byte array:
[byte[]]$bytes = Get-Content $file -Encoding byte
Solution 2
This answer is for the question with no context. I'm adding it because of search results.
[System.Byte[]]::CreateInstance([System.Byte],<Length>)
Solution 3
In PS 5.1, this:
[System.Byte[]]::CreateInstance(<Length>)
didn't work for me. So instead I did:
new-object byte[] 4
which resulted in an empty byte[4]:
0
0
0
0
Solution 4
There are probably even more ways, but these are the ones I can think of:
Direct array initialization:
[byte[]] $b = 1,2,3,4,5
$b = [byte]1,2,3,4,5
$b = @([byte]1,2,3,4,5)
$b = [byte]1..5
Create a zero-initialized array
$b = [System.Array]::CreateInstance([byte],5)
$b = [byte[]]::new(5) # Powershell v5+
$b = New-Object byte[] 5
$b = New-Object -TypeName byte[] -Args 5
And if you ever want an array of byte[]
(2-D array)
# 5 by 5
[byte[,]] $b = [System.Array]::CreateInstance([byte],@(5,5)) # @() optional for 2D and 3D
[byte[,]] $b = [byte[,]]::new(5,5)
Additionally:
# 3-D
[byte[,,]] $b = [byte[,,]]::new(5,5,5)
[byte[,]] $b = [System.Array]::CreateInstance([byte],5,5,5)
Andy Schneider
A Systems Engineer in the Greater Seattle Area. I am big fan of PowerShell. Follow me on Twitter, @andyschneider
Updated on September 24, 2020Comments
-
Andy Schneider over 3 years
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[]?