[RESOLVED]Running powershell from asp. web project MVC

hi,

I’m running powershell from my mvc project but i cannot get any results from the powershell session. as its a web project, is it possible to get the entire results once the script has executed? Also, when running Powershell task against loads of servers,
it just doesn’t seem to do every server. 

any help would be greatly appreciated. Hopefully i have posted enough of the code below.

using ServiceMonitor.DAL;
using ServiceMonitor.Enums;
using ServiceMonitor.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;

namespace ServiceMonitor.Controllers
{
    public class PowershellServerGroupTasksController : Controller
    {

        // load database entities
        public WRE_powershell_DBEntities db = new WRE_powershell_DBEntities();

        public class ResultsModelServergroup
        {
            public string ServerName { get; set; }
            public string TaskName { get; set; }
            public string Result { get; set; }
        }

      


        //
        // GET: /PowershellServerGroupTasks/

        public ActionResult Index(int id)
        {
            var serverGroup = db.ServerGroups.Find(id);

            var service = db.Services.Find(id);

           // var country = db.Countries.Find(id);

            var taske = db.Tasks.Where(t => t.Task_ID == (int)TaskEnum.StartService || t.Task_ID == (int)TaskEnum.StopService || t.Task_ID == (int)TaskEnum.RebootServer || t.Task_ID == (int)TaskEnum.RestartServices);


            ViewBag.ServerGroupLabel = serverGroup.ServerGroup1; //+ " (" + serverGroup.ServerGroupId + ")";
           

            ViewBag.Servers = serverGroup.Servers;

            
            ViewBag.ServergroupId = id;
            ViewBag.Servergroup = serverGroup.ServerGroup1;

            return View(taske);
        }

        [HttpGet]
        public ActionResult RunServerGroupTask(int taskId, int servergroupId)
        {




            //var country = db.Countries.Find(countryid);

            var serverGroup = db.ServerGroups.Find(servergroupId);



            ViewBag.ServerGroupLabel = serverGroup.ServerGroup1;
            //var server = db.ServersGroups.Find(servergroupid);

            var task = db.Tasks.Find(taskId);

            string result = string.Empty;


            switch (taskId)
            {


                case (int)TaskEnum.RestartServices:

                    foreach (var server in serverGroup.Servers)
                    {


                        // task id, service name and server name
                      PowershellHelper.RunPowershell(TaskEnum.StopService, out result, server.Service.ServiceName, server.ServerName);

                    }


                    foreach (var server in serverGroup.Servers)
                    {
                        // task id, service name and server name
                        PowershellHelper.RunPowershell(TaskEnum.StartService, out result, server.Service.ServiceName, server.ServerName);

                      
                    }
                    break;
                case (int)TaskEnum.StartService:
                    foreach (var server in serverGroup.Servers)
                    {

                        // task id, service name and server name
                         PowershellHelper.RunPowershell(TaskEnum.StartService, out result, server.Service.ServiceName, server.ServerName);
                     
                    }

                    break;
                case (int)TaskEnum.RebootServer:
                    foreach (var server in serverGroup.Servers)
                    {

                         PowershellHelper.RunPowershell(TaskEnum.RebootServer, out result, server.ServerName);
                       
                    }
                    break;
                case (int)TaskEnum.StopService:
                    foreach (var server in serverGroup.Servers)
                    {

                        PowershellHelper.RunPowershell(TaskEnum.StopService, out result, server.Service.ServiceName, server.ServerName);
                      
                    }
                    break;
            }





            var model = new ResultsModelServergroup { ServerName = serverGroup.ServerGroupId.ToString(), TaskName = task.TaskName, Result = result };
            //return RedirectToAction("Index", new { id = server.ServerId });


            return View(model);



        }

    }



}


using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServiceMonitor.DAL;

namespace ServiceMonitor.Controllers
{
    public class ServerGroupsTasksQueueController : Controller
    {
        private WRE_powershell_DBEntities db = new WRE_powershell_DBEntities();

        //
        // GET: /ServerGroupsTasksQueue/

        public ActionResult Index()
        {
            var servergroupstaskqueues = db.ServerGroupsTaskQueues.Include(s => s.Country).Include(s => s.ServerGroup).Include(s => s.Task);
            return View(servergroupstaskqueues.ToList());
        }

        //
        // GET: /ServerGroupsTasksQueue/Details/5

        public ActionResult Details(int id = 0)
        {
            ServerGroupsTaskQueue servergroupstaskqueue = db.ServerGroupsTaskQueues.Find(id);
            if (servergroupstaskqueue == null)
            {
                return HttpNotFound();
            }
            return View(servergroupstaskqueue);
        }

        //
        // GET: /ServerGroupsTasksQueue/Create

        public ActionResult Create()
        {
            ViewBag.ServerGroupCountry_ID = new SelectList(db.Countries, "CountryId", "CountryName");
            ViewBag.ServerGroup_ID = new SelectList(db.ServerGroups, "ServerGroupId", "ServerGroup1");
            ViewBag.Task_ID = new SelectList(db.Tasks, "Task_ID", "TaskName");
            return View();
        }

        //
        // POST: /ServerGroupsTasksQueue/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(ServerGroupsTaskQueue servergroupstaskqueue)
        {

            servergroupstaskqueue.Task_start_time = DateTime.Now;

            servergroupstaskqueue.StatusID = 5;

            
            if (ModelState.IsValid)
            {

               

                db.ServerGroupsTaskQueues.Add(servergroupstaskqueue);
                db.SaveChanges();
                return RedirectToAction("Index");
            }


            ViewBag.ServerGroupCountry_ID = new SelectList(db.Countries, "CountryId", "CountryName", servergroupstaskqueue.ServerGroupCountry_ID);
            ViewBag.ServerGroup_ID = new SelectList(db.ServerGroups, "ServerGroupId", "ServerGroup1", servergroupstaskqueue.ServerGroup_ID);
            ViewBag.Task_ID = new SelectList(db.Tasks, "Task_ID", "TaskName", servergroupstaskqueue.Task_ID);
            return View(servergroupstaskqueue);
        }

        //
        // GET: /ServerGroupsTasksQueue/Edit/5

        public ActionResult Edit(int id = 0)
        {
            ServerGroupsTaskQueue servergroupstaskqueue = db.ServerGroupsTaskQueues.Find(id);
            if (servergroupstaskqueue == null)
            {
                return HttpNotFound();
            }
            ViewBag.ServerGroupCountry_ID = new SelectList(db.Countries, "CountryId", "CountryName", servergroupstaskqueue.ServerGroupCountry_ID);
            ViewBag.ServerGroup_ID = new SelectList(db.ServerGroups, "ServerGroupId", "ServerGroup1", servergroupstaskqueue.ServerGroup_ID);
            ViewBag.Task_ID = new SelectList(db.Tasks, "Task_ID", "TaskName", servergroupstaskqueue.Task_ID);
            return View(servergroupstaskqueue);
        }

        //
        // POST: /ServerGroupsTasksQueue/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(ServerGroupsTaskQueue servergroupstaskqueue)
        {
            if (ModelState.IsValid)
            {
                db.Entry(servergroupstaskqueue).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ServerGroupCountry_ID = new SelectList(db.Countries, "CountryId", "CountryName", servergroupstaskqueue.ServerGroupCountry_ID);
            ViewBag.ServerGroup_ID = new SelectList(db.ServerGroups, "ServerGroupId", "ServerGroup1", servergroupstaskqueue.ServerGroup_ID);
            ViewBag.Task_ID = new SelectList(db.Tasks, "Task_ID", "TaskName", servergroupstaskqueue.Task_ID);
            return View(servergroupstaskqueue);
        }

        //
        // GET: /ServerGroupsTasksQueue/Delete/5

        public ActionResult Delete(int id = 0)
        {
            ServerGroupsTaskQueue servergroupstaskqueue = db.ServerGroupsTaskQueues.Find(id);
            if (servergroupstaskqueue == null)
            {
                return HttpNotFound();
            }
            return View(servergroupstaskqueue);
        }

        //
        // POST: /ServerGroupsTasksQueue/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            ServerGroupsTaskQueue servergroupstaskqueue = db.ServerGroupsTaskQueues.Find(id);
            db.ServerGroupsTaskQueues.Remove(servergroupstaskqueue);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
using ServiceMonitor.DAL;
using ServiceMonitor.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Web;
using System.Collections.ObjectModel;



namespace ServiceMonitor.Helpers
{
    public static class PowershellHelper
    {

        // object context - defined here
        public static WRE_powershell_DBEntities db = new WRE_powershell_DBEntities();


        public static bool RunPowershell(TaskEnum taskId, out string result, params string[] inputs)
        {
            var task = db.Tasks.Find((int)taskId);

            var script = String.Format(task.PowershellScript, inputs);
            result = RunScript(script);
            try
            {

             
                return true;
            }
            catch (Exception ex)
            {
               
                result = ex.Message;
                return false;

            }


        }


        private static string RunScript(string scriptText)
        {
            // create Powershell runspace

            Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it

            runspace.Open();

            // create a pipeline and feed it the script text

            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(scriptText);

            // add an extra command to transform the script
            // output objects into nicely formatted strings

            // remove this line to get the actual objects
            // that the script returns. For example, the script

            // "Get-Process" returns a collection
            // of System.Diagnostics.Process instances.

            pipeline.Commands.Add("Out-String");



            // execute the script

            var results = pipeline.Invoke();

            // close the runspace

            runspace.Close();

            // convert the script result into a single string

            StringBuilder stringBuilder = new StringBuilder();
            foreach (var obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }

            return stringBuilder.ToString();
        }

        //        // Clean the Result TextBox
        //        ResultBox.Text = string.Empty;


        //        // We use a string builder ton create our result text
        //        var builder = new StringBuilder();


        //        foreach (var obj in results)
        //        {
        //            // Convert the Base Object to a string and append it to the string builder.
        //            // Add rn for line breaks
        //            builder.Append(obj.BaseObject.ToString() + "rn");
        //        }


        //       ResultBox.Text = HtmlEncode(builder.ToString());
        //    }
        //}
    }

}

Hi jermaineg,

This issue is out of range for MVC.

For this issue, there are some links that may help you:

# Execute PowerShell from a ASP.NET Web Application

http://jeffmurr.com/blog/?p=142

# Using PowerShell in ASP.NET

http://blogs.msdn.com/b/akashb/archive/2009/01/30/howto-using-powershell-in-asp-net-net-framework-2-0.aspx

Best Regards

Starain

Leave a Reply