Search code examples
azurepowershellazure-storage

Powershell function for modifying the ContentType of an object in Azure blob storage


I'm trying to write a function in Powershell that sets blobs in a specific container to a certain type, as they are always written with the type application/octet-stream which causes issues with downstream applications. I have written the below function but it returns the error 'ContentType' is a ReadOnly property.

I was wondering if there was any way around this? I know the property can be set manually in Azure Storage Explorer, however this is a daily task.

Function:

 Function Set-ContentType {

    Param (
        [string]$accountName,
        [string]$accessKey,
        [string]$storageContainer
    )

    # Connect to blob storage and get blobs
    $context = New-AzureStorageContext -StorageAccountName $accountName -StorageAccountKey $accessKey
    $blobs = Get-AzureStorageBlob -Container $storageContainer -Context $context -Blob $fileMask

    foreach ($blob in $blobs) {
        if ($blob.ContentType -eq $genericMIME) {
            $blob.ContentType = $targetMIME
        }
    }
 }

Solution

  • I have solved my own issue by writing an alternative upload script that defines the ContentType at the time of writing the blob:

     Function UploadFile {
    
        Param (
            [string]$accountName,
            [string]$accessKey
        )
    
        $context = New-AzureStorageContext -StorageAccountName $accountName -StorageAccountKey $accessKey
    
        $files = Get-ChildItem $workingDir -Filter $fileMask
    
        foreach ($file in $files) {
            Set-AzureStorageBlobContent -File $file.FullName -Container $container -Properties @{"ContentType" = "$targetMIME"} -Context $context -Force
        }
     }