0
votes

How to to list files, delete files, write files, in an Azure blob container using Powershell and Shared Access Signature

I created a container under a blob and created a shared access signature (SAS) with full access. I want to list all *.csv files and delete them first and then loop through all of our subscriptions and generate usage info with below line

Get-AzConsumptionUsageDetail -StartDate 2019-01-01 -EndDate $EndOfYear -IncludeMeterDetails | Export-Csv -Path "$URI$Subscription.csv"

How can I list/delete all csv files in that container and also have that powershell script write the usagedetail into that container.

1

1 Answers

1
votes

You should also provide the storage account name.

Then the first step is to generate a context by using New-AzStorageContext cmdlet. The sample like below:

$sas_token="?sv=2019-12-12&ss=bfqt&srt=sco&sp=rwdlacupx&se=2021-01-21T09:46:06Z&st=2021-01-21T01:46:06Z&spr=https&sig=xxxx"

$account_name = "your_storage_account_name"

#generate the context
$context = New-AzStorageContext -StorageAccountName $account_name -SasToken $sas_token

Next, you can use Get-AzStorageBlob cmdlet to list blobs ends with .csv. The sample like below:

#list blobs
$myblobs = Get-AzStorageBlob -Container "your_container_name" -Blob *.csv -Context $context

Next, you can use Remove-AzStorageBlob cmdlet to remove these .csv blobs:

#delete these blobs
$myblobs | Remove-AzStorageBlob -Context $context

The last one, when you get the usage info by using Get-AzConsumptionUsageDetail -StartDate 2019-01-01 -EndDate $EndOfYear -IncludeMeterDetails | Export-Csv -Path "$URI$Subscription.csv", at this time, you know the path of the file Subscription.csv. Then you can use Set-AzStorageBlobContent cmdlet to upload this .csv file to blob storage:

#upload blob
Set-AzStorageBlobContent -Container "the container name" -File "the file path, like c:\myfolder\dddd.csv" -Blob "specify the blob name, like usage.csv" -Context $context