【问题标题】:How to find that a file exist in Azure file share without Mounting using powershell如何在不使用 powershell 挂载的情况下查找 Azure 文件共享中存在的文件
【发布时间】:2021-03-25 22:55:57
【问题描述】:

我试图在 Azure 文件共享中找到一个文件。我知道如何通过以编程方式将 Azure 文件共享挂载到机器上来获取文件。除了挂载文件共享还有其他方法吗?发现我们可以利用 Azure 文件共享的 REST API 功能。但是如何使用 PowerShell 使用 REST API

当我尝试使用以下命令时,我收到指定的错误。

   Invoke-RestMethod -Method Get -Uri "https://test.file.core.windows.net/testartifacts/testdb/version?restype=share&comp=metadata"

   Invoke-RestMethod: InvalidQueryParameterValueValue for one of the query parameters specified in 
  the request URI is
  invalid.

还有如何授权这个请求?

【问题讨论】:

    标签: azure powershell rest azure-devops azure-storage-account


    【解决方案1】:

    您检查以下从 Azure 文件共享中获取文件的方法。

    1,使用 Azure CLI。见here

    az login #Log in interactively
    
    az storage file download \
        --account-name $storageAccountName \
        --account-key $storageAccountKey \
        --share-name $shareName \
        --path "myDirectory/SampleUpload.txt" \
        --dest "SampleDownload.txt" \
        --output none
    

    如果您想使用服务主体登录。您需要先创建一个服务主体。请参阅以下文档以创建服务主体

    Use the portal to create an Azure AD application and service principal.

    Create an Azure service principal with the Azure CLI

    并且您需要在您的 azure story 帐户的角色分配中添加对服务主体的读取权限。

    那你可以login using service principal:

    az login --service-principal --username APP_ID --password PASSWORD --tenant TENANT_ID
    
    az storage file download --account-name ...
    

    2、使用Azure powershell:见here

    Connect-AzAccount  #Log in interactively
    
    $ctx=(Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccName).Context  
         
    $file=Get-AZStorageFile -Context $ctx -ShareName $fileShareName -Directory directiry -Path filepath
    

    你也可以sign in using service principal

    $pscredential = New-Object -TypeName System.Management.Automation.PSCredential($sp.ApplicationId, $sp.Secret)
    Connect-AzAccount -ServicePrincipal -Credential $pscredential -Tenant $tenantId
    

    3、使用 Azure Rest api。见here

    您可以查看以下示例来验证其余 api 调用:

    # Variables
    $TenantId = "" # Enter Tenant Id.
    $ClientId = "" # Enter Service Principal Client Id.
    $ClientSecret = "" # Enter Service Principal Client Secret.
    $Resource = "https://management.core.windows.net/"
    $SubscriptionId = "" # Enter Subscription Id.
    
    $RequestAccessTokenUri = "https://login.microsoftonline.com/$TenantId/oauth2/token"
    
    $body = "grant_type=client_credentials&client_id=$ClientId&client_secret=$ClientSecret&resource=$Resource"
    
    $Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType 'application/x-www-form-urlencoded'
    
    Write-Host "Print Token" -ForegroundColor Green
    Write-Output $Token
    
    # Get file
    $fileUrl = "https://myaccount.file.core.windows.net/myshare/mydirectorypath/myfile"
    
    $Headers = @{}
    
    $Headers.Add("Authorization","$($Token.token_type) "+ " " + "$($Token.access_token)")
    
    $file= Invoke-RestMethod -Method Get -Uri $fileUrl -Headers $Headers
    
    Write-Host "Print File" -ForegroundColor Green
    Write-Output $file
    

    查看详细示例here

    【讨论】:

      【解决方案2】:

      如果要检查 Azure 文件共享中是否存在文件,可以使用 Azure File Rest API Get File Properties。关于调用API如何做auth,我们可以使用Shared Key授权。更多详情请参考here

      例如

      $accesskey="<storage account key>"
      $storageAccount = "andyprivate"
      $shareName="share2"
      $filePath="test1.xml"
      $date =  (Get-Date).ToUniversalTime().AddYears(1).toString('R')
      $version = "2020-04-08"
      
      $stringToSign = "HEAD`n`n`n`n`n`n`n`n`n`n`n`nx-ms-date:$date`nx-ms-version:$version`n/$storageAccount/$shareName/$filePath"
       
      $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"}
      
      $url="https://$storageAccount.file.core.windows.net/$shareName/$filePath"
      
      try{
      
       $res=Invoke-WebRequest -Uri $url -Method Head -Headers $headers -UseBasicParsing
       
      }catch{
      
        if($_.Exception.Response.StatusCode.value__ -eq 404){
         write-host "The file does not exist" -ForegroundColor Red
        }
       
      }
      
      
      

      【讨论】:

        猜你喜欢
        • 2021-02-18
        • 2018-03-29
        • 2011-12-02
        • 2017-07-10
        • 1970-01-01
        • 1970-01-01
        • 2012-03-20
        • 1970-01-01
        • 2019-04-28
        相关资源
        最近更新 更多