【问题标题】:Powershell code to download all subfolder of Blob content to local into single folderPowershell 代码将 Blob 内容的所有子文件夹下载到本地到单个文件夹中
【发布时间】:2020-07-04 16:04:20
【问题描述】:

场景说明 - 以前我尝试使用 PS 代码针对特定的 blob 路径文件夹和日期参数化执行将 blob 内容下载到本地的活动。现在工作正常。但是需要进行如下更改 - 肯定欢迎提出想法,以便我可以推动它。 我在 blob 路径中有多个子文件夹假设 - A/B/C、C 有文件夹 1、文件夹 2 等.... 如何使用 PS 代码将所有内容放在一个文件夹中。现在,在 C 中,具有多个 blob 内容的子文件夹正在下载为一个文件夹,假设为 -00,01,02,就像 blob 中可用的内容一样。

【问题讨论】:

  • 请编辑您的问题,使其至少可读。
  • 完成了,...上面的事情只有一个问题。
  • 因此,如果我理解正确,您希望从本地计算机上单个文件夹中的子文件夹中下载所有文件。对吗?
  • 是的,你是对的,你可以这样做 - 子文件夹中可用的所有文件,多个子文件夹可作为单个文件夹使用,目前它得到了 - 就像来自 blob 结构的这种格式。 A/B/C 是 blob c 有日期文件夹,并且在日期里面它有 01,02.... 10-20 个包含 blob 内容的文件夹..
  • 请不要将代码放入 cmets。而是编辑您的问题并将其包含在其中。另外,请确保代码格式正确 (stackoverflow.com/help/formatting)。

标签: azure powershell azure-blob-storage


【解决方案1】:

更新 0327:

下面的代码会将每个文件下载到每个文件夹中:

$container_name="test10"
$destination_path="d:\ccc"

$user="xxx"
$pwd = "xxxxxx"
$context = New-AzStorageContext -StorageAccountName $user -StorageAccountKey $pwd

$path = "A/B" 
#$date = (get-date).AddDays(-1).ToString("yyyy-MM-dd")
$date="2020-03-24"

$blobs = Get-AzStorageBlob -Container $container_name -Prefix "$path/$date" -Context $context

$i=0
foreach($blob in $blobs )
{

$blobName = $blob.Name -split "/" | select -Last 1
Write-Output "downloading blob $blobName"

$finalDirectory = New-Item -ItemType Directory -Force -Path "$($destination_path)\$i"

$finalPath = "$($finalDirectory)\$($blobName)"
$blob.ICloudBlob.DownloadToFile($finalPath,[System.IO.FileMode]::CreateNew)
$i=$i+1
}

Write-Output "***completed downloading***"

原答案:

如果您使用Get-AzStorageBlobContent cmdlet 下载 blob,则无法更改结构。

但是你可以使用$blob object$blob.ICloudBlob.DownloadToFile方法,可以满足你的要求:

示例代码(我自己测试,所有的blob,包括子文件夹中的blob都下载到本地一个单独的文件夹中):

$container_name="test10"
$destination_path="d:\ccc"

$user="storage_account_name"
$pwd = "storage_account_key"
$context = New-AzStorageContext -StorageAccountName $user -StorageAccountKey $pwd    

$path = "A/B" 
$date = (get-date).AddDays(-1).ToString("yyyy-MM-dd")

$blobs = Get-AzStorageBlob -Container $container_name -Prefix "$path/$date" -Context $context

foreach($blob in $blobs )
{

#get the name by removing the directory/folder name of a blob
$blobName = $blob.Name -split "/" | select -Last 1
Write-Output "downloading blob $blobName"

$finalPath = "$($destination_path)\$($blobName)"
$blob.ICloudBlob.DownloadToFile($finalPath,[System.IO.FileMode]::CreateNew)

}

Write-Output "***completed downloading***"

如果您还有其他问题,请告诉我。

【讨论】:

  • 刚刚看到您的代码,将在我的一端进行端到端测试,并了解这是否符合我的要求,如果有任何问题我会在这里与您联系。感谢您的出色工作..!!
  • @anirudhbragadeesan,是的,如果有问题请告诉我。
  • 您能否快速替换上述代码中需要替换的内容,以便我检查一次。谢谢
  • @anirudhbragadeesan,只需替换 $container_name / $destination_path / $user / $pwd 的值
  • 现在尝试这样做,但没有下载发生或按预期执行我们可以在调用中快速同步。
猜你喜欢
  • 1970-01-01
  • 2021-04-09
  • 2021-11-29
  • 1970-01-01
  • 2021-02-22
  • 2019-10-12
  • 1970-01-01
  • 2023-03-27
  • 2019-02-20
相关资源
最近更新 更多