Search code examples
azure-blob-storageazure-powershell

How to Dynamically write a export CSV file to Azure blob container using PowerShell?


I have an Azure Powershell command that exports VM Metric information.

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

$blobpath I have given as a SAS URL of the blob Container.

I want to add the blobpath for the -Path parameter but getting the error "Can not find drive".

Cannot find drive error


Solution

  • Thanks for your suggestion Gaurav Mantri

    Solution 1: First you need to save the exported csv file in local system then you need to upload it to container in azure storage. I tried it in my system

    Use Set-AzStorageBlobContent cmdlet to upload this .csv file to blob storage

    Try with these steps

    1) generate a context by using New-AzStorageContext

    $sas_token="SAS”
    $account_name = "your_storage_account_name"
    
    
    $context = New-AzStorageContext -StorageAccountName $account_name -SasToken $sas_token
    

    2) use Set-AzStorageBlobContent to upload csv file to blob storage

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

    OUTPUT

    enter image description here

    The file uploaded to azure container

    enter image description here

    Solution 2: Upload the content directly to Azure storage by using sas Url.

    Try with this commands

    $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. e.g. set 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 -ContentType "text/csv"
    

    "