如何使用PowerShell将Azuremark列表Blob Rest API使用nextmarker参数

问题描述

使用以下脚本,我可以获取blob,但是由于我有5000多个项目,因此需要使用下一个标记获取所有结果,因此需要帮助来形成$ stringtosign用于标记,$ URL用于下一个标记。在If($ nextMarker)内的代码方面需要帮助。参考:https://docs.microsoft.com/en-us/rest/api/storageservices/list-blobs

$StorageAccount = 'xxxxxxx' 
$ContainerName = 'xxxxxx' 
$accesskey = 'xxxxxxxxxxxxx'

$date = [System.DateTime]::UtcNow.ToString("R",[Globalization.CultureInfo]::InvariantCulture)

$version = '2019-12-12'
$stringToSign = "GET`n`n`n`n`n`n`n`n`n`n`n`n"+
           "x-ms-date:$date`nx-ms-version:$version`n"+
           "/$StorageAccount/$ContainerName`ncomp:list`nrestype:container" 
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Convert]::FromBase64String($accesskey)
$signature = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($stringToSign))
$signature = [Convert]::ToBase64String($signature)

$headers=@{"x-ms-date"=$date;
           "x-ms-version"= $version;
           "Authorization"= "SharedKey $($storageAccount):$signature";
           "ContentType"="application/xml"
}


$URI = "https://$StorageAccount.blob.core.windows.net/" + $ContainerName + "?restype=container&comp=list"

$blobs = Invoke-RestMethod -method GET -Uri $URI -Headers $headers

$Result = [xml]($blobs -replace '',"")
#$Result.EnumerationResults.Blobs.Blob | % {$length = $length + $_.Properties.'Content-Length'}

$NextMarker = $Result.EnumerationResults.NextMarker

If ($NextMarker){

$stringToSign = "GET`n`n`n`n`n`n`n`n`n`n`n`n"+
           "x-ms-date:$date`nx-ms-version:$version`n"+
"/$StorageAccount/$ContainerName`ncomp:list`n`nrestype:container`nmarker:$NextMarker`nmaxresults:5000" 
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Convert]::FromBase64String($accesskey)
$signature = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($stringToSign))
$signature = [Convert]::ToBase64String($signature)

$headers=@{"x-ms-date"=$date;
           "x-ms-version"= $version;
           "Authorization"= "SharedKey $($storageAccount):$signature";
           "ContentType"="application/xml"
}


$URI = "https://$StorageAccount.blob.core.windows.net/" + $ContainerName + "?restype=container&comp=listmarker=$NextMarker&maxresults=5000"

$blobs = Invoke-RestMethod -method GET -Uri $URI -Headers $headers



}

解决方法

If ($NextMarker){ }代码块中,请将$stringToSign替换为以下内容:

$stringToSign = "GET`n`n`n`n`n`n`n`n`n`n`n`n"+
           "x-ms-date:$date`nx-ms-version:$version`n"+
           "/$StorageAccount/$ContainerName`ncomp:list`nmarker:$NextMarker`nmaxresults:5000`nrestype:container"

没有其他更改。在我这边效果很好。