如何在 Azure 文件共享目录中设置目录元数据

How to Set Directory Metadata in Azure File Share directory

我正在尝试使用 Powershell 在 Azure 文件共享中设置目录的元数据。休息 API 文档是 https://docs.microsoft.com/en-us/rest/api/storageservices/set-directory-metadata 如果我从下面的代码中删除 x-ms-meta-name:value 那么它会工作并且它会删除现有的元数据但是当我尝试添加它时。它给出了身份验证错误。 post末尾提到错误。下面是脚本

$Version = "2017-04-17"
$AccessKey = 'xxxxx'
$storageAccount = 'xxxxx'
$ShareName = 'test'
$Directory = 'testdir'

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

$stringToSign = "PUT`n`n`n`n`n`n`n`n`n`n`n`n"+
           "x-ms-date:$date`nx-ms-version:$version`n" + "x-ms-meta-name:value`n" +
           "/$storageAccount/$ShareName/$Directory`ncomp:metadata`nrestype:directory" 
$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";
           "x-ms-meta-name"= "value"
           
                      
}
$URI = "https://$storageAccount.file.core.windows.net/$($ShareName)/$($Directory)?restype=directory&comp=metadata"

Invoke-WebRequest $URI -Method 'Put' -Headers $headers -UseBasicParsing

错误如下

Invoke-WebRequest : AuthenticationFailedServer failed to authenticate the 
request. Make sure the value of Authorization header is formed correctly 
including the signature.
RequestId:2b0f9122-601a-00a9-4c0d-0e6c51000000
Time:2022-01-20T14:55:56.8906064ZThe MAC signature found in the HTTP request 
'Q1HSohGOPCL5uR2WuFqpn/Ix8ZgEBqXF8EjXC4Jd4rs=' is not the same as any computed 
signature. Server used following string to sign: 'PUT
x-ms-date:Thu, 20 Jan 2022 14:55:51 GMT
x-ms-meta-name:value
x-ms-version:2017-04-17
/xxxxx/test/testdir
comp:metadata
restype:directory'.
At line:26 char:8
+ $res = Invoke-WebRequest $URI -Method 'Put' -Headers $headers -UseBas ...
+        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:Htt 
   pWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe 
   ll.Commands.InvokeWebRequestCommand

请更改以下代码行:

$stringToSign = "PUT`n`n`n`n`n`n`n`n`n`n`n`n"+
           "x-ms-date:$date`nx-ms-version:$version`n" + "x-ms-meta-name:value`n" +
           "/$storageAccount/$ShareName/$Directory`ncomp:metadata`nrestype:directory" 

$stringToSign = "PUT`n`n`n`n`n`n`n`n`n`n`n`n"+
           "x-ms-date:$date`n" + "x-ms-meta-name:value`n" + "x-ms-version:$version`n" +
           "/$storageAccount/$ShareName/$Directory`ncomp:metadata`nrestype:directory" 

基本上 x-ms-* headers 必须按字母顺序排序。