我在https://mnaoumov.wordpress.com/2013/08/20/efficient-base64-conversion-in-powershell/
上找到了此代码它适用于Windows 8.1 Powershell 4,但在Powershell 2上,当我将base64字符串解码回文件时,它似乎在文件的末尾添加了一个字节。 Powershell 2还会抛出有关base64字符串无效长度的错误,但它仍然会创建该文件。
我一直试图解决这个问题几个小时,但我不知道.net足以弄明白这个问题。
我使用这些函数来携带数据是一个更大的脚本。它在Powershell 4上没有任何错误。
我需要在超过3000台Windows 7机器上运行,坚持使用Powershell 4不是解决方案。
function ConvertTo-Base64
{
param
(
[string] $SourceFilePath,
[string] $TargetFilePath
)
$SourceFilePath = Resolve-PathSafe $SourceFilePath
$TargetFilePath = Resolve-PathSafe $TargetFilePath
$bufferSize = 9000 # should be a multiplier of 3
$buffer = New-Object byte[] $bufferSize
$reader = [System.IO.File]::OpenRead($SourceFilePath)
$writer = [System.IO.File]::CreateText($TargetFilePath)
$bytesRead = 0
do
{
$bytesRead = $reader.Read($buffer, 0, $bufferSize);
$writer.Write([Convert]::ToBase64String($buffer, 0, $bytesRead));
} while ($bytesRead -eq $bufferSize);
$reader.Dispose()
$writer.Dispose()
}
function ConvertFrom-Base64
{
param
(
[string] $SourceFilePath,
[string] $TargetFilePath
)
$SourceFilePath = Resolve-PathSafe $SourceFilePath
$TargetFilePath = Resolve-PathSafe $TargetFilePath
$bufferSize = 9000 # should be a multiplier of 4
$buffer = New-Object char[] $bufferSize
$reader = [System.IO.File]::OpenText($SourceFilePath)
$writer = [System.IO.File]::OpenWrite($TargetFilePath)
$bytesRead = 0
do
{
$bytesRead = $reader.Read($buffer, 0, $bufferSize);
$bytes = [Convert]::FromBase64CharArray($buffer, 0, $bytesRead);
$writer.Write($bytes, 0, $bytes.Length);
} while ($bytesRead -eq $bufferSize);
$reader.Dispose()
$writer.Dispose()
}
function Resolve-PathSafe
{
param
(
[string] $Path
)
$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
}
ConvertTo-Base64 .\file .\Converted-File.txt