2013-07-04 31 views
11

我有一些使用COM API的PowerShell代码。我在传入字节数组时遇到类型不匹配错误。这里是我如何创建阵列,以及一些类型的信息在PowerShell中创建字节[]

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 

与API打交道了,我发现,它正在寻找一个byte []与基本类型的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 

我想要做的是将$字节转换为$ r.data相同的类型。出于某种原因,$字节被创建为Object []。我如何将它转换为字节[]?

回答

13

其转换为字节数组:

[byte[]]$bytes = Get-Content $file -Encoding byte 
7

这个答案是没有上下文的问题。由于搜索结果,我添加了它。

[System.Byte[]]::CreateInstance([System.Byte],<Length>) 
+1

感谢您给我们!救了我一堆额外的Google搜索 –

+0

没有为我工作。看到我的答案。 – Andrew

+1

@安德鲁,你是对的。我纠正了它。 –

2

在PS 5.1,这样的:

[System.Byte[]]::CreateInstance(<Length>)

并没有为我工作。所以不是我做的事:

new-object byte[] 4

这就造成了一个空字节[4]:

0 
0 
0 
0 
+1

这对我有用。 –