I was building a simple tool to automate some uploads to Azure Blob Storage in Azure Functions. Decided to use PowerShell for that, since well, sounds like a job for PowerShell!
Getting the script to work on my computer was easy, getting it to work on Azure Functions.. not that easy. I wanted to use the Azure.Storage PowerShell module and turns out you need to have a few small things right for this to work. Looking back, it would have been easier to just use built in Invoke-WebRequest to also do the uploads.
File structure from my project:
MyProj
+-- MyFunction/
| + function.json
| + run.ps1
+-- Modules/
| +-- Azure.Storage/
| +-- 4.6.1/
| + -- (lots of files)
+-- host.json
+-- requirements.psd1
The modules folder contains the external Azure.Storage module my script needs. I downloaded this using the following command. This also downlaoded the AzureRM module to the folder, but I simply removed that since this one is not needed (scroll down to see why).
Save-Module Azure.Storage -Path .\Modules
In the host.json we enable the dependency management. This allows the usage of the Az module, without including it separately in the project:
{
"version": "2.0",
"managedDependency": {
"Enabled": "true"
}
}
requirements.psd1 is simply referencing the Az module:
@{
Az = "1.*"
}
I’m using a timer to trigger the function, so function.json is straightforward. Btw, some examples omitted the “name” in the bindings, but omitting this seemed to cause errors.
{
"bindings": [
{
"name": "Timer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 0 7 * * Mon"
}
]
}
And below is an excerpt from the function itself, run.ps1. I have omitted the actual functionality. The important thing is to include the Enable-AzureRmAlias. This is needed because the automatic dependency management works with the new Az modules, while the old Azure Storage library wants to use the AzureRM modules (which I could not get to work with Azure Functions). Calling this Enable-AzureRmAlias will create aliases that point to the new Az functions.
param($Timer)
Enable-AzureRmAlias
$context = New-AzureStorageContext -ConnectionString "BlobEndPoint..."
Set-AzureStorageBlobContent -Force -Context $context -Container "MyContainer" -File myFile.txt