Basically, I want to execute AZURE CLI command from my C# Azure function which is running in Linux environment.
I am currently taking approach of executing this command through running powershell script from C#.
I have tried PowerShell.Core which is cross platform version.
If I include Microsoft.PowerShell.Commands.Diagnostics and System.Management.Automation than it is able to initiate PowerShell instance but it requires PowerShell.SDK that is PowerShell runtime to be included.
If it is included than it works locally in windows but in Azure with Linux environment, it can not understand it. It gives 404 not found error for function.
Sample 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.Collections.ObjectModel;
using System.Management.Automation;
using System.Threading;
namespace FunctionApp1
{
public static class FunctionApp1
{
static ILogger logger;
[FunctionName("FunctionApp1")]
public static ActionResult Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
logger = log;
log.LogInformation("C# HTTP trigger function processed a request.");
try
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("az --version");
log.LogInformation("PowerShell instance created.");
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
outputCollection.DataAdded += outputCollection_DataAdded;
PowerShellInstance.Streams.Error.DataAdded += Error_DataAdded;
IAsyncResult result = PowerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
while (result.IsCompleted == false)
{
log.LogInformation("Waiting for pipeline to finish...");
Thread.Sleep(1000);
}
log.LogInformation("Execution has stopped. The pipeline state: " + PowerShellInstance.InvocationStateInfo.State);
foreach (PSObject outputItem in outputCollection)
{
log.LogInformation(outputItem.BaseObject.ToString());
}
}
log.LogInformation("execution completed.");
}
catch (Exception ex)
{
log.LogInformation("Error occured");
log.LogError(ex.Message + ex.StackTrace);
}
finally
{
log.LogInformation("finally block completed.");
}
return new OkObjectResult("Success");
}
static void outputCollection_DataAdded(object sender, DataAddedEventArgs e)
{
logger.LogInformation("Object added to output.");
}
static void Error_DataAdded(object sender, DataAddedEventArgs e)
{
logger.LogInformation("An error was written to the Error stream!");
Collection<ErrorRecord> error = ((System.Management.Automation.PSDataCollection<System.Management.Automation.ErrorRecord>)sender).ReadAll();
foreach (var item in error)
{
logger.LogInformation(item.ToString());
}
}
}
}