如何在不使用 powershell 挂载的情况下查找 Azure 文件共享中存在的文件

How to find that a file exist in Azure file share without Mounting using powershell

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

当我尝试使用以下命令时,出现了指定的错误。

   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 文件共享获取文件的方法。

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 故事帐户的角色分配中添加对服务主体的读取权限。

那么你可以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

如果要检查 Azure 文件共享中是否存在文件,可以使用 Azure File Rest API Get File Properties. Regarding how to do auth to call the API, we can use the Shared Key authorization. For more details, please refer to 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
  }
 
}