Install PS module into C# Azure function or app service
Cloud services make it easy to create and host your applications. But these benefits come with a cost. For instance underlying hardware is often shared between customers. This brings the cost down but on the other hand, you loose some control over your environment. This is necessary because otherwise other users could disrupt run of your application. Today I encounter a problem, where I need to create C# API, which will get results from Powershell library and return these results to the user. API is hosted as Azure app service web app and the library is published on PowerShell Gallery. I am running Powershell inside my C# code using System.Management.Automation NuGet package. First thing that comes to my mind is install the module to my runspace using command Every module published in PowerShell Gallery can also be downloaded. You can use some kind of package manager tool or do it manually. In general I like the idea of having specific tested version of the module packed with my application. After the download we ended up with package.nupkg file. But how can we integrate it into our Powershell runspace? The .nupkg filetype is nothing more than an archive. You can extract it with anything that can extract ZIP like archives. The result is shown on image bellow. Cool! Now we ended up having familiar .psd1 file, which can be easily imported into the runspace. In short to use third party powershell module in Azure app service you have to take care of its download, extract it and then import it into your session.The problem
Install-Module <module name>
. This requires administrator rights and it just doesn’t work. I don’t like the idea downloading the powershell module from gallery each time anyway.The solution
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
PowerShell powershell = PowerShell.Create();
powershell.Runspace = runspace;
powershell.Commands.AddCommand("Set-ExecutionPolicy")
.AddParameter("Scope", "Process")
.AddParameter("ExecutionPolicy", "RemoteSigned");
powershell.Invoke();
powershell.Commands.Clear();
powershell.Commands.AddCommand("Import-Module")
.AddArgument(@".\PS\ExchangeOnlineManagement.psd1");
powershell.Invoke();
powershell.Commands.Clear();
//you can use imported module now
}