10

我需要将文件从简单存储服务下载到本地文件夹并计算本地文件夹中的文件数量并检查简单存储服务,然后发送带有文件数量的邮件。

我试图从简单的存储服务下载文件,但我收到了类似get-s3object commandnotfoundexception. 我该如何解决这个问题?

我采取的代码参考

# Your account access key - must have read access to your S3 Bucket
$accessKey = "YOUR-ACCESS-KEY"
# Your account secret access key
$secretKey = "YOUR-SECRET-KEY"
# The region associated with your bucket e.g. eu-west-1, us-east-1 etc. (see http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-regions)
$region = "eu-west-1"
# The name of your S3 Bucket
$bucket = "my-test-bucket"
# The folder in your bucket to copy, including trailing slash. Leave blank to copy the entire bucket
$keyPrefix = "my-folder/"
# The local file path where files should be copied
$localPath = "C:\s3-downloads\"    

$objects = Get-S3Object -BucketName $bucket -KeyPrefix $keyPrefix -AccessKey $accessKey -SecretKey $secretKey -Region $region

foreach($object in $objects) {
    $localFileName = $object.Key -replace $keyPrefix, ''
    if ($localFileName -ne '') {
        $localFilePath = Join-Path $localPath $localFileName
        Copy-S3Object -BucketName $bucket -Key $object.Key -LocalFile $localFilePath -AccessKey $accessKey -SecretKey $secretKey -Region $region
    }
}
4

3 回答 3

20

由于这个问题是“powershell 下载 s3 文件”的最佳 Google 结果之一,我将回答标题中的问题(即使实际问题文本不同):

Read-S3Object -BucketName "my-s3-bucket" -KeyPrefix "path/to/directory" -Folder .

Set-AWSCredentials如果它不是公共存储桶,您可能需要调用。

于 2018-10-26T07:10:23.030 回答
5

与 Will 的示例类似,如果要下载保持目录结构的“文件夹”的全部内容,请尝试:

Get-S3Object -BucketName "my-bucket" -KeyPrefix "path/to/directory" | Read-S3Object -Folder .

https://docs.aws.amazon.com/powershell/latest/reference/items/Read-S3Object.html上的 MS doc提供了更高级的过滤示例。

于 2019-11-19T06:34:38.030 回答
4

如果您已安装 AWS PowerShell 模块,则您尚未将其正确加载到当前会话中。我们将此识别为问题,因为您指定的错误意味着找不到给定的 cmdlet。

首先通过以下任何选项验证模块是否已安装:

将模块加载到现有会话中:(PowerShell v3 和 v4):

从文档中:

在 PowerShell 4.0 及更高版本中,Import-Module 还会搜索 Program Files 文件夹以查找已安装的模块,因此无需提供模块的完整路径。您可以运行以下命令来导入 AWSPowerShell 模块。在 PowerShell 3.0 及更高版本中,在模块中运行 cmdlet 还会自动将模块导入会话。

要验证安装是否正确,请将以下命令添加到脚本的开头:

PS C:\> Import-Module AWSPowerShell

将模块加载到现有会话中:(PowerShell v2):

要验证安装是否正确,请将以下命令添加到脚本的开头:

PS C:\> Import-Module "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\AWSPowerShell.psd1"

使用 Windows PowerShell 为 AWS 桌面快捷方式打开一个新会话:

一个快捷方式将添加到您的桌面,该快捷方式启动 PowerShell,并将正确的模块加载到会话中。如果您的安装成功,则应该存在此快捷方式,并且还应该正确加载 AWS PowerShell 模块,而无需您付出额外的努力。

从文档中:

安装程序会创建一个名为 Amazon Web Services 的开始菜单组,其中包含一个名为 Windows PowerShell for AWS 的快捷方式。对于 PowerShell 2.0,此快捷方式会自动导入 AWSPowerShell 模块,然后运行 ​​Initialize-AWSDefaults cmdlet。对于 PowerShell 3.0,只要您运行 AWS cmdlet,就会自动加载 AWSPowerShell 模块。因此,对于 PowerShell 3.0,安装程序创建的快捷方式仅运行 Initialize-AWSDefaults cmdlet。有关 Initialize-AWSDefaults 的更多信息,请参阅使用 AWS 凭证。

延伸阅读:

于 2015-12-30T17:35:00.733 回答