我现在被困在这段小代码上两天了。我有一个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的东西。
你可以使用这样的东西
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());
}
}
}