powershell将文件移动到亚马逊s3

时间:2014-03-10 14:23:30

标签: powershell amazon-web-services amazon-s3 aws-powershell

我有以下PowerShell脚本,可以将文件移动到我的亚马逊桶中,并且所有工作都适用于一些小文件,但是当复制较大的文件时,for循环继续循环并开始复制,然后其他人完成它并且它没有我需要很长时间才能同时传输100个文件。

我想要的是能够将同时文件传输的数量限制为5或10?

foreach ($line in $csv) {  

#--------------------Transfer files Put in a for each loop here---------------------------
$SourceFolder  =$line.destination
$sourceFile = $line.name

if(test-Path -path $SourceFolder){
    Write-S3Object -BucketName $BucketName  -Key $sourceFile  -File  $SourceFolder 
    #check fro missing files
        $S3GetRequest = New-Object Amazon.S3.Model.S3Object  #get-S3Object  -BucketName   $BucketName  -Key $sourceFile
        $S3GetRequest = get-S3Object  -BucketName $BucketName  -Key $sourceFile

        if($S3GetRequest -eq $null){
            Write-Error "ERROR: Amazon S3 get requrest failed. Script halted."
            $sourceFile + ",Transfer Error" |out-file $log_loc -append
    }
}else {$SourceFolder + ",Missing File Error" |out-file $log_loc -append}

}

1 个答案:

答案 0 :(得分:5)

从描述中,听起来你的大文件正在触发分段上传。来自Write-S3Object documentation

  

如果要上载大文件,Write-S3Object cmdlet将使用分段上传来完成请求。如果分段上传中断,Write-S3Object cmdlet将尝试中止分段上传。

不幸的是,Write-S3Object并没有真正的本地方式来处理你的用例。但是,Multipart Upload Overview描述了我们可以利用的行为:

  

分段上传分为三个步骤:您启动上传,上传对象部件,并在上传完所有部件后,完成分段上传。收到完整的分段上传请求后,Amazon S3会从上传的部分构建对象,然后您可以像访问存储桶中的任何其他对象一样访问该对象。

这让我怀疑我们可以使用Get-S3Object ping对象以查看它们是否存在。如果没有,我们应该等待上传更多文件,直到他们这样做。

我已经在下面创建了一个脚本来执行此操作 - 它会遍历一组文件并在您上传文件时收集它们的名称。一旦超过5个上传文件,脚本将检查它们是否存在,如果存在则继续。否则,它将继续检查它们是否存在。

$BucketName = "myS3Bucket"
$s3Directory = "C:\users\$env:username\documents\s3test"
$concurrentLimit = 5
$inProgressFiles = @()

foreach ($i in Get-ChildItem $s3Directory) 
{ 
  # Write the file to S3 and add the filename to a collection.
  Write-S3Object -BucketName $BucketName -Key $i.Name -File $i.FullName 
  $inProgressFiles += $i.Name

  # Wait to continue iterating through files if there are too many concurrent uploads
  while($inProgressFiles.Count -gt $concurrentLimit) 
  {
    Write-Host "Before: "$($inProgressFiles.Count)

    # Reassign the array by excluding files that have completed the upload to S3.
    $inProgressFiles = @($inProgressFiles | ? { @(get-s3object -BucketName $BucketName -Key $_).Count -eq 0 })

    Write-Host "After: "$($inProgressFiles.Count)

    Start-Sleep -s 1
  }

  Start-Sleep -s 1
}

您可以通过更改foreach循环来使用csv内容来根据需要对其进行修改。我为你添加了睡眠声明,以便能够观看它并看看它是如何工作的 - 随意更改/删除它们。