【问题标题】:How to Dynamically write a export CSV file to Azure blob container using PowerShell?如何使用 PowerShell 将导出 CSV 文件动态写入 Azure blob 容器?
【发布时间】:2021-12-06 13:33:03
【问题描述】:

我有一个导出 VM 指标信息的 Azure Powershell 命令。

(Get-AzMetric -ResourceID $id -StartTime $s -EndTime -MetricName $metric).Data |Export-Csv -Path $blobpath

$blobpath 我已作为 blob 容器的 SAS URL 给出。

我想为 -Path 参数添加 blobpath,但出现错误“找不到驱动器”。 [![


]1]1

【问题讨论】:

  • 请编辑您的问题并包含您用于上传 blob 的 PS 命令。
  • @Gaurav - 它是包含 blobURL+SAS 令牌+csvfilename 的 SAS URL
  • 谢谢。 Export-Csv 只能写入本地文件系统。你要做的就是先写入文件系统,然后使用Set-AzBlobContent上传blob。
  • 如果您不想先将 CSV 文件写入磁盘然后上传,请查看我的回答 here。 HTH。
  • @Gaurav - 谢谢你的回答。我还提到了您关于将 &comp=list&restype=container 添加到 SAS URL 的另一个答案。但是对于我来说仍然失败,服务器错误 409 主要是由于公共访问被阻止到存储。我尝试从 cloud shell 和 ADO 执行它。但由于访问问题,它对我不起作用。但是下面突出显示的两个答案对我来说似乎都是正确的。谢谢。

标签: azure-blob-storage azure-powershell


【解决方案1】:

感谢您的建议Gaurav Mantri

解决方案 1: 首先需要将导出的 csv 文件保存在本地系统中,然后将其上传到 Azure 存储中的容器中。我在我的系统中试过了

使用Set-AzStorageBlobContent cmdlet 将此 .csv 文件上传到 Blob 存储

试试这些步骤

1) 使用 New-AzStorageContext

生成上下文
$sas_token="SAS”
$account_name = "your_storage_account_name"


$context = New-AzStorageContext -StorageAccountName $account_name -SasToken $sas_token

2) 使用 Set-AzStorageBlobContent 将 csv 文件上传到 blob 存储

Set-AzStorageBlobContent -Container "the container name" -File " file path Ex: c:\myfolder\test.csv" " -Context $context

输出

上传到 azure 容器的文件

解决方案 2: 使用 sas Url 将内容直接上传到 Azure 存储。

试试这个命令

$accountName = "storage-account-name"
$accountKey = "storage-account-key"
$containerName = "blob-container-name"
$blobName = "blob-name.csv"

# Get storage context
$context = New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $accountKey

# Get Shared Access Signature (SAS) Token expiration time. I have set it to expire after 1 hour.
$sasExpiry = (Get-Date).AddHours(1).ToUniversalTime()

# Get a SAS Token with "write" permission that will expire after one hour.
$sasToken =  New-AzStorageBlobSASToken -Context $context -Container $containerName -Blob $blobName -Permission "w" -ExpiryTime $sasExpiry

# Create a SAS URL
$sasUrl = "https://$accountName.blob.core.windows.net/$containerName/$blobName$sasToken"

# Set request headers
$headers = @{"x-ms-blob-type":"BlockBlob"}

# Set request content (body)

$body = "This is the content I wish to upload"

#Invoke "Put Blob" REST API

Invoke-RestMethod -Method "PUT" -Uri $sasUrl -Body $body -Headers $headers -Content-Type "text/csv

"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-17
    • 2021-04-25
    • 1970-01-01
    • 2020-06-25
    • 2020-10-04
    • 2020-12-30
    • 1970-01-01
    • 2019-07-07
    相关资源
    最近更新 更多