How to run a Windows executable inside Azure Functions v2


When working with automation, I came across this weird less tried around scenario which required to run a Windows executable in the scope of an Azure Function.

Here is an easy way of getting any .exe running inside your Azure Function

You may also be  interested in Run Console Apps on Azure Functions

But for the time let’s say you have an executable made by you. Here I have a console app that prints “Hello world” on console output,  which I have generated using PowerShell but of course, you can be more creative.

Add-Type -outputtype consoleapplication -outputassembly helloworld.exe 'public class helloworld{public static void Main(){System.Console.WriteLine("hello world");}}'
view raw helloWorld.ps1 hosted with ❤ by GitHub

First things first.

Create an Azure function and get the publish profile for the same, so you can publish it right away from the IDE.

Once this is done, get your executable ready.
Copy this executable to the root of your function along with dependencies (if any).

Set the “WorkingDirectoryInfo” and “ExeLocation”

string WorkingDirectoryInfo = @"D:\home\site\wwwroot\ExecFunc";
string ExeLocation = @"D:\home\site\wwwroot\helloworld.exe";

Code:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace execFuncApp
{
public static class ExecFunc
{
[FunctionName("ExecFunc")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log, ExecutionContext executionContext)
{
// you may have better ways to do this, for demonstration purpose i have chosen to keep things simple and declare varables locally.
string WorkingDirectoryInfo = @"D:\home\site\wwwroot\ExecFunc";
string ExeLocation = @"D:\home\site\wwwroot\helloworld.exe";
var msg = ""; //Final Message that is passed to function
var output = ""; //Intercepted output, Could be anything - String in this case.
try
{
//msg = $"WorkingDirectoryInfo : {WorkingDirectoryInfo} \n" +
// $"ExeLocation : {ExeLocation} \n" +
// $"FunctionDirectory: {executionContext.FunctionDirectory} \n" +
// $"FunctionAppDirectory: {executionContext.FunctionAppDirectory} ";
// Values that needs to be set before starting the process.
ProcessStartInfo info = new ProcessStartInfo
{
WorkingDirectory = WorkingDirectoryInfo,
FileName = ExeLocation,
Arguments = "",
WindowStyle = ProcessWindowStyle.Minimized,
UseShellExecute = false,
CreateNoWindow = true
};
Process proc = new Process
{
StartInfo = info
};
// Discard any information about the associated process that has been cached inside the process component.
proc.Refresh();
// for the textual output of an application to written to the System.Diagnostics.Process.StandardOutput stream.
proc.StartInfo.RedirectStandardOutput = true;
// Starts the Process, with the above configured values.
proc.Start();
// Scanning the entire stream and reading the output of application process and writing it to a local variable.
while (!proc.StandardOutput.EndOfStream)
{
output = proc.StandardOutput.ReadLine();
}
// More things that can be done with applications. 🙂
// proc.WaitForInputIdle();
// proc.WaitForExit();
msg = $"HelloWorld.exe {DateTime.Now} : HAHAHAH!, Should work! Output: {output}";
}
catch (Exception e)
{
msg = $"HelloWorld.exe {DateTime.Now} : DAMN-IT!, Failed Somewhere! Output: {e.Message}";
}
//Logging Output, you can be more creative than me.
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
log.LogInformation($"{msg}");
return (ActionResult)new OkObjectResult($"{msg}");
}
}
}
view raw execFunc.cs hosted with ❤ by GitHub

Before you publish this make sure to set the properties of your .exe and dependencies
Build Action: Embedded Resource
Copy to Output Directory: Copy Always

File Properties

Set the Build actions and Copy to output directory

Once Done, publish your Azure function using the Publish Profile.

Go to portal.azure.com and navigate to your function and open console.
make sure your artefacts are copied to the root of function.

Console Dir

Check your artefacts before you run.

You’re good to go. Run and check Output.

Output

Run and check the output.

That shall be all.
You can find the source code here.

Pingback for assistance, your Feedback’s are always a welcome… 🙂

Regards,
Aditya Deshpande

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s