适用于 AWS 的 PowerShell:仅列出 S3 存储桶中的“文件夹”?

Nic*_*der 4 powershell amazon-s3 amazon-web-services aws-powershell

是否有任何简单的方法可以使用 PowerShell 仅从 S3 存储桶获取“文件夹”列表,而无需列出每个对象,而只需编写不同路径的编译列表的脚本?我正在处理的存储桶中有数十万个单独的对象,这将需要很长时间。

这可能是一个非常愚蠢的问题,如果是这样的话,我很抱歉,但我在谷歌或SO上找不到任何东西来回答这个问题。我尝试向 Get-S3Object 的 -KeyPrefix 和 -Key 参数添加通配符,但无济于事。这是唯一一个似乎能够完成我所追求的任务的 cmdlet。

无意义的背景故事:我只是想确保将文件传输到正确的现有文件夹。我是签约第三方,因此我没有控制台登录访问权限,也不是维护 AWS 账户的人。

我知道使用 Java 和 C# 以及其他语言可以做到这一点,但我正在 PS 中完成与这个相当简单的项目相关的所有其他工作,并希望能够坚持下去。

提前致谢。

Ant*_*ace 6

您可以使用适用于 PowerShell 的 AWS 工具列出存储桶中的对象(通过Get-S3Object)并从响应对象中提取常见前缀。

下面是一个用于递归检索子目录的小库:

function Get-Subdirectories
{
  param
  (
    [string] $BucketName,
    [string] $KeyPrefix,
    [bool] $Recurse
  )

  @(get-s3object -BucketName $BucketName -KeyPrefix $KeyPrefix -Delimiter '/') | Out-Null

  if($AWSHistory.LastCommand.Responses.Last.CommonPrefixes.Count -eq 0)
  {
    return
  }

  $AWSHistory.LastCommand.Responses.Last.CommonPrefixes

  if($Recurse)
  {
    $AWSHistory.LastCommand.Responses.Last.CommonPrefixes | % { Get-Subdirectories -BucketName $BucketName -KeyPrefix $_ -Recurse $Recurse }
  }
}

function Get-S3Directories
{
  param
  (
    [string] $BucketName,
    [bool] $Recurse = $false
  )

  Get-Subdirectories -BucketName $BucketName -KeyPrefix '/' -Recurse $Recurse
}
Run Code Online (Sandbox Code Playgroud)

此递归函数依赖于在每次迭代时更新 KeyPrefix 以检查传递给它的每个 KeyPrefix 中的子目录。通过将分隔符设置为'/',在第一次出现分隔符之前与 KeyPrefix 字符串匹配的键将被滚入 $AWSHistory 的最后一个响应中的 CommonPrefixes 集合中。

要仅检索 S3 存储桶中的顶级目录:

PS C:/> Get-S3Directories -BucketName 'myBucket'
Run Code Online (Sandbox Code Playgroud)

要检索 S3 存储桶中的所有目录:

PS C:/> Get-S3Directories -BucketName 'myBucket' -Recurse $true
Run Code Online (Sandbox Code Playgroud)

这将返回一个字符串集合,其中每个字符串都是一个公共前缀。

示例输出:

myprefix/
myprefix/txt/
myprefix/img/
myotherprefix/
...
Run Code Online (Sandbox Code Playgroud)