28

我有一些使用 COM API 的 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,我发现它正在寻找一个基本类型为 System.Array 的 Byte[]。

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

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

4

5 回答 5

41

这个答案是针对没有上下文的问题。我添加它是因为搜索结果。

[System.Byte[]]::CreateInstance([System.Byte],<Length>)
于 2017-10-03T20:48:26.923 回答
23

在 PS 5.1 中,这:

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

对我不起作用。所以我做了:

new-object byte[] 4

这导致了一个空字节[4]:

0
0
0
0
于 2017-11-20T21:01:27.000 回答
19

将其转换为字节数组:

[byte[]]$bytes = Get-Content $file -Encoding byte
于 2013-07-04T15:56:58.243 回答
18

可能还有更多方法,但这些是我能想到的:

直接数组初始化:

[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

创建一个零初始化数组

$b = [System.Array]::CreateInstance([byte],5)
$b = [byte[]]::new(5)        # Powershell v5+
$b = New-Object byte[] 5
$b = New-Object -TypeName byte[] -Args 5

如果你想要一个数组byte[](二维数组)

# 5 by 5
[byte[,]] $b = [System.Array]::CreateInstance([byte],@(5,5)) # @() optional for 2D and 3D
[byte[,]] $b = [byte[,]]::new(5,5)

此外:

# 3-D
[byte[,,]] $b = [byte[,,]]::new(5,5,5)
[byte[,]] $b = [System.Array]::CreateInstance([byte],5,5,5)
于 2019-07-20T04:37:21.110 回答
-1

FWIW 如果您只想将任意字符串编码为 byte[] 数组:

$foo = "This is a string"
[byte[]]$bar = $foo.ToCharArray()
于 2020-09-23T22:04:52.833 回答