Get File from AWS S3 via Powershell

Not battle-tested at all.  Use at your own risk.  Works for me though.  You’ll need an $accessKey and $secretKey variables set outside the scope for this to work.  The $bucketName is the bucket that the file is located in.  The $fileName is the name of the file in said bucket.  The $dest is where you want to write the file locally.  The $logFile does nothing at this point.

function GetS3([string]$bucketName, [string]$fileName, [string]$dest, [string]$logFile)
{
	$AmazonS3 = [Amazon.AWSClientFactory]::CreateAmazonS3Client($accessKey, $secretKey)
	$S3GetRequest = New-Object  Amazon.S3.Model.GetObjectRequest
	$S3GetRequest.BucketName = $bucketName
	$S3GetRequest.Key = $fileName

	$S3Response = $AmazonS3.GetObject($S3GetRequest);
	if($S3Response -eq $null){
	    Write-Error "ERROR: Amazon S3 get requrest failed. Script halted."
	    exit 1
	}

	$stream = $S3Response.ResponseStream;
	$fileStream = new-object system.IO.FileStream($dest, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write);
	$byteArray = New-Object byte[] 32768
	[int]$bytesRead = 0;
	do
	{
		$bytesRead = $stream.read($byteArray, 0, $byteArray.length);
		$fileStream.write($byteArray, 0, $bytesRead);
	}
	while($bytesRead -gt 0)
	$fileStream.flush();

	$fileStream.close();
	$stream.close()

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: