简体   繁体   English

从C#运行的PowerShell启动/停止IIS应用程序池无效

[英]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. 我有一个C#helper类来执行PowerShell脚本。 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. 我基本上使用PowerShell.Create()初始化PowerShell实例,然后使用AddScript编写命令,然后同步Invoke方法。

Now I'm trying to stop a windows service and an IIS application pool. 现在我正在尝试停止Windows服务和IIS应用程序池。 The Windows service stops, but no effect on IIS application pool. Windows服务停止,但对IIS应用程序池没有影响。

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. 当我通过ISE执行它们时,两个脚本都有效。 What is the problem? 问题是什么? I think I'm missing something about PowerShell. 我想我缺少一些关于PowerShell的东西。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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