不使用 Get-content 将变量转换为字节

converting a variable to a byte without using Get-content

我需要将 $var 转换为字节数组以将其推送到 [convert]::ToBase64String($var) 以上传到 sql 数据库。所有这些都没有使用 Get-Content -file -encoding Byte,因为此脚本在 Azure 中是 运行,无法访问任何文件系统。

Header 包含 Auth 不记名令牌。

$var = (invoke-restmethod -uri ...800x800.png -method -get -headers $head)

数据流如下所示:

PNG

IHDR Ûph gAMA ±üa cHRM z& ú è u0 ê` : pºQ< bKGD ÿ ÿ ÿ ½§ tIMEã 5Þ IDATxÚìý[°e[}ß?? ...

 [System.Array]$myarray = (invoke-restmethod...
 $bytes = [System.Text.Encoding]::UTF8.GetBytes($myarray)
 $encoded_array = [System.Convert]::ToBase64String($bytes)

在解码 base64 字符串时,它被感知为 application/octet 而不是图像八位字节并且被破坏了。

但是,运行 通常

invoke-restmethod ... ... -outfile c:\test.png
[System.Convert]::ToBase64String (get-content c\test.png -encoding byte)

正常工作,应该如此。

重现:

(invoke-restmethod -uri "URI to .png" -method -get )

然后继续使用它,直到您可以将其转换为经过编码的 base 64 字符串。

想要的结果是图像的 base64 字符串。
当前结果是 base 64 字符串,即 ???并且没有被解码成任何有用的东西。

您可以使用以下代码将图像转换为 byte64:

1.

$file='C:\aaa.png'
$strm=([io.FileInfo]$file).OpenRead()
$bytes=New-Object byte[] $strm.Length
$strm.Read($bytes,0,$strm.Length)
$base64String=[convert]::ToBase64String($bytes)
$base64String

2.

$url='C:\aaa.png' or 'https://xxx/aaa.png'
$wc=New-Object System.Net.WebClient
$bytes=$wc.DownloadData($url)
$base64String1=[convert]::ToBase64String($bytes)
$base64String1

3.

$url='C:\aaa.png' or 'https://xxx/aaa.png'
$bytes = Invoke-WebRequest -Uri $url -Method Get | Select-Object -ExpandProperty Content
$base64String2=[convert]::ToBase64String($bytes)
$base64String2

然后转到这个link你可以成功地将byte64转换为图像。

我使用这些命令找到了答案:

$wc = New-Object System.Net.WebClient
$wc.Headers["Authorization"] = "Bearer <token>"
$bytes = $wc.DownloadData("URL")
$base64string = [Convert]::ToBase64String($bytes)