简体   繁体   中英

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

I was trying to find that a file exists in Azure file share. I know how to get the file by mounting the Azure file share to the machine programmatically. Is there any other way other than mounting the file share? Found there is a REST API feature of Azure file share we can utilize for this. But how to use the REST API using PowerShell

When I tried to use the below command I'm getting an error as specified.

   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.

Also how to authorize this request?

You check below ways to get the file from Azure file share.

1, Use Azure CLI. See 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

If you want to login using a service principal. You need to create a service principal first. See below document to create a service principal

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

Create an Azure service principal with the Azure CLI

And you need to add the read permission to the service principal in the role assignment of your azure story account.

Then you can login using service principal :

az login --service-principal --username APP_ID --password PASSWORD --tenant TENANT_ID

az storage file download --account-name ...

2, Use Azure powershell: See 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

You can also 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, Using Azure Rest api. See here .

You can check below example to authenticate the rest api call:

# 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

See detailed example here .

If you want to check if a file exists in Azure file share, you can use 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

For example

$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
  }
 
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM