0

我正在使用 PowerShell 通过 API 将文件上传到网站。

在 PS5.1 中,这将使图像采用正确的 B64 编码,由另一端的 API 处理:

$b64 = [convert]::ToBase64String((get-content $image_path -encoding byte))

在 PS7 中,这会因错误而中断:

Get-Content: Cannot process argument transformation on parameter 'Encoding'. 'byte' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method. (Parameter 'name')

我尝试以其他编码读取内容,然后使用 [system.Text.Encoding]:GetBytes() 进行转换,但字节数组总是不同的。例如

PS 5.1> $bytes = get-content -Path $image -Encoding byte ; Write-Host "bytes:" $bytes.count ; Write-Host "First 11:"; $bytes[0..10] 
bytes: 31229
First 11:
137
80
78
71
13
10
26
10
0
0
0

但是在 PowerShell7 上:

PS7> $enc = [system.Text.Encoding]::ASCII
PS7> $bytes = $enc.GetBytes( (get-content -Path $image -Encoding ascii | Out-String)) ; Write-Host "bytes:" $bytes.count ; Write-Host "First 11:"; $bytes[0..10]
bytes: 31416   << larger
First 11:
63 << diff
80 << same
78 << 
71
13
10
26
13 << new
10
0
0

我尝试了其他编码组合,但没有任何改进。谁能建议我哪里出错了?

4

2 回答 2

3

使用 PowerShell 6 字节不再是 Enconding-Parameter 的有效参数。您应该尝试将 AsByteStream-Parameter 与 Parameter Raw 结合使用,如下所示:

$b64 = [convert]::ToBase64String((get-content $image_path -AsByteStream -Raw))

Get-Content 的帮助中甚至还有一个示例,解释了如何使用这些新参数。

于 2020-09-07T18:29:30.753 回答
1

问题出在 Get-Content 上。我绕过了这个问题:

$bytes = [System.IO.File]::ReadAllBytes($image_path)

注意:$image_path 必须是绝对的,而不是相对的。

所以我的 Base64 行变成了:

$b64 = [convert]::ToBase64String([System.IO.File]::ReadAllBytes($image_path))
于 2020-09-02T00:31:39.313 回答