PowerShell starts from C # to start / stop IIS application pools has no effect

I have been stuck on this little piece of code for two days. I have a C # helper class for executing PowerShell scripts. I mainly use PowerShell.Create()

to initialize a PowerShell instance, then use AddScript

to write commands, and then call the method Invoke

synchronously.

Now I am trying to stop Windows Service and IIS Application Pool. The Windows service stops but does not affect the IIS application pool.

using (var powerShell = PowerShell.Create())
{
    // PowerShell doesn't stop application pool
    powerShell.AddScript("Stop-WebAppPool -Name application_name");

    // But it stops windows service
    powerShell.AddScript("Stop-Service service_name");

    var result = powerShell.Invoke();
}

      

Both scripts work when I run them through ISE. What is the problem? I think I am missing something in PowerShell.

+3


source to share


1 answer


You can use something like this



  using (PowerShell shell = PowerShell.Create())
        {
            shell.AddScript(@"Import-Module WebAdministration;");
            shell.AddScript(@"Stop-Website -Name 'Default Web Site';");
            shell.AddScript(@"Stop-WebAppPool -Name 'DefaultAppPool';");
            shell.Invoke();

            if (shell.HadErrors)
            {
                foreach (ErrorRecord _ErrorRecord in shell.Streams.Error)
                {
                    Console.WriteLine(_ErrorRecord.ToString());
                }
            }
        }

      

+1


source







All Articles