0

I am trying to convert .CSV file to .ZIP using Powershell and then store the ZIP file in Azure blob storage.

Invoke-Sqlcmd -ServerInstance $SvrName -Database $dataname -Username $UserName -Password $Password -Query $getTABLEdetails | Export-CSV $filename1 -Append -NoTypeInformation

With the above command I am storing the output in .CSV file. Now I want to convert the .CSV file .ZIP file. And store the ZIP file in Azure blob storage.

$context = New-AzureStorageContext -StorageAccountName 'Accountname' -StorageAccountKey 'storagekey'
Set-AzureStorageBlobContent -Container zipfiles -File $filename1 -Blob $filename1 -Context $context -Force 

With the above command I can store it in .CSV file. But I want to store the file in .ZIP format.

Is their any way I can achieve this?

Please help

Baxy
  • 139
  • 1
  • 13
  • You can use [`Compress-Archive`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.archive/compress-archive?view=powershell-5.1). – Ash May 19 '20 at 21:50

1 Answers1

1

Use Compress-Archive to place your CSV file in a ZIP archive file before uploading to Blob storage.

To extract the filename from the CSV file, I use -LeafBase from Split-Path, then format this filename into a ZIP file path using the Format operator -f. Could also just concatenate with (Split-Path -Path $csvFile -LeafBase) + '.zip'.

$storageAccountName = 'Accountname'
$storageAccountKey = 'storagekey'
$containerName = 'zipfiles'

$csvFile = 'data.csv'

# Format into data.zip
$zipFile = '{0}.zip' -f (Split-Path -Path $csvFile -LeafBase)

# Create archive file
# Use -Update to overwrite if necessary
Compress-Archive -Path $csvFile -DestinationPath $zipFile -Update

# Get current storage account context
$context = New-AzureStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey

# Upload .zip file to Blob storage container
# Use -Force to skip prompts
Set-AzureStorageBlobContent -Container $containerName -Blob $zipFile -File $zipFile -Context $context -Force

To use the newer Az modules, we can replace New-AzureStorageContext with New-AzStorageContext and Set-AzureStorageBlobContent with Set-AzStorageBlobContent.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75