Преобразование файлов в PowerShell 2.0 с ошибками Base64

Я нашел этот код на 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

0 ответов

Другие вопросы по тегам