问题描述
在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
我尝试了其他编码组合,但没有任何改进。 谁能建议我要去哪里错了?
解决方法
问题出在与Get-Content有关。我使用以下方法绕过了问题:
$bytes = [System.IO.File]::ReadAllBytes($image_path)
注意:$ image_path必须是绝对的,而不是相对的。
所以我的Base64行变成了:
$b64 = [convert]::ToBase64String([System.IO.File]::ReadAllBytes($image_path))
,
使用PowerShell 6字节不再是Enconding-Parameter的有效参数。您应该像这样将AsByteStream-Parameter与参数Raw结合使用:
$b64 = [convert]::ToBase64String((get-content $image_path -AsByteStream -Raw))
Get-Content帮助中甚至有一个示例,说明了如何使用这些新参数。