locked
REST API that will run powershell script RRS feed

  • Question

  • User1548996622 posted

    Hello,

    I want fine some example rest api code that can run powershell script and return result in json format to client.

    1. Client will send post request to API.
    2. API must run powershell script, put payload as script parameter
    3. Script will return answer to API
    4. API will return answer to client

    I already have this API and it work`s grate :) one guy made it for a specific task

    For example it able to help me integrate Active Directory for sync users from custom database. Other way I can use this API for receive json requests from scripts from clients side and transfer them to elastic search api. Or can do anything else, like collect data, analyze received information or return answers to client scripts.

    But this api using node.js and java it complicates deployment.
    And I want to try do the same API with ASP.NET. Is it possible? :)
    Or is it too hard to work at once

    Tuesday, July 28, 2020 6:32 PM

Answers

  • User1686398519 posted

    Hi Den Pasternak,

    It is possible to run powershell script in ASP .NET WebAPI.I made an example, you can refer to it.

    • You need to install System.Management.Automation through Nuget.

    HomeController

        public class HomeController : Controller
        {
            public async Task<ActionResult> requestApitestAsync()
            {
                using (var client = new HttpClient())
                {
                    string url = "https://localhost:44307/api/ApiTest";
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    //GET Method  
                    HttpResponseMessage response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        var test = await response.Content.ReadAsStringAsync();
                        dynamic json = JsonConvert.DeserializeObject(test);
                    }
                }
                return View();
            }
    }

    ApiTestController

        public class ApiTestController : ApiController
        {
            public string Get()
            {
                string scriptText = "(Get-UICulture).Calendar | ConvertTo-Json";
                var result=RunScript(scriptText);
                return result;
            }
            private string RunScript(string scriptText)
            {
                Runspace runspace = RunspaceFactory.CreateRunspace();// create Powershell runspace
                runspace.Open();// open it
                Pipeline pipeline = runspace.CreatePipeline();// create a pipeline and feed it the script text
                pipeline.Commands.AddScript(scriptText);// execute the script
                pipeline.Commands.Add("Out-String");
                var results = pipeline.Invoke();
                runspace.Close();// close the runspace
                StringBuilder stringBuilder = new StringBuilder(); // convert the script result into a single string
                foreach (PSObject obj in results)
                {
                    stringBuilder.AppendLine(obj.ToString());
                }
                return stringBuilder.ToString();
            }
    }

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 29, 2020 3:05 AM

All replies

  • User1686398519 posted

    Hi Den Pasternak,

    It is possible to run powershell script in ASP .NET WebAPI.I made an example, you can refer to it.

    • You need to install System.Management.Automation through Nuget.

    HomeController

        public class HomeController : Controller
        {
            public async Task<ActionResult> requestApitestAsync()
            {
                using (var client = new HttpClient())
                {
                    string url = "https://localhost:44307/api/ApiTest";
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    //GET Method  
                    HttpResponseMessage response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        var test = await response.Content.ReadAsStringAsync();
                        dynamic json = JsonConvert.DeserializeObject(test);
                    }
                }
                return View();
            }
    }

    ApiTestController

        public class ApiTestController : ApiController
        {
            public string Get()
            {
                string scriptText = "(Get-UICulture).Calendar | ConvertTo-Json";
                var result=RunScript(scriptText);
                return result;
            }
            private string RunScript(string scriptText)
            {
                Runspace runspace = RunspaceFactory.CreateRunspace();// create Powershell runspace
                runspace.Open();// open it
                Pipeline pipeline = runspace.CreatePipeline();// create a pipeline and feed it the script text
                pipeline.Commands.AddScript(scriptText);// execute the script
                pipeline.Commands.Add("Out-String");
                var results = pipeline.Invoke();
                runspace.Close();// close the runspace
                StringBuilder stringBuilder = new StringBuilder(); // convert the script result into a single string
                foreach (PSObject obj in results)
                {
                    stringBuilder.AppendLine(obj.ToString());
                }
                return stringBuilder.ToString();
            }
    }

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 29, 2020 3:05 AM
  • User1548996622 posted

    Wow! I did not expect such attention to my question. 

    Thank you :)

    Wednesday, July 29, 2020 3:15 AM