gpt4 book ai didi

powershell - 在 Powershell 5.1 中与 Base64 相互转换

转载 作者:行者123 更新时间:2023-12-04 07:51:41 25 4
gpt4 key购买 nike

我找到了一些资源(包括 Convert base64 string to file,实际上是重复的,因为它是我用来构建它的资源之一)但我似乎无法让它工作。

我有以下代码(大致 - 显然它被精简了,)并且我可以根据评论验证流程的大部分步骤。

$pic = Get-Content 'testpic.png'
# $pic looks like a binary dump.

$picBytes = [System.Text.Encoding]::Unicode.GetBytes($pic)
$ $picBytes is an array of bytes. Quite spammy.

$picEncoded = [Convert]::ToBase64String($picBytes)
# $picEncoded is indeed a Base64 string. Halfway there!

$picDecoded = [Convert]::FromBase64String($picEncoded)
# Also an array of bytes. I'm assuming they're right for now...

$outFile = "pic.png"
[IO.File]::WriteAllBytes($outFile,$picDecoded)
# but I get no output file and no error?

我在这里错过了什么?对于它的值(value),我愿意看看其他解决方案 - 但 Base64 有点重要(因为我将数据存储在脚本中。)

最佳答案

要在 PowerShell 中按原样读取二进制文件到内存中,请使用 Get-Content-AsByteStream 开关 (PowerShell (Core) 7+)/-Encoding Byte(Windows PowerShell,版本高达 v5 ... >:

# Windows PowerShell (up to v5.1).
# Note: In PowerShell (Core) v7+, you must use -AsByteStream instead of
# -Encoding Byte
$picBytes = Get-Content testpic.png -Encoding Byte -Raw

注意:PowerShell 版本之间的这种语法变化令人遗憾,如 GitHub issue #7986 中所述。 .如果有足够多的人表现出兴趣,可以想象 -Encoding Byte 将被重新引入以实现跨版本的一致性和兼容性。

$picBytes,作为一个[byte[]]数组,然后可以直接传递给[Convert]::ToBase64String()


要将文件名/路径传递给 .NET 方法,始终传递完整路径,绝不是相对路径或仅仅是文件姓名:

这是必要的,因为 .NET 的工作目录通常不同于 PowerShell 的
这种差异很不幸,但无法避免,如 this answer 中所述。 .

最简单情况下 - 如果您的当前位置是基于文件系统的位置在 PowerShell 特定驱动器上:

$outFile = "$PWD/pic.png" # Use *full path*
[IO.File]::WriteAllBytes($outFile, $picDecoded)

完全稳健方法需要更多工作:

$outFile = Join-Path (Get-Location -PSProvider FileSystem).ProviderPath pic.png
[IO.File]::WriteAllBytes($outFile, $picDecoded)

关于powershell - 在 Powershell 5.1 中与 Base64 相互转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66934993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com