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

问题描述 投票:3回答:1

我现在被困在这段小代码上两天了。我有一个C#helper类来执行PowerShell脚本。我基本上使用PowerShell.Create()初始化PowerShell实例,然后使用AddScript编写命令,然后同步调用Invoke方法。

现在我正在尝试停止Windows服务和IIS应用程序池。 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();
}

当我通过ISE执行它们时,两个脚本都有效。问题是什么?我想我缺少一些关于PowerShell的东西。

c# powershell
1个回答
1
投票

你可以使用这样的东西

  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());
                }
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.