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

abn*_*zer 5 c# powershell tobase64string

我正在尝试将 ~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'
Run Code Online (Sandbox Code Playgroud)

以前,我使用的文件足够小,编码速度相对较快。然而,我现在发现我正在编码的文件会导致该过程耗尽我所有的 RAM,最终速度慢得难以忍受。我感觉有更好的方法可以做到这一点,并且非常感谢任何建议。

fil*_*nic 2

更新 2023-08-17 针对大文件、内存使用和速度

\n

正如 @JohnRanger 提到的,之前的答案存在一个问题,即它的源文件限制为 ~1.5 GiB 并且消耗内存。

\n

解决方案是使用文件流和CryptoStream (... ToBase64Transform ...)

\n
$sourcePath = "C:\\test\\windows_11.iso"\n$targetPath = "C:\\test\\windows_11.iso.b64"\n$size = Get-Item -Path $sourcePath | Select -ExpandProperty Length\n$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()\n\n$converterStream = [System.Security.Cryptography.CryptoStream]::new(\n    [System.IO.File]::OpenRead($sourcePath),\n    [System.Security.Cryptography.ToBase64Transform]::new(), \n    [System.Security.Cryptography.CryptoStreamMode]::Read,\n    $false) # keepOpen = $false => When we close $converterStream, it will close source file stream also\n$targetFileStream = [System.IO.File]::Create($targetPath)\n$converterStream.CopyTo($targetFileStream)\n$converterStream.Close() # And it also closes source file stream because of keepOpen = $false parameter.\n$targetFileStream.Close() # Flush() is called internally.\n\n$stopwatch.Stop()\nWrite-Host "Elapsed: $($stopwatch.Elapsed.TotalSeconds) seconds for $([Math]::Round($size / 1MB))-Mbyte file"\n
Run Code Online (Sandbox Code Playgroud)\n
\n

\xe2\x9a\xa0\xef\xb8\x8f 此代码在 PS7 上的运行速度比 PS5 快 30 倍以上

\n
\n

PS7:在我的机器上,5316 MiB 文件需要 3.1 秒。

\n

文件复制[IO.File]::Copy(...)需要 1.8 秒。

\n
\n

PS5:[System.IO.File]::Create(...)在我的机器上需要 115 秒。\n我在和中使用了缓冲区大小$converterStream.CopyTo(...),但没有得到任何合理的性能差异:对于 5316 MiB,我在默认缓冲区大小下的最差结果为 115 秒,在播放缓冲区大小时为最佳结果 112 秒。也许对于慢速目标,缓冲区大小会产生更大的影响(即使用慢速磁盘或网络共享)。\n性能始终会影响 CPU 的单核。

\n

文件复制[IO.File]::Copy()需要 1.8 秒。

\n