存储 REST API Returns 经常无法解析远程名称

Storage REST API Returns Remote Name Could Not be Resolve Often

我正在调用存储 REST API 以使用

获取容器名称
Invoke-WebRequest -Method GET -Uri $storage_url -Headers $headers

此命令经常 returns 'remote name could not be resolved error',即使存储帐户存在且可访问。只是 运行 命令再次给出正确的结果。

Invoke-WebRequest : The remote name could not be resolved: '<storageAccountName>.blob.core.windows.net'
At line:1 char:1
+ Invoke-WebRequest -Method GET -Uri $storage_url -Headers $headers #In ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

根据您提供的信息,您使用客户端凭据流获取访问令牌,然后使用该令牌调用 Storage Rest API - List Containers

您可以使用下面的脚本,它适用于我。

确保您使用的服务主体具有 RBAC 角色,例如Contributor/Owner 在您的存储帐户中 -> Access Control,如果没有,请单击 Add 添加它。

$ClientID       = "xxxxxxx" 
$ClientSecret   = "xxxxxxx"  
$tennantid      = "xxxxxxx"
$storageaccountname = "joystoragev2"

$TokenEndpoint = {https://login.microsoftonline.com/{0}/oauth2/token} -f $tennantid 
$Resource = "https://storage.azure.com/"

$Body = @{
        'resource'= $Resource
        'client_id' = $ClientID
        'grant_type' = 'client_credentials'
        'client_secret' = $ClientSecret
}

$params = @{
    ContentType = 'application/x-www-form-urlencoded'
    Headers = @{'accept'='application/json'}
    Body = $Body
    Method = 'Post'
    URI = $TokenEndpoint
}

$token = Invoke-RestMethod @params

$accesstoken = $token.access_token

$url = {https://{0}.blob.core.windows.net/?comp=list} -f $storageaccountname

$header = @{
    'Authorization' = 'Bearer ' + $accesstoken
    'x-ms-version' = '2019-02-02'
}

$response = Invoke-WebRequest –Uri $url –Headers $header –Method GET

$response.RawContent