Search code examples
powershellamazon-web-servicesaws-lambdaaws-powershell

In Powershell, how can i get a Base64encoded memorystream of a local zip file?


i've been trying to use the AWS Update-LMFunctionCode to deploy my file to an existing lambda function in AWS.

Differing from the Publish-LMFunction where I can provide just a path to the zipFile (-FunctionZip), the Update-LMFunction wants a memorystream for its -Zipfile argument.

is there an example of loading a local zipfile from disk into a memory stream that works? My initial calls are getting errors that the file can't be unzipped...

$deployedFn =  Get-LMFunction -FunctionName $functionname
        "Function Exists - trying to update"
        try{
            [system.io.stream]$zipStream = [system.io.File]::OpenRead($zipFile)
        [byte[]]$filebytes = New-Object byte[] $zipStream.length
        [void] $zipStream.Read($filebytes, 0, $zipStream.Length)
            $zipStream.Close()
            "$($filebytes.length)"
        $zipString =  [System.Convert]::ToBase64String($filebytes)
        $ms = new-Object IO.MemoryStream
        $sw = new-Object IO.StreamWriter $ms
        $sw.Write($zipString)
        Update-LMFunctionCode -FunctionName $functionname -ZipFile $ms
            }
        catch{
             $ErrorMessage = $_.Exception.Message
            Write-Host $ErrorMessage
            break
        }

docs for the Powershell function is here: http://docs.aws.amazon.com/powershell/latest/reference/items/Update-LMFunctionCode.html although it wants to live in a frame...


Solution

  • Try using the CopyTo method to copy from one stream to another:

    try {
        $zipFilePath = "index.zip"
        $zipFileItem = Get-Item -Path $zipFilePath
        $fileStream = $zipFileItem.OpenRead()
        $memoryStream = New-Object System.IO.MemoryStream
        $fileStream.CopyTo($memoryStream)
    
        Update-LMFunctionCode -FunctionName "PSDeployed" -ZipFile $memoryStream
    }
    finally {
        $fileStream.Close()
    }