Call PowerShell from C# Azure Function Apps

Question:

I would like to run PowerShell commands in a V2 C# Azure Function App. I have tried to run PowerShell Core (which, as far as I know, is the only way I can access PS with .NET Core) from a .NET Core 2.1 Project in Visual Studio, which worked just fine, however, with a C# Azure Function App (which uses .NET Core) project I get the following error when I try to access the URL:

I have the following NuGet packages installed (for PowerShell Core):

  • Microsoft.PowerShell.Commands.Diagnostics 1.0.23
  • Microsoft.PowerShell.SDK 6.1.0
  • Microsoft.WSMan.Management 6.1.0

I could use a V1 Function App with PowerShell and get the desired functionality, but I want to know whether and how is it possible to call PowerShell from a C# Azure Function App.

Answer:

Problem is that assemblies of runtimes i.e.[FunctionProject]\bin\Debug\netcoreapp2.1\bin\runtimes folder are not loaded into function context so we see Could not load file or assembly error.

Workaround is to add those assemblies to bin i.e. [FunctionProject]\bin\Debug\netcoreapp2.1\bin folder.

Right click on your function project, Edit <FunctionProjectName>.csproj.

Add content below. First item copies assemblies to publish directory and the second copy task is for local debug.

Source:

Call PowerShell from C# Azure Function Apps by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply