简体   繁体   中英

How to call Powershell command from ASP.NET

I am using System.Management.Automation.dll to call powershell command from ASP.NET WebAPI. I am trying to start and stop windows service form ASP.NET WebAPI on demand. On my local machine it is working fine.

But when I call API to either to start or stop windows service it is giving me following error, Cannot find any service with service name 'Log Reader'.

Following command are being use,

Start-Service -Name 'Log Reader' -Verbose
Stop-Service -Name 'Log Reader' -Verbose

My code is, filename is the name of powershell command file,

      var runspace = RunspaceFactory.CreateRunspace();

            runspace.Open();
            var ps = PowerShell.Create();
            ps.Runspace = runspace;
            
            string script = GetScript(status, fileName);
            ps.Commands.AddScript(script);

            var result = ps.Invoke();
            StringBuilder sb = new StringBuilder();
            foreach (var r in result)
            {
                sb.Append(r.ToString());
                sb.Append("\n");
            }
            sb.Remove(0, sb.Length);
            foreach (var error in ps.Streams.Error.ReadAll())
            {
                sb.Append(error.ToString());
                sb.Append("\n");
            }
            runspace.Close();

Here, I am using Service Account as application pool identity.Windows service is also calling some commands using powershell and it is executed perfectly under same service account.

I think it might be related to IIS. Please help me.

There was Access right issue with app pool user.Once it is given I am able to call Windows Service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM