繁体   English   中英

如何在不使用 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。 这里

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

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

使用门户创建 Azure AD 应用程序和服务主体

使用 Azure CLI 创建 Azure 服务主体

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

然后您可以使用服务主体登录

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

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

2、使用Azure powershell:看这里

Connect-AzAccount  #Log in interactively

$ctx=(Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccName).Context  
     
$file=Get-AZStorageFile -Context $ctx -ShareName $fileShareName -Directory directiry -Path filepath

您还可以使用 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。 这里

您可以查看以下示例来验证 rest 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

请参阅此处的详细示例。

If you want to check if a file exists in Azure file share, you can use Azure File Rest API Get File Properties . 关于如何调用 API 进行认证,我们可以使用 Shared Key 授权。 更多详情,请参考这里

例如

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


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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