Azure Functions are a great way to run PowerShell scripts on demand. However, most PowerShell scripts require access to functions in modules like Microsoft.Graph.
The default way to add PowerShell modules to an Azure Function is to specify the needed module in the requirements.psd1 file like this:
Microsoft.Graph = '2.*'
Then, each time the Azure Function starts up, the specified modules are downloaded from the PowerShell Gallery. The problem with some modules, especially Microsoft.Graph, is that they are large, and waiting for them to download and install can delay execution.
On the Consumption plan, this can take so long that the function call times out, and your function never executes. The best way to prevent this is to install the module yourself in the Azure Function image, so the download step is unnecessary.
Pre-Installing PowerShell Modules
To add modules to your Azure Function, you need to download them locally and then upload the modules for your scripts to access.
If the module is not already loaded locally, enter the following command from a PowerShell prompt:
Please respond Y to the prompts; then, the module is downloaded and stored locally. On Windows, modules are stored at: "C:\Program Files\WindowsPowerShell\Modules." On a Mac, they are stored at: "~/.local/share/powershell/Modules." To access this file path on a Mac, choose Go -> Go To Folder from the Finder menu.
Previous module versions may also be stored here, so you should delete all module folders before running the Install-Module command.
At this point, you should have one or more folders starting with the module name in your directory. Take all the folders starting with the module name and compress/zip them up into a single file.
All of your scripts in the same Azure Function can share any uploaded module. So, you'll only need to do this step once for each module for use by all of your scripts.
- Go to your Azure Function in the Azure portal, choose the "Advanced Tools" option under the "Development Tools" section, and press "Go." This opens up the Kudu environment.
- Now click the "PowerShell" option under "Debug console" menu.
- Navigate from the "site" directory to the "wwwroot" directory.
- Use the plus sign next to the folder name to create a folder under wwwroot named Modules.
- Navigate to (click on) the Modules directory.
- Drag the zip file you created above over the right side of the folders list until the drag highlighting shows up and release.
The folder will be decompressed/unzipped, and module folders will be installed in the Modules directory.
You can now use the module in your scripts without requiring an Import-Module statement.
After you've completed this step, be sure to change your requirements.psd1 file back to an empty list like this: