Adding modules to PowerShell Azure Functions may seem like a complicated task, but with these quick steps, you’ll be doing it with just a few commands.
For this example I installed the SharePointPnPPowershellOnline module onto a function that retrieves the URL for a tenant’s App Catalog.
Before you begin, you need to know which runtime version your app is running on as this will affect the directory where modules are read from. You can do this from the Function app settings page as shown in the image below.
Note: If a module doesn’t work with .Net Core, you need to use runtime 1. At the moment SharePointPnPPowerShellOnline is one such module, so if you use it on a function app with runtime 2, the commands will be recognized, but the Connect-PnPOnline command will fail.
Once you know the app’s runtime, open the PowerShell console from the Platform features page.
Installing the modules
Azure functions load anything they find stored in the ./Modules folder, but depending on the runtime, they’ll look for the folder in different places.
- For runtime 1, the folder should be located in the directory of each azure function.
- For runtime 2, the folder should be located int the /wwwroot directory to be shared by all azure functions.
Below you’ll find the commands to install modules depending on the runtime. If you’re installing more than one module, know that the first instruction needs to be run only once per console session.
Install-PackageProvider nuget -force -scope CurrentUser; mkdir ./[function folder]/Modules; save-module [module-name] -path ./[function folder]/Modules
Install-PackageProvider nuget -force -scope CurrentUser; mkdir ./Modules; save-module [module-name] -path ./Modules
Putting them to work
When you run a function, the modules in the /Modules folder will be imported automatically into the running context so there’s no need to manually import them in your scripts. Just write them assuming everything is loaded and it should work.
The example below logs into a SharePoint site and prints out the URL for the Tenant’s App Catalog. If you’ve installed the SharePointPnPPowershellOnline, you should be able to paste this into your function and see it work. If you get an error that says the cmdlets are not recognized, try restarting your app.
$sharepointSite = "https://contoso.sharepoint.com" $username = "firstname.lastname@example.org" $password = ConvertTo-SecureString "psswd from secure source" -AsPlainText -Force $psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($username, $password) Connect-PnPOnline –Url $sharepointSite -Credentials $psCred $tenantAppCat = Get-PnPTenantAppCatalogUrl Out-File -Encoding Ascii -FilePath $res -inputObject "$tenantAppCat"
With just a couple steps, you can install PowerShell modules in your azure functions. All you need to do is make sure you’re using the right folder structure for the runtime your app is running and everything should work like a charm.