Saeed Neamati
Saeed Neamati

Reputation: 35852

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

I'm stuck on this little piece of code for two days now. I have a C# helper class to execute PowerShell scripts. I basically use PowerShell.Create() to initialize an instance of PowerShell, then use AddScript to write the commands, and then call the Invoke method synchronously.

Now I'm trying to stop a windows service and an IIS application pool. The Windows service stops, but no effect on 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 execute them via ISE. What is the problem? I think I'm missing something about PowerShell.

Upvotes: 3

Views: 1211

Answers (1)

Jenish Zinzuvadiya
Jenish Zinzuvadiya

Reputation: 1085

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());
                }
            }
        }

Upvotes: 1

Related Questions