使用 Powershell 对大型 Zip 文件进行 Base64 编码

问题描述

我正在尝试将大约 66MB 的 zip 文件 base64 编码为字符串,然后使用 Powershell 将其写入文件。我正在处理一个限制,最终我必须将 base64 编码的文件字符串直接包含到 Powershell 脚本中,这样当脚本在不同的位置运行时,可以从以下位置重新创建 zip 文件它。我不仅限于使用 Powershell 创建 base64 编码的字符串。这是我最熟悉的。

我目前使用的代码

$file = 'C:\zipfile.zip'
$filebytes = Get-Content $file -Encoding byte
$fileBytesBase64 = [System.Convert]::ToBase64String($filebytes)
$fileBytesBase64 | Out-File 'C:\base64encodedString.txt'

以前,我使用过的文件足够小,因此编码速度相对较快。但是,我现在发现我正在编码的文件导致进程占用了我所有的 RAM,并且最终变得非常缓慢。我觉得有更好的方法可以做到这一点,并希望得到任何建议。

解决方法

我的情况是编码或解码 117-Mb 文件不到 1 秒。

Src file size: 117.22 MiB
Tgt file size: 156.3 MiB
Decoded size: 117.22 MiB
Encoding time: 0.294
Decoding time: 0.708

代码 I 制定措施:

$pathSrc = 'D:\blend5\scena31.blend'
$pathTgt = 'D:\blend5\scena31.blend.b64'
$encoding = [System.Text.Encoding]::ASCII

$bytes = [System.IO.File]::ReadAllBytes($pathSrc)
Write-Host "Src file size: $([Math]::Round($bytes.Count / 1Mb,2)) MiB"
$swEncode = [System.Diagnostics.Stopwatch]::StartNew()
$B64String = [System.Convert]::ToBase64String($bytes,[System.Base64FormattingOptions]::None)
$swEncode.Stop()
[System.IO.File]::WriteAllText($pathTgt,$B64String,$encoding)

$B64String = [System.IO.File]::ReadAllText($pathTgt,$encoding)
Write-Host "Tgt file size: $([Math]::Round($B64String.Length / 1Mb,2)) MiB"
$swDecode = [System.Diagnostics.Stopwatch]::StartNew()
$bytes = [System.Convert]::FromBase64String($B64String)
$swDecode.Stop()
Write-Host "Decoded size: $([Math]::Round($bytes.Count / 1Mb,2)) MiB"

Write-Host "Encoding time: $([Math]::Round($swEncode.Elapsed.TotalSeconds,3)) s"
Write-Host "Decoding time: $([Math]::Round($swDecode.Elapsed.TotalSeconds,3)) s"